Opencv如何从Mat快速获取图像流

Opencv how to get image stream from Mat quickly?

本文关键字:获取 图像 Mat Opencv      更新时间:2023-10-16

我可以使用imwrite()将图像(如"face.jpg")写入磁盘,然后使用fstream将此JPG读取到数组中。这个数组就是我想要的。

但是,如何快速得到这个?从内存而不是磁盘。我认为图像数据在Mat.data,长度是Mat.cols*Mat.rows。我不确定这是对还是错。所以,我用fstream把它写入磁盘,然后用图像查看器打开它,什么也没有。一定是出了什么问题。

Mat frame; 
VideoCapture cap(0); 
if (!cap.isOpened())
{ 
   return -1; 
} 
cap.set(CV_CAP_PROP_FRAME_WIDTH, 160); 
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 120); 
cap >> frame; 
if(frame.empty()){
   return -2;
}
//I just want the pointer and length of image information,the following is just for testing
//whether that the same as I thought,if it's right ,frame.data and len is what I want,but it not work.
FILE *fp = fopen("face.jpg", "wb"); 
if (NULL==fp) 
{
   return -1; 
} 
int len = frame.cols*frame.rows; //or 3*frame.cols*frame.rows
fwrite(frame.data, len, sizeof(char), fp); 
fclose(fp);

namedWindow("face", 1);
imshow("face", frame);
waitKey(1000);

我是新的opencv,我只是想获得图像数据。谢谢你的帮助!

在写入磁盘之前检查过尺寸了吗?在这里看到您的代码对其他人很有帮助。在Mat的情况下,除非您的数据是灰度的,否则大小将超过cols *行。您应该验证格式是RGB、RGBA还是YUV等。在JPEG的情况下,它很可能是RGBX;所以你应该检查你的流大小是3 * cols *行还是4 * cols *行

我只是用imencode()做了这个,谢谢@ZdaR。

    vector<uchar> buff;
    vector<int>param = vector<int>(2);
    param[0] = CV_IMWRITE_JPEG_QUALITY;
    param[1] = 95;
    imencode(".jpg", frame, buff, param);
    int len = buff.size();
    FILE *fout;
    fout = fopen("555.jpg", "wb");
    if(NULL==fout){
         return -3;
    }
    fwrite(&buff[0], 1, len*sizeof(uchar), fout);
    fclose(fout);