Click here to add content.

Reading and Writing Videos using OpenCV

Reading and writing videos in OpenCV python is no different than reading and writing images. If we break down a video into its constituent components, we get image frames, all stacked up one after the other. So, all we need to do is read or write the frames in a loop. In this blog, we will see the code explaining how to read, display and write videos from a file, image sequence, and webcam. We will also see the possible errors that might occur in the process. The main functions of OpenCV we are going to discuss are:


  1. cv2.VideoCapture – Creates a video capture object, which would help stream or display the video.
  2. cv2.VideoWriter – saves the output video to a directory
  3. In addition, we also discuss other needed functions such as the get() method to read the video’s frame height and width, cv2.imshow, and cv2.waitKey.


# Import libraries
import cv2


// Include Libraries
using namespace std;
using namespace cv;

In the above code block, we are Importing packages required for the task at hand. Please note that cv2.function() is used for python and cv::function() for C++ but we will use  the function directly as function() since we are using namespace, using namespace cv


Python Function syntax: cv2.VideoCapture(filename, flags)


# Create a video capture object, in this case we are reading the video from a file
vid_capture = cv2.VideoCapture('Resources/Cars.mp4')
C++ function syntax: VideoCapture (filename,flags);


VideoCapture vid_capture("Resources/Cars.mp4");

In the above code block VideoCapture is used to create a VideoCapture object and read from input file (video)

The syntax of VideoCapture is: VideoCapture(path, flag).

It can take two arguments, filename or path of the directory where the video is stored and video capture flags. 

You can use the video file that we have used here which is available in the Downloadable Code folder or replace it with your own video. Flags are API preferences built into the OpenCV backend. We will discuss a few flags in this article. To know more about flags, visit the official documentation link OpenCV Flags.


if (vid_capture.isOpened() == False):
	print("Error opening the video file")
	# Get frame rate information

	fps = int(vid_capture.get(5))
	print("Frame Rate : ",fps,"frames per second")	

	# Get frame count
	frame_count = vid_capture.get(7)
	print("Frame count : ", frame_count)


if (!vid_capture.isOpened())
		cout << "Error opening video stream or file" << endl;
            // Obtain fps and frame count by get() method and print
		int fps = vid_capture.get(5):
		cout << "Frames per second :" << fps;
		frame_count = vid_capture.get(7);
		cout << "Frame count :" << frame_count;

The above block of code will verify if the input file is a video stream and has frames as expected.

isOpened() method returns a boolean that says whether the video stream is valid or not. Otherwise, we will get an error message.

Next, we will see the default frame rate of the video with the help of some built-in methods. Note that this method does not apply to web cameras.

Here we are acquiring frame rate and frame count information. These are very crucial metadata of the video, based on which we decide to change the frame rate. cv2.id_capture.get(5) in python or vid_capture.get(5) in C++ returns the fps. We have converted it into an integer just for simplicity. 5 is the enumeration of CAP_PROP_FPS, a flag that reads fps. Alternatively, we can also write  CAP_PROP_FPS in place of 5. Similarly, 7 is the enumeration. As you can predict, we can replace value 7 with CAP_PROP_FRAME_COUNT as well. Visit the official documentation page to know more.

Next, we will read the frames one by one, and display them accordingly.


	# vCapture.read() methods returns a tuple, first element is a bool 
	# and the second is frame

	ret, frame = vid_capture.read()
	if ret == True:
		k = cv2.waitKey(20)
		# 113 is ASCII code for q key
		if k == 113:


		// Initialise frame matrix
		Mat frame;

	    // Initialize a boolean to check if frames are there or not
		bool isSuccess = vid_capture.read(frame);

		// If frames are present, show it
		if(isSuccess == true)
			//display frames
			imshow("Frame", frame);

		// If frames are not there, close it
		if (isSuccess == false)
			cout << "Video camera is disconnected" << endl;
		//wait 20 ms between successive frames and break the loop if key q is pressed
		int k = waitKey(20);
            if (k == 113)
			cout << "Q key is pressed by the user. Stopping the video" << endl;


vid_capture.read() method returns a tuple, where the first element is a boolean. When it’s True, it indicates that there is a frame still present in the video file and we can read the frame, which is the second element of the tuple. 

cv2.waitKey(20) in Python or waitKey(20) in C++ means that it will wait for keypress for 20 milliseconds, if we press key q, the loop will break. 113 is the ASCII code for key q. For better understanding,try different values for the argument, or use a different keypress, etc.


# Release the objects


// Release video capture object

At last, we release the video capture object, and close the window when it finishes looping through all the frames.


It is a process similar to reading a video from a file.  We only need to specify the image files which are being read.


vid_capture = cv2.VideoCapture('Resources/Image_sequence/Cars%04d.jpg')


VideoCapture vid_capture("Resources/Image_sequence/Cars%04d.jpg");

In this case, we are reading the image sequence from the directory: Resources/Image_sequence. The images in the directory are saved as Cars0000.jpg, Cars0001.jpg, Cars0002.jpg, and so on. That’s why we are using %04d – four-digit numbers after the phrase. If the names were like, Animal01.jpg, Animal02.jpg, and so on, we would have used %02d, for two-digit numbers after the name phrase.


The same process and steps as discussed so far hold good for reading videos from a webcam as well. We only need to replace the directory argument with a “0”. If you have more than one camera hooked on to your system, just put “1” and so on.


vid_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)


VideoCapture vid_capture(0);

You might be wondering about the flag CAP_DSHOW. Well, it works without the flag also. But, you will notice a warning being generated, which is a bug. We hope it will be fixed within the next  release.


Now that you have understood the video reading part, let us look at the video writing part. Just like video reading, we can write videos from any source. It can be a file, an image sequence, or a webcam. Please note that it is different from the imwrite functionality of OpenCV. The workflow to save a video is:

Initialize video capture object

  • Read the frame height and width using the get() method
  • Save the output video to a directory using VideoWriter()

Now we will obtain the height and width of the frame using the get() method.

New Course – OpenCV For Beginners – NOW LIVE

Subscribe to receive the download link, receive updates, and be notified of bug fixes

Almost there! Please complete this form and click the button below to receive the download link.

Subscribe To Receive
We hate SPAM and promise to keep your email address safe.​