Crypto
Crypto

Reputation: 1217

How do I load an image (raw bytes) with OpenCV?

I am using Mat input = imread(filename); to read an image but I'd like to do it from memory instead. The source of the file is from an HTTP server. To make it faster, instead of writing the file to disk and then use imread() to read from it, i'd like to skip a step and directly load it from memory. How do I go about doing this?

Updated to add error

I tried the following but I'm getting segmentation fault

char * do_stuff(char img[])
{
    vector<char> vec(img, img + strlen(img));
    Mat input = imdecode(Mat(vec), 1);
}

Upvotes: 4

Views: 10467

Answers (2)

aviimaging
aviimaging

Reputation: 167

I had a similar problem. I needed to decode a jpeg image stream in memory and use the Mat image output for further analysis.

The documentation on OpenCV::imdecode did not provide me enough information to solve the problem.

However, the code here by OP worked for me. This is how I used it ( in C++ ):

//Here pImageData is [unsigned char *] that points to a jpeg compressed image buffer;
//     ImageDataSize is the size of compressed content in buffer; 
//     The image here is grayscale; 

cv::vector<unsigned char> ImVec(pImageData, pImageData + ImageDataSize);
cv:Mat ImMat;
ImMat = imdecode(ImVec, 1); 

To check I saved the ImMat and was able to open the image file using a image viewer.

cv::imwrite("opencvDecodedImage.jpg", ImMat);

I used : OpenCV 2.4.10 binaries for VC10 on x86. I hope this information can help others.

Upvotes: 2

Related Questions