writing to IplImage imageData

wyatt picture wyatt · Aug 1, 2011 · Viewed 21.8k times · Source

I want to write data directly into the imageData array of an IplImage, but I can't find a lot of information on how it's formatted. One thing that's particularly troubling me is that, despite creating an image with three channels, there are four bytes to each pixel.

The function I'm using to create the image is:

IplImage *frame = cvCreateImage(cvSize(1, 1), IPL_DEPTH_8U, 3);

By all indications, this should create a three channel RGB image, but that doesn't seem to be the case.

How would I, for example, write a single red pixel to that image?

Thanks for any help, it's get me stumped.

Answer

SSteve picture SSteve · Aug 1, 2011

If you are looking at frame->imageSize keep in mind that it is frame->height * frame->widthStep, not frame->height * frame->width.

BGR is the native format of OpenCV, not RGB.

Also, if you're just getting started, you should consider using the C++ interface (where Mat replaces IplImage) since that is the future direction and it's a lot easier to work with.

Here's some sample code that accesses pixel data directly:

int main (int argc, const char * argv[]) {

    IplImage *frame = cvCreateImage(cvSize(41, 41), IPL_DEPTH_8U, 3);

    for( int y=0; y<frame->height; y++ ) { 
        uchar* ptr = (uchar*) ( frame->imageData + y * frame->widthStep ); 
        for( int x=0; x<frame->width; x++ ) { 
            ptr[3*x+2] = 255; //Set red to max (BGR format)
        }
    }

    cvNamedWindow("window", CV_WINDOW_AUTOSIZE);
    cvShowImage("window", frame);
    cvWaitKey(0);
    cvReleaseImage(&frame);
    cvDestroyWindow("window");
    return 0;
}