Be aware of memory alignment of IplImage in OpenCV

The imageData of IplImage is aligned 4 or 8 bytes in order to enhance the processing speed. For example, let’s say you have a color image of size 98-by-98 (pixel depth 8 bits ) and imageData is aligned 4 bytes. The size of each row will not be 98×3=294 bytes but 296 bytes. The widthStep of IplImage shows the actual size of aligned image row in bytes. This can help us access imageData correctly. Here is a code that copy imageData to a user-created buffer.

IplImage *colorImage;
// load an color image
colorImage = cvLoadImage("SL_0230.jpg");
// create a temp buffer
unsigned char *buffer,*temp2;
buffer = new unsigned char[colorImage->width*colorImage->height*colorImage->nChannels];
temp2 = buffer;

// pointer to imageData
unsigned char *temp1 = (unsigned char*) colorImage->imageData;
// copy imagedata to buffer row by row
for(int i=0;i<colorImage->height;i++)
    // memory copy
    memcpy(temp2, temp1, colorImage->width*colorImage->nChannels);
    // imageData jump to next line
    temp1 = temp1 + colorImage->widthStep;
    // buffer jump to next line
    temp2 = temp2+ colorImage->width*colorImage->nChannels;
// ......................

6 Responses to Be aware of memory alignment of IplImage in OpenCV

  1. Thanks for the code.

    Just som corrections. Change 18th line from:

    temp2 = temp2 + colorImage->widthStep;
    temp1 = temp1 + colorImage->widthStep;

    And add a semicolon at the end of the 20th line.

    If you want to know the padding of each row, you can use this code:
    int byte_padding=colorImage->widthStep-colorImage->width*colorImage->nChannels;


  2. chi3x10 says:

    Thanks. Jose.

  3. Baptiste Bouchet says:

    I’m coming very late but I had to perform the same thing and i think there is a mistake on the sample code… In addition to the José Felix Lucia’s correction:
    Line 20:
    temp1 = temp1+ colorImage->width*colorImage->nChannels;
    temp2 = temp2+ colorImage->width*colorImage->nChannels;

    Enjoy 😉

  4. zorrow says:

    thanks for this useful tip!! was almost going crazy trying to figure out why i get those interlaced lines after hue transformation, thanks again!

  5. JDJ says:

    Hi, sorry I am coming in too late. What if the buffer we create is of float data type and we want to copy the imagedata to it?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: