Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV to use in memory buffers or file pointers

Tags:

The two functions in openCV cvLoadImage and cvSaveImage accept file path's as arguments.

For example, when saving a image it's cvSaveImage("/tmp/output.jpg", dstIpl) and it writes on the disk.

Is there any way to feed this a buffer already in memory? So instead of a disk write, the output image will be in memory.

I would also like to know this for both cvSaveImage and cvLoadImage (read and write to memory buffers). Thanks!


My goal is to store the Encoded (jpeg) version of the file in Memory. Same goes to cvLoadImage, I want to load a jpeg that's in memory in to the IplImage format.

like image 842
The Unknown Avatar asked Apr 29 '09 07:04

The Unknown


1 Answers

This worked for me

// decode jpg (or other image from a pointer)
// imageBuf contains the jpg image
    cv::Mat imgbuf = cv::Mat(480, 640, CV_8U, imageBuf);
    cv::Mat imgMat = cv::imdecode(imgbuf, CV_LOAD_IMAGE_COLOR);
// imgMat is the decoded image

// encode image into jpg
    cv::vector<uchar> buf;
    cv::imencode(".jpg", imgMat, buf, std::vector<int>() );
// encoded image is now in buf (a vector)
    imageBuf = (unsigned char *) realloc(imageBuf, buf.size());
    memcpy(imageBuf, &buf[0], buf.size());
//  size of imageBuf is buf.size();

I was asked about a C version instead of C++:

#include <opencv/cv.h>
#include <opencv/highgui.h>

int
main(int argc, char **argv)
{
    char *cvwin = "camimg";

    cvNamedWindow(cvwin, CV_WINDOW_AUTOSIZE);

    // setup code, initialization, etc ...
    [ ... ]

    while (1) {      
        // getImage was my routine for getting a jpeg from a camera
        char *img = getImage(fp);
        CvMat mat;

   // substitute 640/480 with your image width, height 
        cvInitMatHeader(&mat, 640, 480, CV_8UC3, img, 0);
        IplImage *cvImg = cvDecodeImage(&mat, CV_LOAD_IMAGE_COLOR);
        cvShowImage(cvwin, cvImg);
        cvReleaseImage(&cvImg);
        if (27 == cvWaitKey(1))         // exit when user hits 'ESC' key
        break;
    }

    cvDestroyWindow(cvwin);
}
like image 100
codeDr Avatar answered Sep 20 '22 05:09

codeDr