简体   繁体   中英

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. I've tried one or two way on Google but the result seems not the correct jpeg uchar array. 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.

Can anyone help me figure this out?

Check out the OpenCV function 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM