Skip to content

Commit 1e77578

Browse files
authored
Merge pull request #19 from ilikecake/image-function-numpy
Added image function that uses numpy if available
2 parents 581695b + f96d82b commit 1e77578

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

adafruit_sharpmemorydisplay.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
from micropython import const
3232
import adafruit_framebuf
3333

34+
try:
35+
import numpy
36+
except ImportError:
37+
numpy = None
38+
3439
__version__ = "0.0.0-auto.0"
3540
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SharpMemoryDisplay.git"
3641

@@ -103,3 +108,41 @@ def show(self):
103108
self._spi.write(self._buf) # we send one last 0 byte
104109
self._scs_pin.value = False
105110
self._spi.unlock()
111+
112+
def image(self, img):
113+
"""Set buffer to value of Python Imaging Library image. The image should
114+
be in 1 bit mode and a size equal to the display size."""
115+
# determine our effective width/height, taking rotation into account
116+
width = self.width
117+
height = self.height
118+
if self.rotation in (1, 3):
119+
width, height = height, width
120+
121+
if img.mode != "1":
122+
raise ValueError("Image must be in mode 1.")
123+
124+
imwidth, imheight = img.size
125+
if imwidth != width or imheight != height:
126+
raise ValueError(
127+
"Image must be same dimensions as display ({0}x{1}).".format(
128+
width, height
129+
)
130+
)
131+
132+
if numpy:
133+
self.buffer = bytearray(
134+
numpy.packbits(numpy.asarray(img), axis=1).flatten().tolist()
135+
)
136+
else:
137+
# Grab all the pixels from the image, faster than getpixel.
138+
pixels = img.load()
139+
# Clear buffer
140+
for i in range(len(self.buf)): # pylint: disable=consider-using-enumerate
141+
self.buf[i] = 0
142+
# Iterate through the pixels
143+
for x in range(width): # yes this double loop is slow,
144+
for y in range(height): # but these displays are small!
145+
if img.mode == "RGB":
146+
self.pixel(x, y, pixels[(x, y)])
147+
elif pixels[(x, y)]:
148+
self.pixel(x, y, 1) # only write if pixel is true

0 commit comments

Comments
 (0)