Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numpy array of RGB colors from pygame.surface

I have code:

import pygame.camera
pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
cam.start()
img = cam.get_image()

The img variable is

<Surface(640x480x24 SW)>

I found the get numpy array from pygame but still I do not know how to convert it effectively to numpy array of RGB colors.

like image 758
matousc Avatar asked Jan 08 '16 09:01

matousc


1 Answers

For grabbing 3D image data from class pygame.Surface, use .array3d(), as also the doc states -

Copy pixels into a 3d array

array3d(Surface) -> array

Thus, you could do -

imgdata = pygame.surfarray.array3d(img)

Please note that the resulting imgdata might appear with height and width switched. To fix that, swap the first two axes, like so -

imgdata = imgdata.swapaxes(0,1)
like image 162
Divakar Avatar answered Sep 19 '22 11:09

Divakar