Get color of individual pixels of images in pygame

北城余情 提交于 2020-03-01 12:44:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39538642/get-color-of-individual-pixels-of-images-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!