将一串字节转换为cv :: mat [英] Convert a string of bytes to cv::mat

查看:309
本文介绍了将一串字节转换为cv :: mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个功能,接收包含图像字节的字符串(通过Boost套接字连接接收),并将信息转换 OpenCV 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);
}

哪种方法是最好的? OpenCV是否具有用于字符串的Mat的构造函数?

Which is the best method for doing this? Does OpenCV has a constructor for Mat from a string?

推荐答案

OpenCV Mat 具有vector<byte>中的构造函数,但这不是那么直观.您需要先通过这种方式将字符串从向量转换为向量:

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());

然后您可以从矢量创建cv :: Mat:

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

cv::Mat data_mat(vectordata,true);

您还需要对图像进行解码(请检查文档中允许的png,jpg类型,具体取决于OpenCV版本)

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;

这篇关于将一串字节转换为cv :: mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆