Vector of Uchar to cv::Mat

I have an image which I am putting into a vector of uchar which I am sending from processor to processor using open mpi, however I need to put the vector of uchar into a cv::Mat.

Is there an easy way to do this?

cv::Mat image_on_proc = newpopulation(cv::Rect(0, start, population.cols, rows_in_section));
    std::vector<byte> img = matToBytes(image_on_proc);

    std::vector<uchar> test;
    for(int i=0; i<image_on_proc.rows; i++)
    {
      for(int j=0; j<image_on_proc.cols; j++)
      {
    test.push_back(image_on_proc.at<uchar>(i,j));
      }
    }

    MPI_Barrier(MPI_COMM_WORLD);

    MPI_Send(&test[0],test.size()*sizeof(uchar), MPI_BYTE, 0, 99, MPI_COMM_WORLD);

The above shows how I put the image into the vector and send it, there is a corresponding recv and it works, however I do not know how to turn it back into an image.

Answers


You can store a Mat into a vector<uchar> using:

Mat img = ...; // img must be CV_8UC1 in this example
vector<uchar> v(img.begin<uchar>(), img.end<uchar>());

and back into a Mat using:

Mat img2(img.rows, img.cols, img.type(), v.data());

Note that here you're not copying values, but just creating a Mat header for the data in v, so img2 will reflect any change done on v. If v goes out of scope, then img2 becomes invalid. You can simply use clone() to copy data, like:

Mat img3 = Mat(img.rows, img.cols, img.type(), v.data()).clone();

Need Your Help

Subfolders in App_GlobalResources (ASP.NET)

asp.net localization resources internationalization globalization

Is it possible to put resource files (.resx) within subfolders inside App_GlobalResources?

Get Section Names Programmatically from App.config C#

c# configuration config app-config

Is there a way to programmatically get the section names by doing a loop instead of hard coding the names yourself?