SCHOOL OF MAKING
install them manually (or via your package manager if
you’re on Linux).
The code for the conversion is:
import numpy
from PIL import Image
#NumPy magic to convert image to Python list
img = numpy.asarray(Image.open(‘otters.png’)).
tolist()
pallette = []
outbitmap = []
strippedbitmap = []
outpallette = []
#convert array of RGBA values to bitmap and pallet
for i in img:
line=[]
for j in i:
try:
colour = pallette.index(j)
line.append(colour)
except ValueError:
pallette.append(j)
colour = pallette.index(j)
line.append(colour)
outbitmap.append(line)
#strip transparency & convert to hex
for colour in pallette:
outpallette.append(‘0x%02x%02x%02x’ %
(colour[0],colour[1], colour[2]))
#strip down to just the running otter
for x in range(96):
strippedbitmap.append(outbitmap[2*96+x])
print(“otter_bmp_data =”, strippedbitmap)
#need to print the pallette data differently as the
hex values are stored in strings
#and will be outputted with quote marks unless we
do this
print(“otter_pallette_data = [“,)
for colour in outpallette:
print( colour, “,”)
print(“]”)
This opens a file called otters.png (located in the same
directory that you’re running this script from) and
outputs, to the terminal, the Python data structures
holding the bitmap and palette. We pushed this straight
into a Python file by running it with the following:
python convert.py > otter_data.py
This will create a PY file that we can copy to our
CircuitPython device and import – but before getting to
that point, let’s take a look at what the script does.
We won’t dwell on the line that does some magic
from NumPy and PIL to create a 2D list containing the
RGBA (the final A is the Alpha or transparency) values
for each pixel. It just uses some built-in methods to do
the hard work.
We then have to loop through this and, for each
pixel, see if that colour is already in the palette and, if it
is, link that pixel to the index of the colour. If it isn’t,
add the colour to the palette, then link it to the index of
the colour.
We finally have to convert the RGB values, which
are stored in lists to a hex string, and strip out the parts
of the image that we don’t want (as we’re pushing the
memory limits of the PyPortal as it is).
This gives us our transparent image, but we need
something for it to be transparent against. We used
the trees and bushes images from hsmag.cc/
rtasZA, but scaled to be 320×240 pixels to match
the dimensions of the screen. We saved this as
background.bmp in the images folder on
the PyPortal.
Right
The Mu editor is the
easiest way of
programming
CircuitPython – some
other text editors
cause problems
This gives us our
transparent image, but we
need something for it to be
transparent against
”
”
Control a screen with CircuitPython