Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

opencv - Convert a string of bytes to cv::mat

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

std::vector<byte> vectordata(data.begin(),data.end());

Then you can create a cv::Mat from the vector:

cv::Mat data_mat(vectordata,true);

You also need to decode the image (check documentation for which types are allowed, png, jpg, depending on the OpenCV version)

cv::Mat image(cv::imdecode(data_mat,1)); //put 0 if you want greyscale

Now you can check if the resulting size of the image is the same as the one you sent:

cout<<"Height: " << image.rows <<" Width: "<<image.cols<<endl;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...