Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create an array of pixels in Pygame?

According to the docs:

pygame.surfarray.blit_array()
Blit directly from array values
blit_array(Surface, array) -> None
Directly copy values from an array into a Surface ...
The array must be the same dimensions as the Surface and will completely replace all pixel values. Only integer, ascii character and record arrays are accepted.

My code is as follows,

surf = pygame.display.set_mode( ( width, height ) )
pixels = [
   # width * height * 3
   [(255,241,232),(255,241,232),...],
   [(255,241,232),(255,241,232),...],
   ...
]
surfarray.blit_array( surf, pixels )

Running it, I get the error ValueError: list object does not export an array buffer.

What am I doing wrong?



Here's the full error message,

line 23, in <module>    
  surfarray.blit_array( surf, pixels )
line 81, in blit_array
  return numpysf.blit_array (surface, array)
line 82, in blit_array
  return array_to_surface(surface, array)
ValueError: list object does not export an array buffer
like image 572
Jet Blue Avatar asked Oct 24 '25 04:10

Jet Blue


1 Answers

The array for pygame.surfarray.blit_array() must be any array object, either a np.array or numeric array. A array made from list doesn't work in this case, but you can do:

import numpy as np
pixels = np.array([
   [(255,241,232),(255,241,232)],
   [(255,241,232),(255,241,232)]
])
#rest the same...

Which converts your list array to a np.array

In the documentation for pygame.surfarray it states:

Functions to convert pixel data between pygame Surfaces and arrays. This module will only be functional when pygame can use the external Numpy package.

like image 139
Taku Avatar answered Oct 25 '25 17:10

Taku



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!