Search code examples
pythonnumpypygamesurface

is there a faster way of checking if list[i] of pygame surface has alpha 0


I'm making a sprite sheet class in pygame and I'm putting every frame I get from an image in an list. But, sometimes the sprite sheet has some empty frames. e.g. I made a image with 2 sprite animation, so I put each one in a row, but the first one is 1 frame bigger than the 2nd one, so the 2nd has a empty frame.

I did this code to check if the frame is empty. I used a reversed loop 'cause most empty frames are at the end of the list, so I can break when any frame is not empty, so then it won't take that much time.

for i in reversed(range(len(frames))):
    frame_alpha_as_array = surfarray.array_alpha(frames[i])

    if np.sum(frame_alpha_as_array) == 0:
        del(frames[i])
    else:
        break

But, I would like to know if there is a faster way of doing that, so that it doesn't take much of the cpu/gpu/ram (IDK).

I'm relatively new to programing so don't be too harsh if I'm doing something wrong.


Solution

  • Use pygame.surfarray.pixels_alpha() instead of pygame.surfarray.array_alpha(). While pygame.surfarray.array_alpha() copies pixel alphas to a 2D array, pygame.surfarray.pixels_alpha() refers directly to pixel alphas.

    See the documentation of pygame.surfarray.pixels_alpha()

    Create a new 2D array that directly references the alpha values (degree of transparency) in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
    The Surface this array references will remain locked for the lifetime of the array.

    Use numpy.any to test whether any array element is greater 0:

    if not np.any(surfarray.pixels_alpha(frames[i]) != 0):