0

Anybody know why this array I created from pygame's get_buffer method has the R, G, B, values reversed? I want to create an array with the colour values in the same order I put them in - like [8, 16, 32, 0]. Have I done something wrong or is this something with the way pygame stores pixel data?

>>> import pygame
>>> import pygame.gfxdraw
>>> import numpy as np
>>> background_colour = (1, 1, 1)
>>> width, height = (256, 256)
>>> screen = pygame.Surface((width, height))
>>> pygame.draw.rect(screen, (8, 16, 32), (0, 0, 100, 100), 0)
<rect(0, 0, 100, 100)>
>>> s = screen.get_buffer()
>>> x = np.fromstring(s.raw, dtype='b').reshape(height, width, 4)
>>> x[0, 0]
array([32, 16,  8,  0], dtype=int8)

I tried this but I loose the R value:

>>> y = x[:, :, 3:0:-1]
>>> y[0, 0]
array([ 0,  8, 16], dtype=int8)

(I'm using numpy version 1.8.2 so I don't have np.flip).

1 Answer 1

1

I realised there is a much better way to do this. The pygame.surfarray module has various methods that actually create numpy arrays for you!

>>> x3 = pygame.surfarray.pixels3d(screen)
>>> x3.shape
(256, 256, 3)
>>> x3[0, 0]
array([ 8, 16, 32], dtype=uint8)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.