Capture Video using OpenCV

This section explains how to read and display videos using OpenCV. OpenCV provides VideoCapture object for reading and writing videos. We can also use VideoCapture object to capture images from camera as well. The constructor can be used to read a video by providing a string path of the video to read. We can also provide the integer value indicating the camera index to capture the camera.

Let us look at an example to read a video file and display the frames one by one. Normally, the video frames are display at 25 FPS, which means 25 frames are displayed in one second. In this example, we will need to handle it manually by using waitKey() method of OpenCV. It will give an impression of playing the video at the original frame rate. The following code reads a video and displays the frames one by one:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import cv2
path = r'F:\img\videos\news.mp4'
video = cv2.VideoCapture(path)
frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
count=0;
try:
    while video.isOpened():
        _, frame = video.read()
        if frame is None :
            raise Exception("Finished reading vdieo/unable to read.")
        count+=1
        cv2.putText(frame,str(count)+'/'+ str(frames),(20,20),cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,.5,(0,0,255),2)
        cv.imshow('frame', frame)
        if cv.waitKey(30) == 27:
            break
except Exception as ex:
    print("An exception occrued.",ex.args )
finally:
    print("Destorying the VideoCapture Object")
    video.release()
    cv.destroyAllWindows()


Line 2,3: We start with importing required packages.
Line 4: Provide the path of the video files.
Line 5: We get the total number of frames in the video.
Line 6: This line creates the object of VideoCapture class. We passed path as parameter to its constructor, which means it will be reading the frames from video.
Line 7: try-except and finally blocks are used to handle exceptions. If anything goes wrong while reading and displaying video frames, the program will not crash.
Line 8: We use a while loop to read all the frames in the video. We make sure that video object is initialized it properly and is ready to read. This is checked using video.isOpened() in the while loop condition.
Line 9: The read() function actually reads the frames from the video. It returns two values. The first one is a Boolean value indicating whether the frame is read correctly or not. The second parameter is the actually the video frame.
Line 10,11: We make sure the the frame is correctly read, otherwise we throw and exception and stop reading the video.
Line 12: We increase the counter when each frame is read.
Line 13: We write the current frame number and total number of frames read on the frame.
Line 14: It displays the video frame.
Line 15: Put a delay of 30 miliseconds and if user presses the escape key, the video reading is stopped.
Line 19-22: This is the finally block. This will execute everytime the program execution stops. We release the VideoCapture object and close all open windows.
An output frame is shown in Figure 1. Note that on top left corner, we have shown the current frame no/total number of frames.

No image
Figure 1. A sample frame captured from the video.

OpenCV Tutorials