Convert a byte arry to OpenCV image in C++

27,638

Solution 1

the previously mentioned method will work fine, if it's PIXEL data.

if instead, you have a whole jpg FILE in memory, headers, compression, and all, it won't work.

in that case you want:

Mat img = imdecode(data);

which will do the same as imread(), only from memory, not from a filename

Solution 2

as @bob mention, this can be done using the Mat constructor.

byte *data;
cv::Mat imageWithData = cv::Mat(sizeOfData, 1, CV_8U, data).clone();

After you have created this matrix, call the reshape function with the number of rows in the image.

cv::Mat reshapedImage = imageWithData.reshape(0, numberOfRows);

Solution 3

cv::Mat GetImageFromMemory(uchar* image, int length, int flag)
    {
        std::vector<uchar> data = std::vector<uchar>(image, image + length);
        cv::Mat ImMat = imdecode(data, flag);

        return ImMat;
    }

the parameter "flag" refers to the type of image, grayscale, color, any depht .. that has opencv defined

Solution 4

Using cv::Mat1b is alot more efficiant and will not copy the memory 2 times more then needed

cv::Mat GetImageFromMemory(uchar* image, int length, int flag)
{
   cv::Mat1b data(1, length, image));
    return  imdecode(data, flag);
}
Share:
27,638
sparkFinder
Author by

sparkFinder

Updated on November 23, 2021

Comments

  • sparkFinder
    sparkFinder over 2 years

    I have a byte array that represents a .jpg file that I want to convert directly to an OpenCV Mat object.

    I have something like

    byte* data; // Represents a JPG that I don't want to disk and then read.
    // What goes here to end up with the following line?
    cv::Mat* image_representing_the_data;
    
    • Kamyar Infinity
      Kamyar Infinity over 11 years
      So you mean data is the compressed-byte-stream of a JPG image file?
    • Sassa
      Sassa over 11 years
      Have you tried cv::Mat image_representing_the_data(dataSize, 1, CV_8U, data); (and then reshaping the image)?
  • mrid
    mrid about 4 years
    We won't have to provide the image dimensions or pixel format? And how can we do the reverse ( convert a mat to byte array) ?