Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 619
Mechatrnk Avatar asked Oct 16 '25 13:10

Mechatrnk


1 Answers

.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)))
like image 75
Rabbid76 Avatar answered Oct 18 '25 09:10

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!