Code
Once you've finished setting up your Fruit Jam with CircuitPython, you can access the code and necessary libraries by downloading the Project Bundle.
To do this, click on the Download Project Bundle button in the window below. It will download to your computer as a zipped folder.
# SPDX-FileCopyrightText: 2026 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Face detector on Fruit Jam with a Logitech C270
Uses the Frontal Face cascade model from OpenCV.
The feed from the C270 is displayed through DVI. When a face is detected,
a green box is drawn around the face.
"""
import gc
import board
import displayio
import picodvi
import picogame
from supervisor import ticks_ms
from face_lbp import FaceDetector
from face_camera import CameraSession
# --- Camera ---
CAMERA_MODE = (320, 240)
DECODE_SCALE = 1
CAMERA_WAIT_MS = 3 # how long each check waits for a frame
MIRROR = True
# --- Face detection ---
CASCADE_PATH = "/frontalface.lbp"
SCALE_FACTOR = 1.3 # size step between searches; 1.1 is finer and slower
MIN_NEIGHBORS = 1 # raise for fewer false faces, lower to find more
# Smallest face to look for, in screen pixels.
# 48 is the smallest a 160x120 picture can show; with DECODE_SCALE 0, a
# smaller value finds faces farther away but takes much longer.
MIN_FACE_ON_SCREEN = 48
DETECT_SLICE_MS = 10 # detection work per loop pass, between video frames
TRACK = True # after finding a face, search near it first
TRACK_MISSES = 5 # tracking passes that may miss before a full search again
# Combine each pass's hits with the previous pass's, so a face needs
# MIN_NEIGHBORS + 1 hits across two frames rather than in one frame.
MERGE_PASSES = True
PRINT_FACES = True
# Debugging: don't take camera frames (or redraw) while a search is running.
PAUSE_CAMERA_DURING_SEARCH = False
# --- Screen ---
SCREEN_W, SCREEN_H = 320, 240
WAIT_FOR_VBLANK = False # True avoids tearing, but can wait up to a frame
BOX_COLOR = picogame.rgb565(0, 255, 0)
LINE = 2 # box line thickness in screen pixels
MAX_FACES = 3
HOLD_MS = 1200 # keep a box this long after its face was last found
SMOOTHING = 0.7 # 0 jumps straight to each new position, near 1 glides
REPORT_SECONDS = 4 # 0 for no timing reports
_TICKS_MASK = 0x1FFFFFFF # ticks_ms() wraps at 2**29
_CLEAR = picogame.rgb565(255, 0, 255) # the overlay's transparent color
frame_w = CAMERA_MODE[0] >> DECODE_SCALE
frame_h = CAMERA_MODE[1] >> DECODE_SCALE
zoom = SCREEN_W // frame_w # screen pixels per camera pixel
def elapsed(the_now, then):
return (the_now - then) & _TICKS_MASK
def reached(the_now, deadline):
"""Whether ticks_ms() time now is at or past deadline, across a wrap."""
return elapsed(the_now, deadline) < (_TICKS_MASK >> 1)
gc.collect()
# --- The detector, while memory is unfragmented ---
detector = FaceDetector(
CASCADE_PATH,
frame_w,
frame_h,
scale_factor=SCALE_FACTOR,
min_neighbors=MIN_NEIGHBORS,
min_size=max(0, MIN_FACE_ON_SCREEN // zoom),
track=TRACK,
track_misses=TRACK_MISSES,
merge_passes=MERGE_PASSES,
)
verifier = live_copy = None
verified = mismatched = 0
print(
"detecting in %dx%d frames: %d pyramid levels, faces from %d to %d camera pixels"
% (frame_w, frame_h, len(detector.levels), detector.levels[0][6], detector.levels[-1][6])
)
# --- Display ---
displayio.release_displays()
framebuffer = picodvi.Framebuffer(
SCREEN_W,
SCREEN_H,
clk_dp=board.CKP,
clk_dn=board.CKN,
red_dp=board.D0P,
red_dn=board.D0N,
green_dp=board.D1P,
green_dn=board.D1N,
blue_dp=board.D2P,
blue_dn=board.D2N,
color_depth=16,
)
target = picogame.Framebuffer(framebuffer, SCREEN_W, SCREEN_H, native_rgb565=True)
overlay = picogame.Canvas(SCREEN_W, SCREEN_H, transparent=_CLEAR)
overlay.clear(_CLEAR)
video = None # the camera sprite, once a camera is connected
layers = [overlay]
def render():
picogame.render(target, layers, None, 0, 0, SCREEN_W, SCREEN_H)
class Box:
"""One face outline"""
def __init__(self):
self.visible = False
self.x = self.y = self.w = self.h = 0.0
self.seen = 0
def show(self, x, y, w, h, the_now):
if self.visible:
keep = SMOOTHING
self.x += (x - self.x) * (1 - keep)
self.y += (y - self.y) * (1 - keep)
self.w += (w - self.w) * (1 - keep)
self.h += (h - self.h) * (1 - keep)
else:
self.x, self.y, self.w, self.h = float(x), float(y), float(w), float(h)
self.visible = True
self.seen = the_now
def center(self):
return self.x + self.w / 2, self.y + self.h / 2
def draw(self):
x = int(self.x + 0.5)
y = int(self.y + 0.5)
w = int(self.w + 0.5)
h = int(self.h + 0.5)
for i in range(LINE):
if w - 2 * i > 0 and h - 2 * i > 0:
overlay.rect(x + i, y + i, w - 2 * i, h - 2 * i, BOX_COLOR)
boxes = [Box() for _ in range(MAX_FACES)]
def redraw_boxes():
overlay.clear(_CLEAR)
for box in boxes:
if box.visible:
box.draw()
def show_faces(the_faces, the_now): # pylint: disable=too-many-locals
"""Move each box to the nearest new face, or start a new box"""
matched = []
for face in the_faces[:MAX_FACES]:
x, y, w, h = face[0], face[1], face[2], face[3]
if MIRROR:
x = frame_w - x - w
x, y, w, h = x * zoom, y * zoom, w * zoom, h * zoom
cx, cy = x + w / 2, y + h / 2
best = None
best_distance = w
for box in boxes:
if box.visible and box not in matched:
bx, by = box.center()
distance = abs(bx - cx) + abs(by - cy)
if distance < best_distance:
best, best_distance = box, distance
if best is None:
for box in boxes:
if not box.visible:
best = box
break
if best is not None:
best.show(x, y, w, h, the_now)
matched.append(best)
def hide_stale_boxes(the_now):
changed = False
for box in boxes:
if box.visible and elapsed(the_now, box.seen) >= HOLD_MS:
box.visible = False
changed = True
return changed
# --- Camera session, reconnecting when it fails ---
camera = frame = None
retry_at = ticks_ms()
def disconnect(e):
global camera, frame, video, retry_at # pylint: disable=global-statement
if camera is not None:
camera.close()
camera = frame = None
if video is not None:
layers.remove(video)
video = None
detector.reset()
for box in boxes:
box.visible = False
redraw_boxes()
render()
retry_at = (ticks_ms() + 3000) & _TICKS_MASK
print("Camera problem, retrying in 3 s:", type(error).__name__, e)
gc.collect()
def connect():
global camera, frame, video # pylint: disable=global-statement
try:
camera = CameraSession(
CAMERA_MODE[0],
CAMERA_MODE[1],
DECODE_SCALE,
read_timeout_ms=CAMERA_WAIT_MS,
stale_seconds=5,
)
frame = memoryview(camera.bitmap).cast("B")
# displayio bitmaps hold RGB565 high byte first, which is picogame's
# transfer byte order, so picogame reads the camera bitmap directly.
picture = picogame.Bitmap(camera.bitmap, frame_w, frame_h)
video = picogame.Sprite(picture, 0, 0, flip_x=MIRROR)
video.scale = zoom
layers.insert(0, video)
print("Camera connected: %dx%d MJPEG decoded at %dx%d" % (CAMERA_MODE + (frame_w, frame_h)))
except (RuntimeError, OSError, ValueError, MemoryError) as error:
disconnect(error)
def print_faces(the_faces):
kind = "tracking" if detector.tracked else "full"
if not the_faces:
print("no face [%s pass, %d raw hits]" % (kind, detector.hits))
return
parts = ["%dx%d at (%d, %d), %d hits" % (w, h, x, y, n) for x, y, w, h, n in the_faces]
print(
"%d face%s: %s [%s pass, %d raw hits, %d ms]"
% (
len(the_faces),
"" if len(the_faces) == 1 else "s",
"; ".join(parts),
kind,
detector.hits,
detector.pass_ms,
)
)
render()
gc.collect()
print("free memory: %d" % gc.mem_free())
cam_frames = draws = passes = full_passes = 0
draw_ms = work_ms = pass_ms = features = hits = faces_seen = 0
had_faces = False
report_at = ticks_ms()
while True:
now = ticks_ms()
if camera is None and reached(now, retry_at):
connect()
new_frame = False
if camera is not None and not (PAUSE_CAMERA_DURING_SEARCH and detector.busy):
try:
new_frame = camera.poll()
except (RuntimeError, OSError, ValueError, MemoryError) as error:
disconnect(error)
if new_frame:
cam_frames += 1
if not detector.busy:
detector.start(frame)
boxes_changed = False
if detector.busy and detector.work(DETECT_SLICE_MS):
faces = detector.faces
show_faces(faces, ticks_ms())
boxes_changed = bool(faces)
passes += 1
full_passes += 0 if detector.tracked else 1
pass_ms += detector.pass_ms
work_ms += detector.work_ms
features += detector.features
hits += detector.hits
faces_seen += len(faces)
if PRINT_FACES and (faces or had_faces):
print_faces(faces)
had_faces = bool(faces)
if verifier is not None and not detector.tracked:
again = [tuple(f) for f in verifier.detect(live_copy)]
same = (verifier.hits, verifier.features) == (detector.hits, detector.features)
if same:
verified += 1
else:
mismatched += 1
print(
"verify: live pass %d hits, %d features, %d faces; same frame again"
" %d hits, %d features, %d faces -> %s"
% (
detector.hits,
detector.features,
len(faces),
verifier.hits,
verifier.features,
len(again),
"same" if same else "DIFFERENT",
)
)
if hide_stale_boxes(ticks_ms()):
boxes_changed = True
if boxes_changed:
redraw_boxes()
if new_frame or boxes_changed:
t0 = ticks_ms()
render()
draw_ms += elapsed(ticks_ms(), t0)
draws += 1
# debug printing
if REPORT_SECONDS and elapsed(ticks_ms(), report_at) >= REPORT_SECONDS * 1000:
n = max(passes, 1)
line = (
f"camera {cam_frames / REPORT_SECONDS:.1f} fps,"
f" screen {draws / REPORT_SECONDS:.1f} fps ({draw_ms / max(draws, 1):.0f} ms each)"
f" | passes {passes} ({full_passes} full):"
f" {pass_ms // n} ms start to finish, {work_ms // n} ms working,"
f" {features // n} features, {hits / n:.1f} raw hits, {faces_seen / n:.1f} faces"
f" | frame brightness {detector.brightness}, contrast {detector.contrast}"
)
if verifier is not None:
line += f" | verify: {verified} same, {mismatched} different"
if camera is not None:
snap = camera.snapshot()
line += (
f" | dropped {snap['partial_frames_dropped']},"
f" decode errors {snap['decode_errors']},"
f" max decode {snap['max_decode_ns'] / 1e6:.0f} ms"
)
print(line)
cam_frames = draws = passes = full_passes = 0
draw_ms = work_ms = pass_ms = features = hits = faces_seen = 0
report_at = (report_at + REPORT_SECONDS * 1000) & _TICKS_MASK
Upload the Code and Libraries to the Fruit Jam
After downloading the Project Bundle, plug your Fruit Jam into your computer's USB port with a known good USB data+power cable. You should see a new flash drive appear in the computer's File Explorer or Finder (depending on your operating system) called CIRCUITPY. Unzip the folder and copy the following items to the Fruit Jam's CIRCUITPY drive.
- lib folder
- code.py
- face_camera.py
- face_lbp.mpy
- frontalface.lbp
Your Fruit Jam CIRCUITPY drive should look like this after copying the files and folders:
Face LBP
The face_lbp.mpy file is a CircuitPython Turbo helper file that was compiled with mpy-cross for the RP2350 on the Fruit Jam. The original source Python file is also available on GitHub:
# SPDX-FileCopyrightText: 2026 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Face detection for CircuitPython turbo: an OpenCV LBP cascade in Viper."""
import array
import os
import micropython
from micropython import const
from supervisor import ticks_ms
_TICKS_MASK = const(0x1FFFFFFF) # ticks_ms() wraps at 2**29
# The cascade binary
_HEADER = const(16) # words before the stages
_STAGE_WORDS = const(3) # first weak classifier, count, threshold
_WEAK_WORDS = const(11) # feature, 8-word mask, two leaves
_FEATURE_WORDS = const(4) # x, y, block width, block height
# Slots of the scan kernel's argument array. Hits follow from _A_HITS.
_A_STRIDE = const(0) # integral table row stride, in words
_A_X0 = const(1) # window columns to try: X0, X0 + STEP, ... below X1
_A_X1 = const(2)
_A_Y0 = const(3) # window rows likewise
_A_Y1 = const(4)
_A_STEP = const(5)
_A_CAPACITY = const(6) # hits the array has room for
_A_WINDOWS = const(7) # out: windows tested (added to)
_A_FEATURES = const(8) # out: features evaluated (added to)
_A_HITS = const(16)
# Window rows per scan call
_ROWS_PER_CALL = const(4)
# pylint: disable=undefined-variable, too-many-locals, too-many-statements, too-many-boolean-expressions
# pylint: disable=too-many-branches, too-many-instance-attributes, too-many-arguments
def _elapsed(now, then):
return (now - then) & _TICKS_MASK
def _zeros(count):
"""An int array of count zeros, without building a list first."""
try:
return array.array("i", [0]) * count
except TypeError:
return array.array("i", bytes(4 * count))
@micropython.viper
def _gray(frame: ptr8, gray: ptr8, count: int, totals: ptr32):
"""RGB565 to 8-bit brightness. Sum of the brightness and of
its square / 256, for the frame's mean and contrast"""
total = 0
squares = 0
i = 0
j = 0
while j < count:
v = (frame[i] << 8) | frame[i + 1]
r = v >> 11
g = (v >> 5) & 63
b = v & 31
level = (
77 * ((r << 3) | (r >> 2)) + 150 * ((g << 2) | (g >> 4)) + 29 * ((b << 3) | (b >> 2))
) >> 8
gray[j] = level
total += level
squares += (level * level) >> 8
i += 2
j += 1
totals[0] = total
totals[1] = squares
@micropython.viper
def _resize(src: ptr8, dst: ptr8, args: ptr32):
"""Shrink an 8-bit image with bilinear filtering
args: source width and height, destination width and height,
then source pixels per destination pixel across and down
in 16.16 fixed point"""
src_w = args[0]
src_h = args[1]
dst_w = args[2]
dst_h = args[3]
step_x = args[4]
step_y = args[5]
out = 0
y = 0
while y < dst_h:
sy = ((((y << 1) + 1) * step_y) - 65536) >> 1
sy = max(sy, 0)
y0 = sy >> 16
fy = (sy >> 8) & 255
if y0 >= src_h - 1:
y0 = src_h - 1
fy = 0
row0 = y0 * src_w
row1 = row0
if fy:
row1 = row0 + src_w
x = 0
while x < dst_w:
sx = ((((x << 1) + 1) * step_x) - 65536) >> 1
sx = max(sx, 0)
x0 = sx >> 16
fx = (sx >> 8) & 255
if x0 >= src_w - 1:
x0 = src_w - 1
fx = 0
x1 = x0
if fx:
x1 = x0 + 1
top = src[row0 + x0] * (256 - fx) + src[row0 + x1] * fx
bottom = src[row1 + x0] * (256 - fx) + src[row1 + x1] * fx
dst[out + x] = (top * (256 - fy) + bottom * fy + 32768) >> 16
x += 1
out += dst_w
y += 1
@micropython.viper
def _integral(gray: ptr8, table: ptr32, args: ptr32):
"""Summed-area table: table[y * stride + x] is the sum of the pixels
above and left of (x, y); row 0 and column 0 are zero. args: width,
height, stride."""
width = args[0]
height = args[1]
stride = args[2]
x = 0
while x <= width:
table[x] = 0
x += 1
src = 0
above = 0
here = stride
y = 0
while y < height:
table[here] = 0
row_sum = 0
x = 0
while x < width:
row_sum += gray[src + x]
table[here + x + 1] = table[above + x + 1] + row_sum
x += 1
src += width
above = here
here += stride
y += 1
@micropython.viper
def _scan(table: ptr32, words: ptr32, offsets: ptr32, args: ptr32) -> int:
"""Run the cascade at each window position in args' range. Passing
positions are stored from args[_A_HITS] as x, y pairs, up to the
capacity; returns how many passed.
offsets holds, for every feature, the 16 integral-table corners of its
3x3 grid of blocks relative to the window's top-left corner."""
stride = args[_A_STRIDE]
x0 = args[_A_X0]
x1 = args[_A_X1]
y = args[_A_Y0]
y1 = args[_A_Y1]
step = args[_A_STEP]
capacity = args[_A_CAPACITY]
stage_end = _HEADER + _STAGE_WORDS * words[4]
first_weak = stage_end
windows = 0
features = 0
count = 0
while y < y1:
x = x0
while x < x1:
window = y * stride + x
windows += 1
passed = 1
skip = 0
stage = _HEADER
while stage < stage_end:
weak = first_weak + _WEAK_WORDS * words[stage]
weak_end = weak + _WEAK_WORDS * words[stage + 1]
total = 0
while weak < weak_end:
o = words[weak] << 4
# The 4x4 corners around the feature's 3x3 blocks
s0 = table[window + offsets[o]]
s1 = table[window + offsets[o + 1]]
s2 = table[window + offsets[o + 2]]
s3 = table[window + offsets[o + 3]]
s4 = table[window + offsets[o + 4]]
s5 = table[window + offsets[o + 5]]
s6 = table[window + offsets[o + 6]]
s7 = table[window + offsets[o + 7]]
s8 = table[window + offsets[o + 8]]
s9 = table[window + offsets[o + 9]]
s10 = table[window + offsets[o + 10]]
s11 = table[window + offsets[o + 11]]
s12 = table[window + offsets[o + 12]]
s13 = table[window + offsets[o + 13]]
s14 = table[window + offsets[o + 14]]
s15 = table[window + offsets[o + 15]]
center = s5 - s6 - s9 + s10
# Each outer block against the center, clockwise from
# the top left: one bit each of an 8-bit code
code = 0
if s0 - s1 - s4 + s5 >= center:
code = 128
if s1 - s2 - s5 + s6 >= center:
code |= 64
if s2 - s3 - s6 + s7 >= center:
code |= 32
if s6 - s7 - s10 + s11 >= center:
code |= 16
if s10 - s11 - s14 + s15 >= center:
code |= 8
if s9 - s10 - s13 + s14 >= center:
code |= 4
if s8 - s9 - s12 + s13 >= center:
code |= 2
if s4 - s5 - s8 + s9 >= center:
code |= 1
# Bit `code` of the 256-bit mask picks the leaf
if (words[weak + 1 + (code >> 5)] >> (code & 31)) & 1:
total += words[weak + 9]
else:
total += words[weak + 10]
features += 1
weak += _WEAK_WORDS
if total < words[stage + 2]:
passed = 0
if stage == _HEADER:
skip = 1
break
stage += _STAGE_WORDS
if passed:
if count < capacity:
args[_A_HITS + (count << 1)] = x
args[_A_HITS + (count << 1) + 1] = y
count += 1
x += step
if skip:
x += step
y += step
args[_A_WINDOWS] += windows
args[_A_FEATURES] += features
return count
def _divide_round(total, n):
"""total / n to the nearest int"""
q = total // n
r = total - q * n
if 2 * r > n or (2 * r == n and q & 1):
q += 1
return q
def group_rectangles(rects, min_neighbors):
"""OpenCV's groupRectangles with eps 0.2, in integers: cluster similar
rectangles, average each cluster, keep those with more than
min_neighbors members, and drop small ones inside a stronger big one.
"""
n = len(rects)
if min_neighbors <= 0:
return [(r[0], r[1], r[2], r[3], 1) for r in rects]
parent = list(range(n))
def root(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i in range(n):
ax, ay, aw, ah = rects[i]
for j in range(i + 1, n):
bx, by, bw, bh = rects[j]
limit = min(aw, bw) + min(ah, bh)
if (
10 * abs(ax - bx) <= limit
and 10 * abs(ay - by) <= limit
and 10 * abs(ax + aw - bx - bw) <= limit
and 10 * abs(ay + ah - by - bh) <= limit
):
a = root(i)
b = root(j)
if a != b:
parent[b] = a
sums = {}
for i in range(n):
x, y, w, h = rects[i]
total = sums.get(root(i))
if total is None:
sums[root(i)] = [x, y, w, h, 1]
else:
total[0] += x
total[1] += y
total[2] += w
total[3] += h
total[4] += 1
clusters = []
for total in sums.values():
k = total[4]
if k > min_neighbors:
clusters.append(
(
_divide_round(total[0], k),
_divide_round(total[1], k),
_divide_round(total[2], k),
_divide_round(total[3], k),
k,
)
)
faces = []
for face in clusters:
x1, y1, w1, h1, n1 = face
inside = False
for other in clusters:
if other is face:
continue
x2, y2, w2, h2, n2 = other
dx = (w2 * 2 + 5) // 10 # round(0.2 * w2): never a tie
dy = (h2 * 2 + 5) // 10
if (
x1 >= x2 - dx
and y1 >= y2 - dy
and x1 + w1 <= x2 + w2 + dx
and y1 + h1 <= y2 + h2 + dy
and (n2 > max(3, n1) or n1 < 3)
):
inside = True
break
if not inside:
faces.append(face)
faces.sort(key=lambda f: -f[2])
return faces
def load_cascade(path):
"""Read a .lbp file straight into an int array"""
size = os.stat(path)[6]
if size % 4 or size < 4 * _HEADER:
raise ValueError("%s is not a cascade from lbp_convert.py" % path)
words = _zeros(size // 4)
with open(path, "rb") as file:
if file.readinto(words) != size:
raise ValueError("%s: short read" % path)
if words[0] != 0x4350424C: # the bytes "LBPC", little-endian
raise ValueError("%s is not a cascade from lbp_convert.py" % path)
if words[1] != 1:
raise ValueError("cascade format version %d isn't supported" % words[1])
width, height = words[2], words[3]
stages, weaks, features = words[4], words[5], words[6]
first_weak = _HEADER + _STAGE_WORDS * stages
first_feature = first_weak + _WEAK_WORDS * weaks
if stages < 1 or weaks < 1 or features < 1:
raise ValueError("empty cascade")
if len(words) != first_feature + _FEATURE_WORDS * features:
raise ValueError("cascade length doesn't match its header")
for i in range(stages):
first = words[_HEADER + 3 * i]
count = words[_HEADER + 3 * i + 1]
if count < 1 or first < 0 or first + count > weaks:
raise ValueError("stage %d is out of range" % i)
for i in range(weaks):
feature = words[first_weak + _WEAK_WORDS * i]
if not 0 <= feature < features:
raise ValueError("weak classifier %d is out of range" % i)
for i in range(features):
x, y, w, h = words[first_feature + 4 * i : first_feature + 4 * i + 4]
if w < 1 or h < 1 or x < 0 or y < 0 or x + 3 * w > width or y + 3 * h > height:
raise ValueError("feature %d is outside the window" % i)
return words
class FaceDetector:
"""Finds faces in width x height RGB565 frames.
:param cascade_path: the .lbp file from lbp_convert.py
:param scale_factor: size step between pyramid levels, as in OpenCV.
1.2 is a good balance; 1.1 finds a few more faces and takes about
twice as long.
:param min_neighbors: number of hits a face needs
:param min_size: smallest face to look for, in pixels
:param max_size: largest face to look for (0 for the frame height)
:param track: after finding faces, search only near them for the next
few passes
:param full_every: with track, cover the whole frame at least this
often, counting passes
:param track_misses: with track, how many tracking passes in a row may
miss before going back to searching the whole frame
:param merge_passes: group each pass's hits together with the previous
pass's, so a face needs min_neighbors hits across two frames rather
than in one
:param keep_hits: once a face has been found, it stays found while at
least this many of a pass's raw hits land on it.
:param capacity: most hits kept per scan call
"""
def __init__(
self,
cascade_path,
width=160,
height=120,
*,
scale_factor=1.2,
min_neighbors=3,
min_size=0,
max_size=0,
track=True,
full_every=4,
track_misses=2,
merge_passes=True,
keep_hits=1,
capacity=128,
):
if not 1.01 <= scale_factor <= 2.0:
raise ValueError("scale_factor must be 1.01 to 2.0")
if not (32 <= width <= 640 and 32 <= height <= 480):
raise ValueError("frame size out of range")
self.words = load_cascade(cascade_path)
words = self.words
self.window_w, self.window_h = words[2], words[3]
if width < self.window_w or height < self.window_h:
raise ValueError("frame is smaller than the cascade window")
self.width = width
self.height = height
self.min_neighbors = min_neighbors
self.track = track
self.full_every = max(1, full_every)
self.track_misses = max(0, track_misses)
self.merge_passes = merge_passes
self.keep_hits = keep_hits
self.stride = stride = width + 1
count = words[6]
first_feature = _HEADER + _STAGE_WORDS * words[4] + _WEAK_WORDS * words[5]
self.offsets = offsets = _zeros(16 * count)
for i in range(count):
fx, fy, fw, fh = words[first_feature + 4 * i : first_feature + 4 * i + 4]
for r in range(4):
for c in range(4):
offsets[16 * i + 4 * r + c] = (fy + r * fh) * stride + fx + c * fw
self.gray = bytearray(width * height)
self.level = bytearray(width * height)
self.table = _zeros(stride * (height + 1))
self.capacity = capacity
self.args = _zeros(_A_HITS + 2 * capacity)
self.args[_A_STRIDE] = stride
self.args[_A_CAPACITY] = capacity
self._resize_args = array.array("i", [width, height, 0, 0, 0, 0])
self._integral_args = array.array("i", [0, 0, stride])
self._totals = array.array("i", [0, 0])
self.levels = []
largest = max_size or min(width, height)
step_q16 = int(scale_factor * 65536 + 0.5)
factor = 65536 # 1.0
while True:
win_w = (self.window_w * factor + 32768) >> 16
win_h = (self.window_h * factor + 32768) >> 16
if win_w > min(largest, width) or win_h > min(largest, height):
break
level_w = (width * 65536 + factor // 2) // factor
level_h = (height * 65536 + factor // 2) // factor
if (win_w >= min_size and win_h >= min_size and
level_w >= self.window_w and level_h >= self.window_h):
self.levels.append(
(
factor, # level pixels -> frame pixels, 16.16
level_w,
level_h,
(width * 65536 + level_w // 2) // level_w, # resize steps
(height * 65536 + level_h // 2) // level_h,
1 if factor >= 131072 else 2, # window spacing
win_w,
win_h,
)
)
factor = (factor * step_q16 + 32768) >> 16
if not self.levels:
raise ValueError("no pyramid levels for this size range")
self.faces = []
self._target = [] # the faces tracking passes look near
self._misses = 0
self._previous = [] # the last pass's hits, for merge_passes
self.busy = False
self.tracked = False # whether the last pass was a tracking pass
self._since_full = 0
self._plan = []
self._job = 0
self._row = -1
self._rects = []
# Statistics of the last finished pass
self.pass_ms = 0 # start() to the faces being ready
self.work_ms = 0 # time spent inside work()
self.windows = 0
self.features = 0
self.hits = 0 # windows that passed the cascade, before grouping
self.kept = 0 # faces in the last result held on by keep_hits
# Of the last frame given to start(): mean brightness, and contrast
# as the standard deviation of brightness (both 0-255)
self.brightness = 0
self.contrast = 0
self._started = 0
self._work = 0
def start(self, frame):
"""Begin a pass on frame: width x height RGB565, high byte first."""
if len(frame) != 2 * self.width * self.height:
raise ValueError("frame must be %d bytes" % (2 * self.width * self.height))
self._started = ticks_ms()
pixels = self.width * self.height
_gray(frame, self.gray, pixels, self._totals)
mean = self._totals[0] / pixels
self.brightness = int(mean + 0.5)
self.contrast = int(max(0.0, self._totals[1] * 256 / pixels - mean * mean) ** 0.5 + 0.5)
self._plan = self._make_plan()
self._job = 0
self._row = -1
self._rects = []
self._work = 0
self.args[_A_WINDOWS] = 0
self.args[_A_FEATURES] = 0
self.busy = True
def cancel(self):
"""Abandon the pass in progress."""
self.busy = False
self._plan = []
def reset(self):
"""Cancel and forget everything earlier passes found, so the next
pass is a full one"""
self.cancel()
self.faces = []
self._target = []
self._misses = 0
self._previous = []
self._since_full = 0
def work(self, budget_ms):
"""Do about budget_ms of the pass (at least one step). Returns True
when the pass is done and ``faces`` holds its result."""
if not self.busy:
return False
began = ticks_ms()
while True:
if self._job >= len(self._plan):
self._finish(began)
return True
self._step()
if _elapsed(ticks_ms(), began) >= budget_ms:
self._work += _elapsed(ticks_ms(), began)
return False
def detect(self, frame):
"""A whole pass at once. It forgets earlier passes, so the result
depends only on this frame."""
self.reset()
self.start(frame)
while not self.work(1000):
pass
return self.faces
def _make_plan(self):
"""The levels and window ranges for this pass"""
full = not (self.track and self._target) or self._since_full + 1 >= self.full_every
plan = []
if full:
self._since_full = 0
self.tracked = False
for i, level in enumerate(self.levels):
plan.append((i, 0, level[1] - self.window_w + 1, 0, level[2] - self.window_h + 1))
return plan
self._since_full += 1
self.tracked = True
left = top = 1 << 20
right = bottom = -1
small = 1 << 20
big = 0
for x, y, w, h, _ in self._target: # pylint: disable=unused-variable
margin = w // 2
left = min(left, x - margin)
top = min(top, y - margin)
right = max(right, x + margin)
bottom = max(bottom, y + margin)
small = min(small, w)
big = max(big, w)
for i, (scale, level_w, level_h, _, _, step, win_w, _) in enumerate(self.levels):
if win_w * 10 < small * 7 or win_w * 20 > big * 29:
continue
columns = level_w - self.window_w + 1
rows = level_h - self.window_h + 1
# Frame pixels to this level's positions, on the step grid
x0 = max(0, left * 65536 // scale) // step * step
y0 = max(0, top * 65536 // scale) // step * step
x1 = min(columns, (right * 65536 + scale - 1) // scale + 1)
y1 = min(rows, (bottom * 65536 + scale - 1) // scale + 1)
if x0 < x1 and y0 < y1:
plan.append((i, x0, x1, y0, y1))
return plan
def _step(self):
index, x0, x1, y0, y1 = self._plan[self._job]
scale, level_w, level_h, step_x, step_y, step, win_w, win_h = self.levels[index]
args = self.args
if self._row < 0:
# Shrink the frame to this level and build its integral table
if level_w == self.width and level_h == self.height:
source = self.gray
else:
resize_args = self._resize_args
resize_args[2] = level_w
resize_args[3] = level_h
resize_args[4] = step_x
resize_args[5] = step_y
_resize(self.gray, self.level, resize_args)
source = self.level
self._integral_args[0] = level_w
self._integral_args[1] = level_h
_integral(source, self.table, self._integral_args)
self._row = y0
return
row_end = min(y1, self._row + _ROWS_PER_CALL * step)
args[_A_X0] = x0
args[_A_X1] = x1
args[_A_Y0] = self._row
args[_A_Y1] = row_end
args[_A_STEP] = step
found = min(_scan(self.table, self.words, self.offsets, args), self.capacity)
width, height = self.width, self.height
rects = self._rects
for i in range(found):
# Back to frame pixels, clipped to the frame like OpenCV
x = (args[_A_HITS + 2 * i] * scale + 32768) >> 16
y = (args[_A_HITS + 2 * i + 1] * scale + 32768) >> 16
rects.append((x, y, min(win_w, width - x), min(win_h, height - y)))
self._row = row_end
if self._row >= y1:
self._job += 1
self._row = -1
def _keep(self, rects):
"""Add back each followed face that lost min_neighbors support but
still has keep_hits of this pass's hits on it"""
faces = self.faces
for tx, ty, tw, th, _ in self._target:
found = False
for x, y, w, h, _ in faces:
cx, cy = x + w // 2, y + h // 2
if tx <= cx < tx + tw and ty <= cy < ty + th:
found = True # still found the normal way
break
if found:
continue
sx = sy = sw = sh = n = 0
for x, y, w, h in rects:
cx, cy = x + w // 2, y + h // 2
if (tx <= cx < tx + tw and ty <= cy < ty + th
and 5 * w >= 3 * tw and 5 * w <= 8 * tw):
sx += x
sy += y
sw += w
sh += h
n += 1
if n and n >= self.keep_hits:
faces.append((sx // n, sy // n, sw // n, sh // n, n))
self.kept += 1
if self.kept:
faces.sort(key=lambda f: -f[2])
def _finish(self, began):
now = ticks_ms()
self._work += _elapsed(now, began)
rects = self._rects
if self.merge_passes and self._previous:
self.faces = group_rectangles(rects + self._previous, self.min_neighbors)
else:
self.faces = group_rectangles(rects, self.min_neighbors)
self._previous = rects
self.kept = 0
if self.keep_hits and self._target:
self._keep(rects)
# Where the next tracking pass looks: the new faces, or after a miss
# the old ones again, a few times, before a full search.
if self.faces:
self._target = self.faces
self._misses = 0
elif self.tracked and self._misses < self.track_misses:
self._misses += 1
else:
self._target = []
self._misses = 0
self.busy = False
self.pass_ms = _elapsed(now, self._started)
self.work_ms = self._work
self.windows = self.args[_A_WINDOWS]
self.features = self.args[_A_FEATURES]
self.hits = len(self._rects)
To build from source, run mpy-cross:
mpy-cross -march=armv7emsp face_lbp.py
This file handles the face detection by running OpenCV's LBP frontal face cascade, which uses the Viola-Jones object detection framework, over each frame from the camera feed. It combines the positive hits across frames to confirm that a face is found. After a face is found, it can follow the face until it goes off screen.
The cascade model is converted from an XML file to a .LBP (local binary pattern matrix) file with this lbp_convert.py script. You can pass other XML models to this script to try running them in CircuitPython. LBP models are light weight and meant to run on smaller processors, like microcontrollers. They also use integer comparisons for calculations, which makes them a great target for CircuitPython Turbo Viper helpers.
# SPDX-FileCopyrightText: 2026 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Convert an OpenCV LBP cascade (XML) into a compact binary for CircuitPython.
To run::
python lbp_convert.py lbpcascade_frontalface.xml frontalface.lbp
The binary is a flat run of little-endian signed 32-bit words, so the board
can read it straight into an ``array.array("i")`` with ``readinto()`` and a
Viper module can use it as a ``ptr32``.
====== =============================================================
words contents
====== =============================================================
0 magic: the bytes ``LBPC``
1 format version (1)
2-3 detection window width, height in pixels
4 stage count
5 weak classifier count, all stages together
6 feature count
7 fixed-point shift
8-15 reserved, 0
then 3 words per stage: first weak classifier, weak count, threshold
then 11 words per weak classifier: feature index, 8-word category
mask, leaf added when the LBP code's bit is set, leaf when clear
then 4 words per feature: x, y, block width, block height
====== =============================================================
"""
import argparse
import re
import struct
import sys
import xml.etree.ElementTree as ET
MAGIC = struct.unpack("<i", b"LBPC")[0]
VERSION = 1
HEADER_WORDS = 16
STAGE_WORDS = 3
WEAK_WORDS = 11
FEATURE_WORDS = 4
# OpenCV subtracts this from every stage threshold when it loads a cascade.
THRESHOLD_EPS = 1e-5
INT32_MIN, INT32_MAX = -(2**31), 2**31 - 1
# pylint: disable=too-many-boolean-expressions, too-many-locals, too-many-branches
class CascadeError(ValueError):
"""If the XML isn't a cascade this converter can handle."""
def _text(node, tag):
child = node.find(tag)
if child is None or child.text is None:
raise CascadeError("missing <%s>" % tag)
return child.text.strip()
def _items(node, tag):
child = node.find(tag)
if child is None:
raise CascadeError("missing <%s>" % tag)
return child.findall("_")
def parse_cascade(path):
"""Read an LBP cascade XML into plain Python numbers."""
with open(path, "rb") as file:
raw = file.read()
text = raw.decode("utf-8", errors="replace")
match = re.match(r"\s*(?:<\?xml[^>]*\?>\s*)?<!--(.*?)-->", text, re.S)
notice = match.group(1).replace("\r", "").strip("\n") if match else ""
root = ET.fromstring(raw)
cascade = root.find("cascade")
if cascade is None:
raise CascadeError(
"no <cascade>: this looks like an old-format cascade; only the "
"opencv_traincascade format is supported"
)
feature_type = _text(cascade, "featureType")
if feature_type != "LBP":
raise CascadeError("featureType is %s; only LBP is supported" % feature_type)
if _text(cascade, "stageType") != "BOOST":
raise CascadeError("only BOOST stages are supported")
params = cascade.find("stageParams")
if params is not None and params.find("maxDepth") is not None:
if int(_text(params, "maxDepth")) != 1:
raise CascadeError("only depth-1 weak classifiers (stumps) are supported")
width = int(_text(cascade, "width"))
height = int(_text(cascade, "height"))
features = []
for item in _items(cascade, "features"):
values = [int(v) for v in _text(item, "rect").split()]
if len(values) != 4:
raise CascadeError("an LBP feature rect needs 4 numbers")
x, y, w, h = values
# The feature is a 3x3 grid of w x h blocks and must fit the window.
if w < 1 or h < 1 or x < 0 or y < 0 or x + 3 * w > width or y + 3 * h > height:
raise CascadeError("feature %d %r is outside the window" % (len(features), values))
features.append((x, y, w, h))
stages = []
for stage in _items(cascade, "stages"):
threshold = float(_text(stage, "stageThreshold"))
weaks = []
for weak in _items(stage, "weakClassifiers"):
nodes = [int(v) for v in _text(weak, "internalNodes").split()]
leaves = [float(v) for v in _text(weak, "leafValues").split()]
# A stump: left = 0, right = -1 (both leaves), the feature, then
# the 256-bit category mask as 8 signed 32-bit words.
if len(nodes) != 11 or nodes[0] != 0 or nodes[1] != -1 or len(leaves) != 2:
raise CascadeError("weak classifier is not a categorical stump")
feature = nodes[2]
if not 0 <= feature < len(features):
raise CascadeError("feature index %d out of range" % feature)
weaks.append((feature, nodes[3:11], leaves[0], leaves[1]))
if not weaks:
raise CascadeError("stage %d has no weak classifiers" % len(stages))
stages.append((threshold, weaks))
if not stages:
raise CascadeError("no stages")
return {
"width": width,
"height": height,
"stages": stages,
"features": features,
"notice": notice,
}
def _fixed(value, shift):
result = int(round(value * (1 << shift)))
if not INT32_MIN <= result <= INT32_MAX:
raise CascadeError("%r doesn't fit 32 bits at shift %d" % (value, shift))
return result
def to_words(cascade, shift=20):
"""The binary layout as a list of ints."""
stages = cascade["stages"]
features = cascade["features"]
weak_count = sum(len(weaks) for _, weaks in stages)
words = [0] * HEADER_WORDS
words[0:8] = [
MAGIC,
VERSION,
cascade["width"],
cascade["height"],
len(stages),
weak_count,
len(features),
shift,
]
first = 0
largest = 0
for threshold, weaks in stages:
words += [first, len(weaks), _fixed(threshold - THRESHOLD_EPS, shift)]
first += len(weaks)
largest = max(largest, sum(max(abs(a), abs(b)) for _, _, a, b in weaks))
# The kernel adds up to one stage's leaves; make sure that can't wrap.
if largest * (1 << shift) >= 2**30:
raise CascadeError("a stage's leaf sum could overflow at shift %d" % shift)
for _, weaks in stages:
for feature, mask, leaf_set, leaf_clear in weaks:
words.append(feature)
words += mask
words += [_fixed(leaf_set, shift), _fixed(leaf_clear, shift)]
for feature in features:
words += list(feature)
return words
def write_binary(words, path):
with open(path, "wb") as file:
file.write(struct.pack("<%di" % len(words), *words))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("xml", help="OpenCV LBP cascade, e.g. lbpcascade_frontalface.xml")
parser.add_argument("output", help="binary to write, e.g. frontalface.lbp")
parser.add_argument(
"--shift",
type=int,
default=20,
help="fixed-point bits after the binary point (default 20)",
)
args = parser.parse_args(argv)
try:
cascade = parse_cascade(args.xml)
words = to_words(cascade, args.shift)
except (CascadeError, ET.ParseError) as error:
sys.exit("%s: %s" % (args.xml, error))
write_binary(words, args.output)
weak_counts = [len(weaks) for _, weaks in cascade["stages"]]
print(
"%s: %dx%d window, %d stages, %d weak classifiers, %d features"
% (
args.xml,
cascade["width"],
cascade["height"],
len(weak_counts),
sum(weak_counts),
len(cascade["features"]),
)
)
print("weak classifiers per stage:", " ".join(str(n) for n in weak_counts))
print("wrote %s: %d bytes (shift %d)" % (args.output, 4 * len(words), args.shift))
notice_path = args.output + ".NOTICE.txt"
with open(notice_path, "w") as file:
file.write("Converted by lbp_convert.py from %s\n" % args.xml)
file.write("Keep this notice with the converted cascade.\n\n")
if cascade["notice"]:
file.write(cascade["notice"] + "\n")
else:
file.write("(The source XML carried no comment header.)\n")
print("wrote %s" % notice_path)
if __name__ == "__main__":
main()
Face Camera
This file manages the USB host webcam session with the Adafruit_USB_Host_Camera library. It connects to the camera and initiates the correct mode and resolution (MJPEG at 320x240). It then decodes each frame as a bitmap with jpegio. It also has logic to reconnect and restart the session if the connection is lost.
# SPDX-FileCopyrightText: 2026 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""MJPEG camera session built on adafruit_usb_host_camera"""
import time
import adafruit_usb_host_camera
import displayio
import jpegio
class CameraSession:
"""One streaming session. ``bitmap`` holds the newest decoded frame"""
def __init__(self, mode_width=320, mode_height=240, scale=1,
read_timeout_ms=5, stale_seconds=5):
if (isinstance(read_timeout_ms, bool) or not isinstance(read_timeout_ms, int)
or not 1 <= read_timeout_ms <= 100):
raise ValueError("read timeout must be 1..100 ms")
if not 1 <= stale_seconds <= 120:
raise ValueError("stale deadline must be 1..120 seconds")
if scale not in (0, 1, 2, 3):
raise ValueError("scale must be 0..3 (1, 1/2, 1/4 or 1/8 size)")
self.closed = self.valid = False
self.mode = None
self._camera = None
self.mode_width, self.mode_height = mode_width, mode_height
self.scale = scale
self.width = mode_width >> scale
self.height = mode_height >> scale
self._timeout = read_timeout_ms / 1000
self._stale_ns = int(stale_seconds * 1_000_000_000)
self._decode_errors_in_row = 0
self._stats = {
"polls": 0,
"frames": 0,
"no_frame_yet": 0,
"decode_errors": 0,
"max_poll_ns": 0,
"max_decode_ns": 0,
}
# Raises ValueError when no UVC camera is attached.
self._camera = adafruit_usb_host_camera.UVCCamera()
try:
mode = self._camera.find_mode(mode_width, mode_height,
adafruit_usb_host_camera.FORMAT_MJPEG)
if mode is None or (mode.width, mode.height) != (mode_width, mode_height):
raise ValueError(
f"camera has no {mode_width}x{mode_height} MJPEG mode (closest: {mode})"
)
self._camera.start(mode)
self.mode = mode
self.bitmap = displayio.Bitmap(self.width, self.height, 65536)
self._decoder = jpegio.JpegDecoder()
except BaseException:
self.close()
raise
self._started_ns = self._last_frame_ns = time.monotonic_ns()
def poll(self):
"""Take in whatever code.py has buffered. Returns True when a new
frame was decoded into ``bitmap``; False when none is complete yet."""
if self.closed:
raise RuntimeError("camera closed")
start = time.monotonic_ns()
if start - self._last_frame_ns >= self._stale_ns:
self.close()
raise RuntimeError("camera stale: no frame for too long")
self._stats["polls"] += 1
try:
frame = self._camera.capture(timeout=self._timeout)
except RuntimeError:
self._stats["no_frame_yet"] += 1
return False
finally:
elapsed = time.monotonic_ns() - start
self._stats["max_poll_ns"] = max(self._stats["max_poll_ns"], elapsed)
try:
started = time.monotonic_ns()
jpeg = self._camera.add_huffman_tables(frame)
if self._decoder.open(jpeg) != (self.mode_width, self.mode_height):
raise ValueError("unexpected JPEG dimensions")
self._decoder.decode(self.bitmap, scale=self.scale)
decoded = time.monotonic_ns()
self._stats["max_decode_ns"] = max(self._stats["max_decode_ns"], decoded - started)
except (RuntimeError, ValueError, OSError) as error:
self._stats["decode_errors"] += 1
self._decode_errors_in_row += 1
self.valid = False
if self._decode_errors_in_row >= 5:
self.close()
raise RuntimeError("repeated camera decode failure") from error
return False
self._decode_errors_in_row = 0
self.valid = True
self._last_frame_ns = decoded
self._stats["frames"] += 1
return True
def snapshot(self):
"""Counters for the serial report."""
result = dict(self._stats)
camera = self._camera
lost = camera.lost_packets if camera else 0
bad = camera.dropped_frames if camera else 0
result.update(
{
"valid": self.valid,
"closed": self.closed,
"mode": repr(self.mode),
"partial_frames_dropped": lost + bad,
"lost_packets": lost,
"invalid_frames": bad,
"read_errors": camera.read_errors if camera else 0,
"elapsed_ns": time.monotonic_ns() - self._started_ns,
}
)
return result
def close(self):
if self.closed:
return
self.closed = True
self.valid = False
camera = self._camera
if camera is not None:
try:
camera.stop()
except (OSError, RuntimeError):
pass
And finally, code.py
code.py controls initializing the PicoDVI output through picogame and starting the connection to the C270 camera. It also handles drawing the boxes around faces when they are detected. In the loop, it calls into face_lbp.mpy to pass the next camera frame, put it through the face detection model and redraw the camera feed to the DVI display.
# SPDX-FileCopyrightText: 2026 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Face detector on Fruit Jam with a Logitech C270
Uses the Frontal Face cascade model from OpenCV.
The feed from the C270 is displayed through DVI. When a face is detected,
a green box is drawn around the face.
"""
import gc
import board
import displayio
import picodvi
import picogame
from supervisor import ticks_ms
from face_lbp import FaceDetector
from face_camera import CameraSession
# --- Camera ---
CAMERA_MODE = (320, 240)
DECODE_SCALE = 1
CAMERA_WAIT_MS = 3 # how long each check waits for a frame
MIRROR = True
# --- Face detection ---
CASCADE_PATH = "/frontalface.lbp"
SCALE_FACTOR = 1.3 # size step between searches; 1.1 is finer and slower
MIN_NEIGHBORS = 1 # raise for fewer false faces, lower to find more
# Smallest face to look for, in screen pixels.
# 48 is the smallest a 160x120 picture can show; with DECODE_SCALE 0, a
# smaller value finds faces farther away but takes much longer.
MIN_FACE_ON_SCREEN = 48
DETECT_SLICE_MS = 10 # detection work per loop pass, between video frames
TRACK = True # after finding a face, search near it first
TRACK_MISSES = 5 # tracking passes that may miss before a full search again
# Combine each pass's hits with the previous pass's, so a face needs
# MIN_NEIGHBORS + 1 hits across two frames rather than in one frame.
MERGE_PASSES = True
PRINT_FACES = True
# Debugging: don't take camera frames (or redraw) while a search is running.
PAUSE_CAMERA_DURING_SEARCH = False
# --- Screen ---
SCREEN_W, SCREEN_H = 320, 240
WAIT_FOR_VBLANK = False # True avoids tearing, but can wait up to a frame
BOX_COLOR = picogame.rgb565(0, 255, 0)
LINE = 2 # box line thickness in screen pixels
MAX_FACES = 3
HOLD_MS = 1200 # keep a box this long after its face was last found
SMOOTHING = 0.7 # 0 jumps straight to each new position, near 1 glides
REPORT_SECONDS = 4 # 0 for no timing reports
_TICKS_MASK = 0x1FFFFFFF # ticks_ms() wraps at 2**29
_CLEAR = picogame.rgb565(255, 0, 255) # the overlay's transparent color
frame_w = CAMERA_MODE[0] >> DECODE_SCALE
frame_h = CAMERA_MODE[1] >> DECODE_SCALE
zoom = SCREEN_W // frame_w # screen pixels per camera pixel
def elapsed(the_now, then):
return (the_now - then) & _TICKS_MASK
def reached(the_now, deadline):
"""Whether ticks_ms() time now is at or past deadline, across a wrap."""
return elapsed(the_now, deadline) < (_TICKS_MASK >> 1)
gc.collect()
# --- The detector, while memory is unfragmented ---
detector = FaceDetector(
CASCADE_PATH,
frame_w,
frame_h,
scale_factor=SCALE_FACTOR,
min_neighbors=MIN_NEIGHBORS,
min_size=max(0, MIN_FACE_ON_SCREEN // zoom),
track=TRACK,
track_misses=TRACK_MISSES,
merge_passes=MERGE_PASSES,
)
verifier = live_copy = None
verified = mismatched = 0
print(
"detecting in %dx%d frames: %d pyramid levels, faces from %d to %d camera pixels"
% (frame_w, frame_h, len(detector.levels), detector.levels[0][6], detector.levels[-1][6])
)
# --- Display ---
displayio.release_displays()
framebuffer = picodvi.Framebuffer(
SCREEN_W,
SCREEN_H,
clk_dp=board.CKP,
clk_dn=board.CKN,
red_dp=board.D0P,
red_dn=board.D0N,
green_dp=board.D1P,
green_dn=board.D1N,
blue_dp=board.D2P,
blue_dn=board.D2N,
color_depth=16,
)
target = picogame.Framebuffer(framebuffer, SCREEN_W, SCREEN_H, native_rgb565=True)
overlay = picogame.Canvas(SCREEN_W, SCREEN_H, transparent=_CLEAR)
overlay.clear(_CLEAR)
video = None # the camera sprite, once a camera is connected
layers = [overlay]
def render():
picogame.render(target, layers, None, 0, 0, SCREEN_W, SCREEN_H)
class Box:
"""One face outline"""
def __init__(self):
self.visible = False
self.x = self.y = self.w = self.h = 0.0
self.seen = 0
def show(self, x, y, w, h, the_now):
if self.visible:
keep = SMOOTHING
self.x += (x - self.x) * (1 - keep)
self.y += (y - self.y) * (1 - keep)
self.w += (w - self.w) * (1 - keep)
self.h += (h - self.h) * (1 - keep)
else:
self.x, self.y, self.w, self.h = float(x), float(y), float(w), float(h)
self.visible = True
self.seen = the_now
def center(self):
return self.x + self.w / 2, self.y + self.h / 2
def draw(self):
x = int(self.x + 0.5)
y = int(self.y + 0.5)
w = int(self.w + 0.5)
h = int(self.h + 0.5)
for i in range(LINE):
if w - 2 * i > 0 and h - 2 * i > 0:
overlay.rect(x + i, y + i, w - 2 * i, h - 2 * i, BOX_COLOR)
boxes = [Box() for _ in range(MAX_FACES)]
def redraw_boxes():
overlay.clear(_CLEAR)
for box in boxes:
if box.visible:
box.draw()
def show_faces(the_faces, the_now): # pylint: disable=too-many-locals
"""Move each box to the nearest new face, or start a new box"""
matched = []
for face in the_faces[:MAX_FACES]:
x, y, w, h = face[0], face[1], face[2], face[3]
if MIRROR:
x = frame_w - x - w
x, y, w, h = x * zoom, y * zoom, w * zoom, h * zoom
cx, cy = x + w / 2, y + h / 2
best = None
best_distance = w
for box in boxes:
if box.visible and box not in matched:
bx, by = box.center()
distance = abs(bx - cx) + abs(by - cy)
if distance < best_distance:
best, best_distance = box, distance
if best is None:
for box in boxes:
if not box.visible:
best = box
break
if best is not None:
best.show(x, y, w, h, the_now)
matched.append(best)
def hide_stale_boxes(the_now):
changed = False
for box in boxes:
if box.visible and elapsed(the_now, box.seen) >= HOLD_MS:
box.visible = False
changed = True
return changed
# --- Camera session, reconnecting when it fails ---
camera = frame = None
retry_at = ticks_ms()
def disconnect(e):
global camera, frame, video, retry_at # pylint: disable=global-statement
if camera is not None:
camera.close()
camera = frame = None
if video is not None:
layers.remove(video)
video = None
detector.reset()
for box in boxes:
box.visible = False
redraw_boxes()
render()
retry_at = (ticks_ms() + 3000) & _TICKS_MASK
print("Camera problem, retrying in 3 s:", type(error).__name__, e)
gc.collect()
def connect():
global camera, frame, video # pylint: disable=global-statement
try:
camera = CameraSession(
CAMERA_MODE[0],
CAMERA_MODE[1],
DECODE_SCALE,
read_timeout_ms=CAMERA_WAIT_MS,
stale_seconds=5,
)
frame = memoryview(camera.bitmap).cast("B")
# displayio bitmaps hold RGB565 high byte first, which is picogame's
# transfer byte order, so picogame reads the camera bitmap directly.
picture = picogame.Bitmap(camera.bitmap, frame_w, frame_h)
video = picogame.Sprite(picture, 0, 0, flip_x=MIRROR)
video.scale = zoom
layers.insert(0, video)
print("Camera connected: %dx%d MJPEG decoded at %dx%d" % (CAMERA_MODE + (frame_w, frame_h)))
except (RuntimeError, OSError, ValueError, MemoryError) as error:
disconnect(error)
def print_faces(the_faces):
kind = "tracking" if detector.tracked else "full"
if not the_faces:
print("no face [%s pass, %d raw hits]" % (kind, detector.hits))
return
parts = ["%dx%d at (%d, %d), %d hits" % (w, h, x, y, n) for x, y, w, h, n in the_faces]
print(
"%d face%s: %s [%s pass, %d raw hits, %d ms]"
% (
len(the_faces),
"" if len(the_faces) == 1 else "s",
"; ".join(parts),
kind,
detector.hits,
detector.pass_ms,
)
)
render()
gc.collect()
print("free memory: %d" % gc.mem_free())
cam_frames = draws = passes = full_passes = 0
draw_ms = work_ms = pass_ms = features = hits = faces_seen = 0
had_faces = False
report_at = ticks_ms()
while True:
now = ticks_ms()
if camera is None and reached(now, retry_at):
connect()
new_frame = False
if camera is not None and not (PAUSE_CAMERA_DURING_SEARCH and detector.busy):
try:
new_frame = camera.poll()
except (RuntimeError, OSError, ValueError, MemoryError) as error:
disconnect(error)
if new_frame:
cam_frames += 1
if not detector.busy:
detector.start(frame)
boxes_changed = False
if detector.busy and detector.work(DETECT_SLICE_MS):
faces = detector.faces
show_faces(faces, ticks_ms())
boxes_changed = bool(faces)
passes += 1
full_passes += 0 if detector.tracked else 1
pass_ms += detector.pass_ms
work_ms += detector.work_ms
features += detector.features
hits += detector.hits
faces_seen += len(faces)
if PRINT_FACES and (faces or had_faces):
print_faces(faces)
had_faces = bool(faces)
if verifier is not None and not detector.tracked:
again = [tuple(f) for f in verifier.detect(live_copy)]
same = (verifier.hits, verifier.features) == (detector.hits, detector.features)
if same:
verified += 1
else:
mismatched += 1
print(
"verify: live pass %d hits, %d features, %d faces; same frame again"
" %d hits, %d features, %d faces -> %s"
% (
detector.hits,
detector.features,
len(faces),
verifier.hits,
verifier.features,
len(again),
"same" if same else "DIFFERENT",
)
)
if hide_stale_boxes(ticks_ms()):
boxes_changed = True
if boxes_changed:
redraw_boxes()
if new_frame or boxes_changed:
t0 = ticks_ms()
render()
draw_ms += elapsed(ticks_ms(), t0)
draws += 1
# debug printing
if REPORT_SECONDS and elapsed(ticks_ms(), report_at) >= REPORT_SECONDS * 1000:
n = max(passes, 1)
line = (
f"camera {cam_frames / REPORT_SECONDS:.1f} fps,"
f" screen {draws / REPORT_SECONDS:.1f} fps ({draw_ms / max(draws, 1):.0f} ms each)"
f" | passes {passes} ({full_passes} full):"
f" {pass_ms // n} ms start to finish, {work_ms // n} ms working,"
f" {features // n} features, {hits / n:.1f} raw hits, {faces_seen / n:.1f} faces"
f" | frame brightness {detector.brightness}, contrast {detector.contrast}"
)
if verifier is not None:
line += f" | verify: {verified} same, {mismatched} different"
if camera is not None:
snap = camera.snapshot()
line += (
f" | dropped {snap['partial_frames_dropped']},"
f" decode errors {snap['decode_errors']},"
f" max decode {snap['max_decode_ns'] / 1e6:.0f} ms"
)
print(line)
cam_frames = draws = passes = full_passes = 0
draw_ms = work_ms = pass_ms = features = hits = faces_seen = 0
report_at = (report_at + REPORT_SECONDS * 1000) & _TICKS_MASK
Some debugging print statements are also sent to the serial console. These include FPS for the camera and information if a face is detected. This can help you add more lighting or adjust your camera position if you find that the project is not detecting a face when you think it should.
Page last edited October 15, 2026