joyalrj22 joyalrj22 - 1 year ago 104
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 Source

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

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

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)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download