DaddyTheRunner
Posts: 8
Joined: Sun Sep 13, 2015 11:56 pm

Sense hat and numpy

Fri Oct 14, 2016 1:27 am

I've been experimenting with the LED array on the sense hat and realized that storing the pixel values in a numpy array would provide a lot more flexibility for manipulating the pixel values as compared to using python lists. While experimenting, I noticed that the sense hat set_pixels() function accepts a numpy array without having to convert it back into a python list. I was wondering if this is a feature of the sense hat library or a feature of numpy arrays.

Here's some sample code that demonstrates what I discovered:

Code: Select all

## Example of how to use Sense_Hat with numpy
from sense_hat import SenseHat
import numpy as np

sense = SenseHat()
sense.gamma = [i for i in range(32)]
sense.set_pixels([3*[i] for i in range(64)])

# Get the current pixel values in list form
pl = sense.get_pixels()

# Convert to an np.array
pa = np.array(pl)

# Resize the array into an 8 x 8 x 3 array
pa.resize(8,8,3)

# Manipulate the array to add three lines
pa[3:6,3,:] = [255, 0, 0]
pa[3:6,4,:] = [0, 255, 0]
pa[3:6,5,:] = [0, 0, 255]

# Send the new array to the sense hat
sense.set_pixels(pa.reshape(64,3))

# Which is simpler than the anticipated explicit conversion to a list:
# sense.set_pixels(pa.reshape(64,3).tolist())

Return to “Astro Pi”