简体   繁体   English

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

[英]How to get color of each pixel on a screen in PyGame

I would like to get an array which would consist of RGBA code of every pixel in the pygame display我想得到一个数组,它包含 pygame 显示器中每个像素的 RGBA 代码

I tried this:我试过这个:

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

But I got an error message that Surface.get_at does not work for tuples so I removed one set of bracket and then it told me that Surface.get_at does not work with integers, so I am confused, how can I get the RGBA value of all pixels?但是我收到一条错误消息,指出 Surface.get_at 不适用于元组,所以我删除了一组括号,然后它告诉我 Surface.get_at 不适用于整数,所以我很困惑,我怎样才能获得 RGBA 值所有像素? Thank you谢谢

EDIT , Ok after a comment I post full runable code:编辑,好的评论后我发布完整的可运行代码:

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

And I got these exact error, nothing less and nothing more:我得到了这些确切的错误,仅此而已:

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

.get_at is a instance function method (see Method Objects ) of pygame.Surface . .get_at是 pygame.Surface 的实例pygame.Surface方法(参见 方法对象)。 So it has to be called on an instance of pygame.Surface .所以它必须在pygame.Surface的实例上调用。 screen is the Surface object, which represents the window. screen是Surface object,代表的是window。 So it has to be:所以它必须是:

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

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

respectively分别

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

To get all pixels value as bytes, you can use要将所有像素值作为字节获取,您可以使用

pygame.Surface.get_buffer(screen).raw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM