(OpenCV, data type change, copy) vector to Mat, Mat to vector

This post is about how to copy Mat data to vector and copy vector data to Mat.
Reference this example source code.

 printf("//vector to Mat\n");
 int r=3;
 int c=4;

 vector< float> Vf;

 //insert value
 int cnt=0;
 for(int i=0; i< c; ++i) 
  for(int j=0; j< r; ++j)  
 //create Mat
 Mat M=Mat(r,c,CV_32FC1);
 //copy vector to mat

 //print Mat
 cout < <  M < <  endl;

 printf("//Mat to vector\n");
 vector< float> Vf2;
 //copy mat to vector
 Vf2.assign((float*)M.datastart, (float*)M.dataend);
 for(int i=0; i< c; ++i)
  for(int j=0; j< r; ++j)  
   printf("%lf ", Vf2[cnt++]);


You want to copy image buffer to Mat example source code.
Reference on this page -> http://feelmare.blogspot.kr/2014/01/opencv-mat-class-image-bufferpoint-copy.html


  1. thanks a lot! :)

  2. This comment has been removed by the author.

  3. I tryed to use this solution in my code but it crash, I tryed the same code shown above and it crash too, I think it is because the memcpy. Any idea?

    1. Does the length of the data was entered correctly in memcpy param 3rd?
      on line 15, CV_32FC1 means 32bit float and 1 channel.
      Thank you.

  4. The data are the same that you used. I copy&paste your code.

  5. Anonymous5/4/16 02:55

    For people who have problems with this code to copy a vector to a mat, you can also use this:

    vector oOutput; // fill this with data
    int iHeight = 5;
    int iWidth = 4;

    Mat oRealOutput;

    oRealOutput = Mat(iHeight, iWidth, CV_64F);

    int k = 0;
    for (int i = 0; i< oRealOutput.rows; ++i)
    for (int j = 0; j< oRealOutput.cols; ++j)
    oRealOutput.at< double >(i, j) = oOutput[k];
    k = k + 1;

    1. Thank you for answer.
      May be, this problem is 64 and 32bit problem.
      If your build option is 64bit, than you use CV_64.
      otherwise your build option is 32bit, than you use like sample code.

      I think that.

      Thank you

  6. The Vector doesnt have any attributes "assign"


Post a Comment

Popular posts from this blog

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

OpenCV Stitching example (Stitcher class, Panorama)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Real-time N camera stitching Class.

Optical Flow sample source code using OpenCV

OpenCV Drawing Example, (line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours)

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

SICK LMS511 sensor data acquisition interface (source code, C++/MFC)

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Image warping (using opencv findHomography, warpPerspective)