Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

rgb

pygame

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.

like image 258
gandreadis Avatar asked Oct 18 '12 14:10

gandreadis


1 Answers

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

like image 60
martineau Avatar answered Oct 11 '22 12:10

martineau