PyGameExamplesAndAnswers

StackOverflow            reply.it reply.it


Surface array, pixel array, buffer proxy

Surface array

pygame.surfarray module

Related Stack Overflow questions:

Use pygame.surfarray.pixels2d, pygame.surfarray.array2d, pygame.surfarray.pixels3d, or pygame.surfarray.array3d to create a pixel array from a pygame.Surface object (see pygame.surfarray module):

import pygame

# [...]

window = pygame.display.set_mode()
array2D = pygame.surfarray.array2d(window)
array3D = pygame.surfarray.array3d(window)

While array* creates copies of the pixels from a Surface object, pixel* creates a new array that directly references the pixel values ​​in a Surface object.
The *2d version generates a two-dimensional array, with each pixel represented by a single integral value. The *3d version generates a three-dimensional array in which each color channel is represented by an integer value.

To get the all channels of an transparent image, you have to get the color channels (array3d or pixels3d) and the alpha channel (array_alpha or pixels_alpha) and stick them together. Recreate the Surface with pygame.image.frombuffer:

pixels_rgb = pygame.surfarray.array3d(rgba_image)
pixels_alpha = pygame.surfarray.array_alpha(rgba_image).reshape((*pixels_rgb.shape[0:2], 1))
pixels_rgba = np.concatenate((pixels_rgb, pixels_alpha), 2)

new_rgba_image = pygame.image.frombuffer(pixels_rgba.transpose((1, 0, 2)).copy(order='C'), text.get_size(), 'RGBA')

Pixel array

pygame.PixelArray object

Related Stack Overflow questions:

Use a “pygame.PixelArray” object to enable direct pixel access to Surface objects. A PixelArray pixel item can be assigned directly. The pixel can be accessed by subscription. The PixelArray locks the Surface, You have to close() it when you have changed the pixel:

pixel_array = pygame.PixelArray(window_surface)

pixel_array[x, y] = my_color
pixel_array[start_x:end_x, start_y:end_y] = my_color

pixel_array.close()

📁 Minimal example - Draw pixels with pygame.PixelArray

Pygame: Draw single pixel

Buffer proxy

pygame.BufferProxy object