在 C++ 中将字节 arry 转换为 OpenCV 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12114605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a byte arry to OpenCV image in C++
提问by sparkFinder
I have a byte array that represents a .jpg file that I want to convert directly to an OpenCV Mat object.
我有一个字节数组,它表示我想直接转换为 OpenCV Mat 对象的 .jpg 文件。
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;
回答by berak
the previously mentioned method will work fine, if it's PIXEL data.
如果是 PIXEL 数据,则前面提到的方法可以正常工作。
if instead, you have a whole jpg FILE in memory, headers, compression, and all, it won't work.
如果相反,您在内存、标题、压缩等中有一个完整的 jpg 文件,则它将无法工作。
in that case you want:
在这种情况下,你想要:
Mat img = imdecode(data);
which will do the same as imread()
, only from memory, not from a filename
这将与 相同imread()
,仅从内存中,而不是从文件名中
回答by masad
as @bob mention, this can be done using the Mat constructor.
正如@bob 提到的,这可以使用 Mat 构造函数来完成。
byte *data;
cv::Mat imageWithData = cv::Mat(sizeOfData, 1, CV_8U, data).clone();
After you have created this matrix, call the reshapefunction with the number of rows in the image.
创建此矩阵后,使用图像中的行数调用reshape函数。
cv::Mat reshapedImage = imageWithData.reshape(0, numberOfRows);
回答by GaBo
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
参数“flag”指的是图像的类型,灰度,颜色,任何定义了 opencv 的 depht ..