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

[pygame] Stuck with surfarray



I'm trying to optimize a color swapping method:

def swapRGB( surf, sourceRGB, destRGB ):
    '''Swap rgb, but not alpha'''
    for x in range(surf.get_width()):
        for y in range(surf.get_height()):
            pos       = (x,y)
            pixelRGBA = surf.get_at( pos )
            if pixelRGBA[:3] == sourceRGB:
                surf.set_at( pos, destRGB + (pixelRGBA[-1],) )


into something like this:

def swapRGB( surf, sourceRGB, destRGB ):
    array = pygame.surfarray.array3d( surf )
    array = N.where( array == sourceRGB, destRGB, array )
    return pygame.surfarray.make_surface( array )


But this just gives me an RGB image with all alphas set to 255, and it
doesn't seem possible to use surfarray for RGBA at the same time.

 I can't quite figure out how to swap RGB while leaving alpha alone;
surfarray.pixels3d() or pixels_alpha() seemed like they might work as it
lets you modify a surface indirectly, but I could not get it to accept
setting from an array3D.  surfarray.blit_surface() didn't work for me
either.

I'm stumped, What's the trick?  If only make_surf would take an RGB and
an alpha array, or surfarray could handle RGBA all at once. :-/

-Jasper