Search code examples
pythonpygamepygame2

Get RGB pixel data of a section of a screen as an array in pygame


My code allows a user to draw on a section of a pygame screen. I want to be able to extract all the RGB pixel values for this section of the screen and convert them to a 3d array, like this:

top_left = [50, 50]
bottom_right = [100, 100]
pixel_data = SomeFunctionToGetPixelData(screen, top_left, bottom_right)

# get RGB value for pixel that was at position (53, 51) on the screen
print(pixel_data[3][1])
> [255, 255, 255]

What's the best way to do this?


Solution

  • Create a subsurface from the section of the screen. A subsurface shares its pixels with its new parent (see pygame.Surface.subsurface):

    w = bottom_right[0] - top_left[0]
    h = bottom_right[1] - top_left[1]
    area = pygame.Rect(top_left[0], top_left[1], w, h)
    sub_surface = screen.subsurface(area)
    

    Use pygame.surfarray.array3d() to copy the pixels from a Surface into a 3D array:

    pixel_data = pygame.surfarray.array3d(sub_surface)
    

    Minimal function:

    def get_pixel_data(surf, top_left, bottom_right):
        w = bottom_right[0] - top_left[0]
        h = bottom_right[1] - top_left[1]
        sub_surface = surf.subsurface(pygame.Rect(*top_left, w, h))
        return pygame.surfarray.array3d(sub_surface)