使用OpenCV将视频写入文件

时间:2015-01-12 17:34:40

标签: c++ opencv video

您好我正试图从我的网络摄像头写一个视频到我的电脑,但我一直收到我的作家没有打开的错误。我使用Windows 8 64位,VS 2013& OpenCV 2.4.10。这是我正在使用的代码:

#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <iostream>

using namespace cv;
using namespace std;

string intToString(int number){


    std::stringstream ss;
    ss << number;
    return ss.str();
}

int main(int argc, char* argv[])
{

    VideoCapture cap(0); // open the video camera no. 0

    VideoWriter writer;

    if (!cap.isOpened())  // if not success, exit program
    {
        cout << "ERROR INITIALIZING VIDEO CAPTURE" << endl;
        return -1;
    }

    char* windowName = "Webcam Feed";
    namedWindow(windowName, CV_WINDOW_AUTOSIZE); //create a window to display our webcam feed

    string filename = "C:\\thevideo.avi";
    int fcc = CV_FOURCC('D', 'I', 'V', '3');
    double fps = 20;
    cv::Size frameSize(cap.get(CV_CAP_PROP_FRAME_WIDTH), cap.get(CV_CAP_PROP_FRAME_HEIGHT));

    writer = VideoWriter(filename, fcc, fps, frameSize);

    if (!writer.isOpened())
    {

        cout << "the writer isnt opened" << endl;
        getchar();
        return -1;
    }




    while (1) {
        Mat frame;

        bool bSuccess = cap.read(frame); // read a new frame from camera feed

        if (!bSuccess) //test if frame successfully read
        {
            cout << "ERROR READING FRAME FROM CAMERA FEED" << endl;
            break;
        }

        writer.write(frame);

        imshow(windowName, frame); //show the frame in "MyVideo" window

        //listen for 10ms for a key to be pressed
        switch (waitKey(10)){

        case 27:
            //'esc' has been pressed (ASCII value for 'esc' is 27)
            //exit program.
            return 0;

        }


    }

    return 0;

}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

我发现使用有点令人困惑。你这样做:

VideoWriter writer;

然后

writer = VideoWriter(filename, fcc, fps, frameSize);

要么:

VideoWriter writer = VideoWriter(filename, fcc, fps, frameSize);

VideoWriter writer;
writer.open(filename, 0, fps, frameSize, 1);

也许这就是问题?

另外,在writer.open()中,最后一个参数是颜色设置。相应地设置它。我假设你有颜色输入。

此外,更复杂的事情可能是编解码器问题。我读过OPENCV只能写AVI文件。所以,我不确定它是否可以使用DIV3编解码器进行编写。用以下方式打电话给作者:

writer = VideoWriter(filename, -1, fps, frameSize);

并查看可以使用的编解码器。

答案 1 :(得分:0)

试试这个编解码器:

  

int fcc = CV_FOURCC(&#39; M&#39;,&#39; J&#39;,&#39; P&#39;,&#39; G&#39;)

而不是:

  

int fcc = CV_FOURCC(&#39; D&#39;,&#39;我&#39;,&#39; V&#39;,&#39; 3&#39;);