joyalrj22 joyalrj22 - 2 months ago 15
Python Question

Get color of individual pixels of images in pygame

How can I get the colour values of pixels of an image that is blitted onto a pygame surface? Using Surface.get_at() only returns the color of the surface layer, not the image that has been blitted over it.

Answer

The method surface.get_at is fine. Here is an example showing the difference when blitting an image without alpha channel.

import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
image = pygame.image.load("./img.bmp")
image_rect = image.get_rect()

screen.fill((0,0,0))
screen.blit(image, image_rect)
screensurf = pygame.display.get_surface()

while 1:

  for event in pygame.event.get():
     if event.type == pygame.MOUSEBUTTONDOWN :
        mouse = pygame.mouse.get_pos()
        pxarray = pygame.PixelArray(screensurf)
        pixel = pygame.Color(pxarray[mouse[0],mouse[1]])
        print pixel
        print screensurf.get_at(mouse)

  pygame.display.flip()

Here, clicking on a red pixel will give :

(0, 254, 0, 0)
(254, 0, 0, 255)

The PixelArray returns a 0xAARRGGBB color component, while Color expect 0xRRGGBBAA. Also notice that the alpha channel of the screen surface is 255.