Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OpenCV-VideoWriter can not write *.mp4 with C++ ?

Hi there,

My name is Toan. I have a really strange issue. In Python, I able to write video with both *.avi (MJPG) and *.mp4 (DIVX). But in C++, I can only write video with *.avi (MJPG). I tried to write *.mp4 video with many codec "DIVX", "XVID", "H264", "MP4V",...etc... but output is still empty. When compile the program has no any error. I refer some materials and articles, It's may concern about FFMPEG library and I installed OpenCV contains FFMPEG as 3rdparty. But I don't know how to fix this.

This is my code:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <opencv2/videoio.hpp>
using namespace cv; using namespace std;

int main()
{
    cout << "Built with OpenCV " << CV_VERSION << endl;
    Mat image;
    Mat src;
    VideoCapture capture;
    capture.open(1 + cv::CAP_V4L2);
capture >> src;
bool isColor = (src.type() == CV_8UC3);
VideoWriter writer;
int codec = VideoWriter::fourcc('H', '2', '6', '4'); 
double fps = 10.0;     
Size sizeFrame(640,480);
string pipeline = "appsrc ! videoconvert ! avenc_h264 ! matroskamux ! filesink location=test.mp4";
writer.open("front.mp4", codec, fps, sizeFrame, isColor);
cout << "Started writing video... " << endl;
Mat xframe;
    for (int i = 0 ; i < 100 ; i ++)
{
    capture >> image;
    resize(image,xframe,sizeFrame);
    writer.write(xframe);
}
cout << "Write complete !" << endl;
capture.release();
writer.release();
return 0;
}

So what should I do now ?

Thank you so much,

Toan