获取pygame中图像的单个像素的颜色

问题描述:

如何获取图像的像素的颜色值,并将其映射到pygame表面上?使用Surface.get_at()只返回表面图层的颜色,而不是返回的图像。获取pygame中图像的单个像素的颜色

+0

请提供您的代码样本 – Flint

方法surface.get_at没问题。 下面是一个示例,显示了在不使用Alpha通道的情况下传输图像时的差异。

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() 

这里,点击红色像素会给:

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

的PixelArray返回0xAARRGGBB颜色分量,而彩色期待0xRRGGBBAA。另请注意,屏幕表面的alpha通道为255.

+0

+1很好的答案!只有两件事:你提到'surface.getAt'并使用'surface.get_at'。这可能会让人困惑。其次,你在'pygame.display.flip'函数中使用未定义的变量'e'。我不确定它会是什么样子,因为它只是为了改变几个字符,所以我不能自己编辑它。 –