如何在PyGame中获取屏幕上每个像素的颜色

4

我希望获得一个数组,其中包含pygame显示器中每个像素的RGBA代码

我尝试了这个:

for i in range(SCREEN_WIDTH):
    for j in range(SCREEN_HEIGHT):
        Pixels.append(pygame.Surface.get_at((i, j)))

但是我遇到了一个错误消息,说Surface.get_at不能处理元组,所以我去掉了一组括号,然后它告诉我Surface.get_at不能处理整数,所以我很困惑,如何获取所有像素的RGBA值?谢谢

编辑,好的,在收到评论后,我把完整可运行的代码发了出来:

import pygame
pygame.init()
PPM = 15
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pos_X = SCREEN_WIDTH/PPM/3
pos_Y = SCREEN_HEIGHT/PPM/3
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
FPS = 24
TIME_STEP = 1.0 / FPS
running = True

lead_x = pos_X*PPM
lead_y = pos_Y*PPM

k = 0
Pixels = []
while running:
    screen.fill((255, 255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
            running = False

    if k == 0:
        for i in range(SCREEN_WIDTH):
            for j in range(SCREEN_HEIGHT):
                Pixels.append(pygame.Surface.get_at((i, j)))

        k +=1

    pygame.draw.rect(screen, (128,128,128),  [lead_x, lead_y,50,50])

    pygame.display.update()
    pygame.display.flip() # Update the full display Surface to the screen
    pygame.time.Clock().tick(FPS)

pygame.quit()

我得到了完全相同的错误,没有更少也没有更多:

Exception has occurred: TypeError
descriptor 'get_at' for 'pygame.Surface' objects doesn't apply to 'tuple' object

你能贴出堆栈跟踪吗?否则很难调试,因为这看起来是 API 的正常使用,需要看到确切的错误信息。 - Brian
我只需要将 Pygame.Surface 更改为 screen,问题就解决了,抱歉打扰你了... 我很惊讶这是一个多么愚蠢的错误。 - Mechatrnk
2个回答

3

.get_atpygame.Surface 的一个实例函数方法(参见Method Objects)。因此,它必须在 pygame.Surface 的实例上调用。screen 是代表窗口的 Surface 对象。所以应该是:

Pixels.append(pygame.Surface.get_at((i, j)))

Pixels.append(screen.get_at((i, j)))

分别地

Pixels.append(pygame.Surface.get_at(screen, (i, j)))

0

为了以字节的形式获取所有像素值,您可以使用

pygame.Surface.get_buffer(screen).raw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接