[英]How to convert Opencv Mat to JPEG char data
Recently, i am having trouble with converting a Mat frame captured from my webcam by OpenCV to a normal JPEG unsigned char array. 最近,我在将OpenCV从网络摄像头捕获的Mat帧转换为普通JPEG无符号字符数组时遇到麻烦。 I've tried one or two way on Google but the result seems not the correct jpeg uchar array.
我在Google上尝试了一种或两种方法,但结果似乎不是正确的jpeg uchar数组。 Here is a piece of my code:
这是我的一段代码:
VideoCapture cap(0);
if(!cap.isOpened())
return -1;
Mat frame;
cap >> frame;
if( frame.empty())
return -1;
int size = frame.total() * frame.elemSize();
unsigned char* buffer = new unsigned char[size];
memcpy(buffer, frame.data, size * sizeof(unsigned char));
Then i used fwrite to write that buffer into a file.jpg (it looks silly but it does work if the buffer is correct),but the file cannot be openned or be determined as a jpeg image. 然后我用fwrite将缓冲区写入file.jpg (看起来很傻,但是如果缓冲区正确,它确实可以工作),但是无法打开文件或将其确定为jpeg图像。
Can anyone help me figure this out? 谁能帮我解决这个问题?
Check out the OpenCV function imencode()
. imencode()
出OpenCV函数imencode()
。 It will fill a buffer with data encoded as the correct image type (based on the file type argument) so that it can be written to a file and other programs will know what to do with it. 它将使用编码为正确图像类型(基于文件类型参数)的数据填充缓冲区,以便可以将其写入文件,并且其他程序将知道如何处理该文件。
The problem with your current approach is that you are attempting to write raw image data as a JPEG, but JPEG is a compressed data format so programs won't know what to do with the data you've written. 当前方法的问题是,您试图将原始图像数据写入JPEG,但是JPEG是一种压缩数据格式,因此程序将不知道如何处理已写入的数据。 It would be equivalent of taking a binary file and just saving it as a JPEG, the file won't have the right headers to be decoded as an image and the data otherwise likely won't match up with the JPEG format anyways.
这相当于获取一个二进制文件并将其另存为JPEG,该文件将没有正确的标头被解码为图像,否则数据无论如何都可能与JPEG格式不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.