Thursday, June 11, 2015

Save Webcam Video to a File

Posted by Md.Hanif Ali on Thursday, June 11, 2015 in | No comments

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.

Code:

#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
    if(!capture.isOpened())
    {
        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
    if(!video.isOpened())
    {
        cerr << "Could not create video.";
        return -1;
    }

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

    // Get the next frame until the user presses the escape key
    while(char(waitKey(1))!='q')
    {
        // Get frame from capture
        capture >> frame;

        // Check if the frame was retrieved
        if(!frame.data)
        {
            cerr << "Could not retrieve frame.";
            return -1;
        }

        // Save frame to video
        video << frame;

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


    }

    // Exit
    return 0;
}

Output:

Write webcam video to file

 

0 comments:

Post a Comment