I need to implement a function that receives a string containing the bytes of an image (received via boost socket connection) and converts the info into an OpenCV cv::Mat.
I also know the width and height of the image and its size in bytes. My function looks like this:
void createImageFromBytes(const std::string& name, std::pair<int,int> dimensions, const std::string& data)
{
int width,height;
width = dimensions.first;
height = dimensions.second;
//convert data to cv::Mat image
std::string filepng = DATA_PATH"/" + name +".png";
imwrite(filepng, image);
}
Which is the best method for doing this? Does OpenCV has a constructor for Mat from a string?
Easy to trip here as the image may have null characters and any c function handling string will see null as string end
Read the image
Convert to Bytes (this is just working code, not checked for leaks)
Test and see if conversion works
If the data in the string is raw pixels (rather than a Jpeg/png etc) you can create the cv::mat directly
Here is my improved solution of Jav_Rock, the problem is that is not clear to use vector (byte type is not defined in c++, i didn't found that), instead of that, use vector, here is a example code
OpenCV Mat has a constructor from
vector<byte>
, but this is not so intuitive. You need to convert from string to vector this way first:Then you can create a cv::Mat from the vector:
You also need to decode the image (check documentation for which types are allowed, png, jpg, depending on the OpenCV version)
Now you can check if the resulting size of the image is the same as the one you sent: