g-andreadis g-andreadis - 6 months ago 21
Python Question

Converting an image in pygame to an 2D array of RGB values

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.

Answer

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)

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 values, a pygame.Colorpygame object 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 Surface object for which the PixelArray was created.

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[0][0] == surface.map_rgb((0, 0, 255)):
  ...

Hope this helps.