Geänderte Bildbereiche für Teil-Updates ermitteln

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main
AmiPoke 1 month ago
parent 187c3be89c
commit caf2ed0478
  1. 32
      src/ramscreen/diff.py
  2. 55
      tests/test_diff.py

@ -0,0 +1,32 @@
"""Ermittelt, welche Bildbereiche sich geändert haben (das Display ist langsam: ~2 s pro Vollbild)."""
from PIL import Image, ImageChops
BAND_HEIGHT = 16
Rect = tuple[int, int, int, int] # x, y, Breite, Höhe
def changed_rects(old: Image.Image | None, new: Image.Image) -> list[Rect]:
width, height = new.size
if old is None or old.size != new.size:
return [(0, 0, width, height)]
diff = ImageChops.difference(old.convert("RGB"), new.convert("RGB"))
boxes: list[list[int]] = [] # [x0, y0, x1, y1], x1/y1 exklusiv
current: list[int] | None = None
for top in range(0, height, BAND_HEIGHT):
bbox = diff.crop((0, top, width, min(top + BAND_HEIGHT, height))).getbbox()
if bbox is None:
if current is not None:
boxes.append(current)
current = None
continue
x0, y0, x1, y1 = bbox[0], top + bbox[1], bbox[2], top + bbox[3]
if current is None:
current = [x0, y0, x1, y1]
else:
current = [min(current[0], x0), current[1], max(current[2], x1), y1]
if current is not None:
boxes.append(current)
return [(x0, y0, x1 - x0, y1 - y0) for x0, y0, x1, y1 in boxes]

@ -0,0 +1,55 @@
from PIL import Image, ImageDraw
from ramscreen.diff import changed_rects
BG = (14, 16, 20)
def blank():
return Image.new("RGB", (320, 480), BG)
def test_ohne_vorbild_ganzes_bild():
assert changed_rects(None, blank()) == [(0, 0, 320, 480)]
def test_andere_groesse_ganzes_bild():
assert changed_rects(Image.new("RGB", (480, 320)), blank()) == [(0, 0, 320, 480)]
def test_identisch_keine_rechtecke():
assert changed_rects(blank(), blank()) == []
def test_zwei_getrennte_bereiche():
new = blank()
d = ImageDraw.Draw(new)
d.rectangle((10, 5, 19, 9), fill=(255, 0, 0)) # Band 0
d.rectangle((100, 200, 149, 209), fill=(255, 0, 0)) # Bänder 192–208 und 208–224
assert changed_rects(blank(), new) == [(10, 5, 10, 5), (100, 200, 50, 10)]
def test_ueber_bandgrenze_ein_rechteck():
new = blank()
ImageDraw.Draw(new).rectangle((0, 14, 4, 17), fill=(255, 255, 255))
assert changed_rects(blank(), new) == [(0, 14, 5, 4)]
def test_aufeinanderfolgende_baender_vereinigen_x_bereich():
new = blank()
d = ImageDraw.Draw(new)
d.rectangle((0, 10, 4, 15), fill=(255, 255, 255)) # Band 0
d.rectangle((50, 16, 59, 19), fill=(255, 255, 255)) # Band 1
assert changed_rects(blank(), new) == [(0, 10, 60, 10)]
def test_aenderung_nur_im_blaukanal_wird_erkannt():
new = blank()
new.putpixel((5, 7), (BG[0], BG[1], BG[2] + 1))
assert changed_rects(blank(), new) == [(5, 7, 1, 1)]
def test_letzte_zeile():
new = blank()
new.putpixel((319, 479), (255, 255, 255))
assert changed_rects(blank(), new) == [(319, 479, 1, 1)]
Loading…
Cancel
Save