Reading Video

Video Capture

Here, you will learn how to set up video capture in OpenCV.

Understanding how video processing works in OpenCV is quite simple if you already understand cv2.imread(). It functions similarly to cv2.imread(), yet imagine it like a version of cv2.imread() that loops infinitely to read each individual frame.

  • to get started, run the cv2.VideoCapture() function and assign it to a variable. The argument for this function can be an integer that represents the videocamera you are using, or a video path (like an image path). For the sake of simplicity though, stick with the number 0 as it will use your default web camera.

  • Then create an infinite while loop by setting the argument of the while loop to be true.

  • Then within the loop, you will use the .read() function on your video camera variable, which will read the frames from your video camera. No arguments are required. Assign it to two variables. One will be a boolean variable and the other will be your actual frame.

  • Then use the cv2.imshow function to show each frame.

  • Then use a combination of cv2.waitkey() with an argument of 1 and get the hexadecimal value of a keypress with 0xFF==ord('d') in an if statement to say that the window will only close if the d key is pressed and that each frame will open and close according to your computer's maximum framerate, by saying the program will break if these conditions are met. (technically it should be 1000 fps since the 1 represents 1 millisecond, but it will default to the computer's maximum fps instead).

  • using the .release() function, release your capture variable as it is a pointer. when you are done.

NOTE: Remember, this video capture method will take in every frame and store it as a variable. So you can treat it as if it were an image being read and perform all of your image operations just as you have done before.

capture=cv.VideoCapture(0)


while True:

isTrue, frame =capture.read()

cv.imshow('Video',frame)


if cv.waitKey(1) & 0xFF==ord('d'):

break


capture.release()


#destroys the window


cv.destroyAllWindows


Congrats!

You have finished the OpenCV modules! Hopefully, you have a good understanding of how most of these functions work and can use them in your final project.