Writing video to File using OpenCV

Writing video to file using Opencv

In OpenCV, a video can be read either by using the feed from a camera connected to a computer or by reading a video file. The first step towards reading a video file is to create a VideoCapture object. Its argument can be either the device index or the name of the video file to be read.

After reading a video file, we can display the video frame by frame. A frame of a video is simply an image and we display each frame the same way we display images, i.e., we use the function imshow().

After we are done with capturing and processing the video frame by frame, the next step we would want to do is to save the video using the imwrite() function or assigning the frames to a certain file located on our disk.

In this tutorial you will learn how to write video file using OpenCV


#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main()
// 0 is the ID of the built-in laptop camera, change if you want to use other camera
VideoCapture cap(0);
//check if the file was opened properly
if (!cap.isOpened())
cout << "Capture could not be opened succesfully" << endl;
return -1;
// Get size of frames
Size S = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH), (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
// Make a video writer object and initialize it at 30 FPS
VideoWriter put("c://test//output.mpg", CV_FOURCC('M', 'P', 'E', 'G'), 30, S);
if (!put.isOpened())
cout << "File could not be created for writing. Check permissions" << endl;
return -1;

// Play the video in a loop till it ends
while (char(waitKey(1)) != 'q' && cap.isOpened())
Mat frame;
cap >> frame;
// Check if the video is over
if (frame.empty())
cout << "Video over" << endl;
imshow("Video", frame);
put << frame;
return 0;


ww-500x150 Writing video to File using OpenCV


life2coding_icon [] Writing video to File using OpenCV

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.