[Cython] 2d buffer interface with aligned data

Christian Heimes lists at cheimes.de
Tue Jul 17 17:38:59 CEST 2012


Hello,

I'm the author of https://bitbucket.org/tiran/smc.freeimage , a Cython
wrapper of the FreeImage and LCMS libraries. FreeImage supports a broad
variety of image formats and pixel formats from standard RGB up to RGBAF
and complex numbers.

Now I like to add support for buffer interface to my code to support
zero-copy access of pixel data from NumPy. The wiki describes several
ways to access objects through the new and old Python buffer interface.
However I'm unable to find an example how to *implement* the buffer
interface.

Memory alignment makes the buffer interface more complicated, too.
FreeImage stores the raw pixels non-contiguously. The lines are memory
aligned (usually 32bit). For example a standard RGB image with 1 byte
per pixel and size of 2*3 pixels has a memory layout of

   BGRBGRxxBGRBGRxxBGRBGRxx

on a little-endian machine. 'xx' are the two alignment bytes.

Here is an excerpt from the FreeImage manual on how to access the raw
pixel data. The above example has width: 2, height: 3, pitch: 8 and bpp: 3.

unsigned width = FreeImage_GetWidth(dib);   // 2
unsigned height = FreeImage_GetHeight(dib); // 3
unsigned pitch = FreeImage_GetPitch(dib);   // 8
unsigned bpp = FreeImage_GetBPP(dib);       // 3

BYTE *bits = (BYTE*)FreeImage_GetBits(dib);
for(y = 0; y < height; y++) {
    BYTE *pixel = (BYTE*)bits;
    for(x = 0; x < width; x++) {
        pixel[FI_RGBA_RED] = 128;
        pixel[FI_RGBA_GREEN] = 128;
        pixel[FI_RGBA_BLUE] = 128;
        pixel += bpp;
    }
    // next line
    bits += pitch;
}

Please help,
Christian


More information about the cython-devel mailing list