在C++中将字节arry转换为OpenCV图像

spa*_*der 16 c++ arrays opencv bytearray

我有一个字节数组,表示我想直接转换为OpenCV Mat对象的.jpg文件.

我有类似的东西

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;
Run Code Online (Sandbox Code Playgroud)

ber*_*rak 20

如果它是PIXEL数据,前面提到的方法将正常工作.

如果相反,你在内存,标题,压缩和所有内容中都有一个完整的jpg文件,它将无法正常工作.

在这种情况下你想要:

Mat img = imdecode(data);
Run Code Online (Sandbox Code Playgroud)

这将imread()与内存相同,而不是从文件名中执行

  • 我们不必提供图像尺寸或像素格式?我们如何做相反的事情(将 mat 转换为字节数组)? (2认同)

mas*_*sad 13

正如@bob提到的,这可以使用Mat构造函数完成.

byte *data;
cv::Mat imageWithData = cv::Mat(sizeOfData, 1, CV_8U, data).clone();
Run Code Online (Sandbox Code Playgroud)

创建此矩阵后,使用图像中的行数调用reshape函数.

cv::Mat reshapedImage = imageWithData.reshape(0, numberOfRows);
Run Code Online (Sandbox Code Playgroud)