[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Directly accessing pixel data



Tim Ansell wrote:

Hello,

I'm currently using ctypes to wrap the libmng module to support MNG
animations.

The library needs to be provided with a place to output the animation
frames to. Currently I'm using the following method,

1. Using ctype's c_buffer to create a file of the correct size
2. Use pygame.image.frombuffer pointing to the c_buffer

However it appears that frombuffer doesn't support the native pixel
format of the screen. For example SDL is using BGRA format on my screen,
but giving this format to frombuffer complains of "Unrecognized type of
format".


There's no need for the image and surface pixel formats to be the same, blits will only be slightly slower during the conversion from RGBA to BGRA.

Another way to solve the problem would be to create a surface and then
get a pointer to the SDL pixel buffer, which I could provide the library
with.

If I was using ctypes Pygame it looks like I could use the access the
pointer directly using the SDL part. Is there a way I could do this with
the older pygame?


Using surfarray.pixels2d will give you a Numeric array overlayed over the buffer, you can extract the buffer pointer with a little ctypes hackery (see array.py in pygame-ctypes).

This is fairly important because for high speed animations the time
required to convert to the correct format is quite high and a waste of
resources because the library could have converted to this format as it
was reading the data.


If you have no luck with the above, use a regex to reorder the components: this can be surprisingly fast (and is how pygame-ctypes does its pixel transfer). For RGBA to BGRA use something like

 data = re.sub('(.)(.)(.)(.)', r'\3\2\1\4', data)

Alex.

You can find the work so far at
http://darcs.thousandparsec.net/darcsweb/darcsweb.cgi?r=libmng-py;a=tree

Thanks for your time.

Tim Ansell