Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV VideoWriter won't write anything, although cvWriteToAVI does

I'm been trying to capture video from a cam and write it into an AVI file. I'm using Qt 4.8.2 with MSVC 2010 (x86) on Windows 7. I have 2 versions of the code: one using cv::Mat and the other using IplImage*. However, only the IplImage* version is working. Here's my code using cv::Mat:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;

int main() {
    VideoCapture* capture2 = new VideoCapture( CV_CAP_DSHOW );
    Size size2 = Size(640,480);
    int codec = CV_FOURCC('M', 'J', 'P', 'G');
    VideoWriter* writer2 = new VideoWriter("video.avi",codec,15,size2);

    int a = 100;
    Mat frame2;
    while ( a > 0 ) {
        capture2->read(frame2);
        writer2->write(frame2);
        a--;
    }

    writer2->release();
    capture2->release();
    return 0;
}

And here's the code using IplImage*:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

int main() {
    CvCapture* capture = cvCaptureFromCAM( CV_CAP_DSHOW );
    CvSize size = cvSize(640,480);
    int codec = CV_FOURCC('M', 'J', 'P', 'G');
    CvVideoWriter* writer = cvCreateVideoWriter("video.avi",codec,15,size);

    int a = 100;
    while ( a > 0 ) {
        IplImage* frame = cvQueryFrame( capture );
        cvWriteToAVI(writer,frame);
        a--;
    }

    cvReleaseVideoWriter(&writer);
    cvReleaseCapture( &capture );
    return 0;
}

It's basically the same, or at least it looks like the same thing to me. It reads 100 frames and should write them into "video.avi". It compiles and runs without errors, but the cv::Mat version doesn't write anything, and the IplImage* version works perfectly.

Does someone have any idea on what's going on?

like image 596
Alex Machado Avatar asked Aug 21 '12 12:08

Alex Machado


1 Answers

The syntax in Opencv C++ reference is bit different, and here is a working code in C++. I Just added imshow and waitkey, for checking you can remove them if you want.

int main()
{
    VideoCapture* capture2 = new VideoCapture(CV_CAP_DSHOW);
    Size size2 = Size(640, 480);
    int codec = CV_FOURCC('M', 'J', 'P', 'G');
    // Unlike in C, here we use an object of the class VideoWriter//
    VideoWriter writer2("video_.avi", codec, 15.0, size2, true);

    writer2.open("video_.avi", codec, 15.0, size2, true);
    if (writer2.isOpened())
    {
        int a = 100;
        Mat frame2;
        while (a > 0)
        {
            capture2->read(frame2);
            imshow("live", frame2);
            waitKey(100);
            writer2.write(frame2);
            a--;
        }
    }
    else
    {
        cout << "ERROR while opening" << endl;
    }

    // No Need to release the Writer as the distructor will called automatically
    capture2->release();

    return 0;
}
like image 151
G453 Avatar answered Sep 19 '22 19:09

G453