In this tutorial we’re going to see how to load the video from it’s source whether it’s a webcam or a video file.
The process is relatively simple. After we import the libraries cv2 and numpy, we need to define the cap object.

To load the frames from the webcam:

  • cap = cv2.VideoCapture(0)

The number 0 it means the first webcam. If you have more webcam installed, you can change the number to 1 take second or to 2 for thirt webcam and so on.

To load the frames from a video file we use the same function but instead of passing a number as argument, we pass the file title (if the file it’s in the same folder of the python script) like in example 1 or the entire path if it’s on another folder like in example 2:

  1. cap = cv2.VideoCapture("video_file.mp4")
  2. cap = cv2.VideoCapture(r"C:\Users\MYUSER\Documents\video_file.mp4")

*Please note the prefix “r” before the string. The r must be used to avoid that escape character are interpredet according to the python rules.

 

Working with the video frames:

A video is just a sequence of images, so keeping this in mind, we need to operate with the images.
To work with videos we work inside a while loop, there we extract the frames and do all the operations.

After creating the object cap, we need to call it to read the frames wheter it’s from a video file or from the webcam.

  • ret, frame = cap.read()

Ret is just equal to True or False. It’s true if cap is reading a frame, and frame is the the array containing the image.

Then there we show it using cv2.imshow like we did for the images.

And we have the function waitkey:

  • key = cv2.waitKey(25)

This function is literally waiting for us to press a key. Each key that we press on the keyboard is associated to a number.
Thanks to this we can do any operation we want pressing some key.
For example we decide that when we press the “Esc” key on the keyboard, we want to close it. The esc key correspond to the number “27” and after that we break the loop so it stops the executions.

 

Read from Webcam

Read from File

Read video from file and Save it to file

Files:

1) red_panda_snow.mp4