python 2.6: how to modify a PIL image from C without copying forth and back

News123 news123 at free.fr
Wed Mar 3 01:38:21 CET 2010


Hi,

I created a grayscale image with PIL.

Now I would like to write a C function, which reads a;most all pixels
and will modify a few of them.


My current approach is:
- transform the image to a string()
- create a byte array huge enough to contain the resulting image
- call my c_function, which copies over the entire image in order
   to modify a few pixels
How can I achieve this with the least amount of copies?


########## Python code snippet ################

im = Image.open('grayscalefile_onebyteperpixel')
wx,wy = im.size

# create a string in order to pass it to my function
# I'm afraid this involves copying so  want to get rid of it
im_as_string = im.tostring()

# create a byte array in order to store my result
new_img_array = array.array('B', [0]*(wx*wy) )


# my function which should just change some pixels has
# to copy all unmodified pixels
my_extension.my_func(wx,wy,im_as_string,new_img_array)


im = Image.frombuffer('L',(wx,wy),new_img_array)
show(im2)

############ C wrapper code snippet ###############

    int wx,wy;
    Py_buffer img;
    Py_buffer new_img;
    Py_buffer table;
    unsigned char *img_ptr;
    unsigned char *new_img_ptr;

    int ok = PyArg_ParseTuple(args,
        "iis*w*",&wx,&wy,&img,&new_img);
    img_ptr = (unsigned char *) img.buf;
    new_img_ptr = (unsigned char *) new_img.buf;
    my_func(wx,wy,img_ptr,new_img_ptr);


Thanks in advance for any suggestions to make this more efficient.


bye


N




More information about the Python-list mailing list