Save Webcam Video to a File

Write webcam video to file:

In this example a VideoCapture object is used to capture the webcam video to frames then a VideoWriter object is used to write frames to file. The constructor of this class requires output filename, codecs, frames per second, size of frames.


#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;

int main (int argc, char *argv[])
// Open the default camera
VideoCapture capture(0);

// Check if the camera was opened
cerr << "Could not open camera";
return -1;

// Get the properties from the camera
double width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
double height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);

cout << "width = " << width << endl <<"height = "<< height << endl;

// Create a matrix to keep the retrieved frame
Mat frame;

// Create a window to show the image
namedWindow ("Window", CV_WINDOW_AUTOSIZE);

// -1 specify as the FourCC code, and a window will pop up displaying all of the available video codecs that are on your computer.

// Create the video writer

VideoWriter video("c:/capture.avi",-1, 30, Size((int)width,(int)height) );

// VideoWriter video("c:/capture.avi",CV_FOURCC('I','Y','U','V'), 30, Size((int)width,(int)height) );

// Check if the video was opened
cerr << "Could not create video.";
return -1;

cout << "Press 'q' stop recording." << endl;

// Get the next frame until the user presses the escape key
// Get frame from capture
capture >> frame;

// Check if the frame was retrieved
cerr << "Could not retrieve frame.";
return -1;

// Save frame to video
video << frame;

// Show image
imshow("Window", frame);


// Exit
return 0;


Save%2BWebcam%2BVideo%2Bto%2Ba%2BFile Save Webcam Video to a File
Write webcam video to file


life2coding_icon [] Save Webcam Video to a File

Leave a Reply

Your email address will not be published.

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