AnsweredAssumed Answered

How to write *.mp4 video with OpenCV-C++?

Question asked by Dao Van Toan on Feb 13, 2020
Latest reply on Feb 21, 2020 by Dao Van Toan

Hi NXP,

My name is Toan. Currently, I'm using OpenCV-C++ to write video *.mp4 type. I can write video .avi type but It's take a lot of storage. About 1Mb/1s with 640x480 resolution and 15 FPS. I'm using iMX6UL-EVK board(Linux).

I built without error but no output .mp4 file. And in python code (OpenCV-Python), this board can write .mp4 video with "mp4v".

I tried with "mp4v", "xvid", "divx", "h264", "x264" but not working. So what can I do now? Or may you show me others type of video which not take much of storage ?

This is my code:

#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(){   
   cout
<< "Built with OpenCV " << CV_VERSION << endl;   
   Mat image;   
   Mat src;   
   VideoCapture capture;   
   capture
.open(2);   
   capture
>> src;   
   
bool isColor = (src.type() == CV_8UC3);   
   
VideoWriter writer;   
   
int codec = VideoWriter::fourcc('M', 'P', '4', 'V');      
   
double fps = 15.0;   
   string filename
= "live.mp4";   
   Size sizeFrame(640,480);   
   writer
.open(filename, codec, fps, sizeFrame, isColor);   
   cout
<< "Started writing video... " << endl;   
   for (int i = 0 ; i < 60 ; i ++)   
   {       
      capture
>> image;       
      Mat xframe;       
      resize
(image,xframe,sizeFrame);       
      writer
.write(xframe);       
   
   }   
   cout
<< "Write complete !" << endl;   
   capture
.release();   
   writer
.release();   
   return 0;
}

Thank you so much,

Toan

Outcomes