Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Mat to raw Image


I am having trouble writing a raw image from a Mat. I am using OpenCV 2.3.1. I have seen plenty of replies for the inverse operation (raw to Mat) but not Mat to raw. I am not even sure it is possible the way I do it since no headers are set.

The following code opens a video, and saves the 10 first frames into files. When I try to open those file with XNview (for example), I get a black and striped image. Clearly not the expected image. The .raw file starts with plenty of 00 00 00 00 before the real content. I cannot figure out what I am missing. DO I need to add headers ?

Thanks a lot in advance

Here is the code :

int main( int argc , char *argv[] )
  unsigned long lFrameId = 0;

  // open video file
  string mediaPath = "/home/videos/film.mp4";
  VideoCapture captureV;
  Mat frame;;

   if( !captureV.isOpened() )
     cerr << "capture error" << endl;

  // set media parameters
  captureV.set(CV_CAP_PROP_CONVERT_RGB, true);

  while (lFrameId < 10

    int rows = frame.rows;      // 880)
    int cols = frame.cols;      // 720
    uchar* buffer =; // 8-bit pixel

    // Write frame data into raw file
    ostringstream filename;
    filename << "Frame_" << lFrameId << ".raw";
    std::ofstream outfile (filename.str().c_str(), ios::out | ios::binary);
    outfile.write ((char*)(buffer),;  // In byte so should be enough ?


  return 0;