The link moves ~150 KB/s, so a full frame takes 2 s. After the first frame the runner diffs against what the screen shows and sends tight boxes; full frame on big changes, after a failed push, and every 15 minutes. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
36 lines
1.5 KiB
Python
36 lines
1.5 KiB
Python
"""Find what changed between two frames, so only that is sent over the slow serial link."""
|
|
from PIL import Image, ImageChops
|
|
|
|
TILE = 32
|
|
|
|
Box = tuple[int, int, int, int] # x0, y0, x1, y1 (x1, y1 exclusive)
|
|
|
|
|
|
def changed_regions(old: Image.Image, new: Image.Image, tile: int = TILE) -> list[Box]:
|
|
"""Tight boxes around the pixels that differ.
|
|
|
|
The frame is cut into tiles; consecutive changed tiles in one tile row become a single box, trimmed to the
|
|
pixels that actually changed. The screen's link costs time per byte only, so many small boxes are fine.
|
|
"""
|
|
if old.size != new.size:
|
|
raise ValueError(f"size mismatch: {old.size} vs {new.size}")
|
|
diff = ImageChops.difference(old.convert("RGB"), new.convert("RGB"))
|
|
if diff.getbbox() is None:
|
|
return []
|
|
width, height = diff.size
|
|
boxes: list[Box] = []
|
|
for ty in range(0, height, tile):
|
|
run: Box | None = None
|
|
for tx in range(0, width, tile):
|
|
inner = diff.crop((tx, ty, min(tx + tile, width), min(ty + tile, height))).getbbox()
|
|
if inner is not None:
|
|
box = (tx + inner[0], ty + inner[1], tx + inner[2], ty + inner[3])
|
|
run = box if run is None else (min(run[0], box[0]), min(run[1], box[1]),
|
|
max(run[2], box[2]), max(run[3], box[3]))
|
|
elif run is not None:
|
|
boxes.append(run)
|
|
run = None
|
|
if run is not None:
|
|
boxes.append(run)
|
|
return boxes
|