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 then welcome.
The 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 surface's
PixelArray() method like this:
pxarray = pygame.PixelArray(surface)
PixelArray object is a 2-dimensional array of RGB values stored as integers.
PixelArraypixel item can be assigned a raw integer values, a
pygame.Colorpygameobject for color representations instance, 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 the
Surfaceobject for which the
Which means you'll need to use the
Surface.map_rgb() method to map RGB tuples to
PixelArray integer values whenever you're not doing an assignment, i.e. when reading a pixel's value, as is being done in the following conditional which is comparing a pixel to a constant color value (blue):
if pxarray == surface.map_rgb((0, 0, 255)): ...
Hope this helps.