How can I convert a surface object in pygame to a 2-dimensional array of RGB values (one value for every pixel)? I have read the documentation on PixelArrays and Surfarrays and I cannot seem to find an answer to my question. Examples are more than welcome.
The pygame documentation says that given a surface object, you can create a PixelArray
wrapper to provide direct 2D array access to its pixels by calling the module's PixelArray()
method like this:
pxarray = pygame.PixelArray(surface)
Logically a PixelArray
object is a 2-dimensional array of RGB values stored as integers.
A
PixelArray
pixel item can be assigned a raw integer value, apygame.Color
instance (an object for color representations), or a(r, g, b[, a])
tuple.pxarray[x, y] = 0xFF00FF pxarray[x, y] = pygame.Color(255, 0, 255) pxarray[x, y] = (255, 0, 255)
It also mentions:
However, only a pixel’s integer value is returned. So, to compare a pixel to a particular color, the color needs to be first mapped using the
Surface.map_rgb()
method of theSurface
object for which thePixelArray
was created.
Which means you'll need to use the Surface.map_rgb()
method to get RGB tuples from PixelArray
integer values whenever you're not doing an assignment to the array, i.e. when reading a pixel's value, as is being done in the following conditional:
# Check, if the first pixel at the topleft corner is blue
if pxarray[0, 0] == surface.map_rgb((0, 0, 255)):
...
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With