[opencv]5.获取视频流并保存到本地

本文的目标就是实现获取摄像头视频流并且保存到本地。
代码如下:

#include "opencv2/highgui/highgui.hpp"
#include 

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    VideoCapture cap(0); //打开摄像头

    if (!cap.isOpened())  
    {
        cout << "ERROR: Cannot open the video file" << endl;
        return -1;
    }

    namedWindow("MyVideo", CV_WINDOW_AUTOSIZE); 

    double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); 
    double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); 

    cout << "Frame Size = " << dWidth << "x" << dHeight << endl;

    Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));

    VideoWriter oVideoWriter("D:/MyVideo.avi", CV_FOURCC('P', 'I', 'M', '1'), 20, frameSize, true); //视频保存
    //  其他格式:
    //  CV_FOURCC('D', 'I', 'V', '3') for DivX MPEG - 4 codec
    //  CV_FOURCC('M', 'P', '4', '2') for MPEG - 4 codec
    //  CV_FOURCC('D', 'I', 'V', 'X') for DivX codec
    //  CV_FOURCC('P', 'I', 'M', '1') for MPEG - 1 codec
    //  CV_FOURCC('I', '2', '6', '3') for ITU H.263 codec
    //  CV_FOURCC('M', 'P', 'E', 'G') for MPEG - 1 codec
    if (!oVideoWriter.isOpened()) 
    {
        cout << "ERROR: Failed to write the video" << endl;
        return -1;
    }

    while (1)
    {

        Mat frame;

        bool bSuccess = cap.read(frame); 

        if (!bSuccess) 
        {
            cout << "ERROR: Cannot read a frame from video file" << endl;
            break;
        }

        oVideoWriter.write(frame); //读一帧,写一帧

        imshow("MyVideo", frame); 

        if (waitKey(10) == 27) 
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }
    }

    return 0;

}

你可能感兴趣的:(opencv)