简体   繁体   中英

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

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? 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 . So it has to be called on an instance of pygame.Surface . screen is the Surface object, which represents the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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