Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): judge the spill reference on its subject window
Soohong Kima0f9fc5c134d
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 4df23fb..d2e244a 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -215,6 +215,18 @@ count even on an edge. The report names the metric, band and dark-only policy.Genuine key-coloured material above the 0.5% share still keeps the conservativemode. Tiny accents or dark, edge-only material can fall below that reference test; use `--spill small` when preserving those is essential.+The reference is keyed on its subject window only. A canvas padded for motion room+(`video-canvas`) is mostly key, and the matte's memory grows with every pixel it keys,+so keying the whole canvas made the judgment cost grow with the padding: about 0.14 GiB+per megapixel, past 4 GiB for a 30-megapixel canvas. The window is the box of pixels the+hard cut cannot erase (farther than 96 from the declared key, and not the painted key's+own colour), plus one keyed pixel all round. The painted key is read on the whole still,+and with that ring the window gives exactly the counts the whole still gives, so the+decision does not change. The still itself is only decoded and read a band of rows at+a time. A window over 6 megapixels is keyed on every n-th pixel each way instead, so no+reference costs more than that to judge. The report records `reference_size`,+`reference_window` and `reference_stride` (1 = every pixel of the window).+### Edges: `--decontam palette``--spill` fixes key colour painted *into* the subject. The strands and outlines at itsdiff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.pyindex c07da05..04c60bc 100644--- a/sprite_gen/frames/cutout.py+++ b/sprite_gen/frames/cutout.py@@ -94,15 +94,15 @@ def _corner_average(image: Image.Image) -> tuple[int, int, int]:"""Raw average of the non-transparent corner pixels — no brightness filter.Used for route detection so a saturated key colour (magenta/green, which the- bright-only `estimate_background` skips) is still seen.+ bright-only `estimate_background` skips) is still seen. Any mode: only the four+ corner pixels are converted to RGBA, so a large still is not converted whole."""width, height = image.size- px = image.load()- samples = [- px[x, y][:3]+ corners = [+ image.crop((x, y, x + 1, y + 1)).convert("RGBA").getpixel((0, 0))for x, y in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1))- if px[x, y][3] > 0]+ samples = [pixel[:3] for pixel in corners if pixel[3] > 0]if not samples:return (248, 247, 242)n = len(samples)@@ -274,13 +274,17 @@ def _matte_route(def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float | None = None,spill_min_tint: float | None = None,spill_require_hue: bool = False, decontam: str = "off", decontam_fit: str = "still",- decontam_palette: dict[str, Any] | None = None) -> tuple[Image.Image, dict[str, Any]]:+ decontam_palette: dict[str, Any] | None = None,+ background_key: tuple[int, int, int] | None = None) -> tuple[Image.Image, dict[str, Any]]:"""Magenta/green key background → reuse the verified `extract` chroma engine (no drift).The engine keys from the background colour it detects on the borders(`detect_background_key_rgb`) as well as the pure key, so the brightnessthe model happened to paint does not decide whether the cut lands. Thedetected colour is reported as `chroma_key_painted` for the audit trail.+ `background_key` hands in a colour detected elsewhere instead: a crop keyed as part+ of a larger image (`extract.subject_window`) takes the whole image's, whose borders+ it no longer has.Public because `video-canvas` normalizes a still's background through thisexact matte, so the canvas and `video-frames` agree by construction.`decontam` is the engine's edge decontamination pass (`extract.remove_chroma_background`);@@ -289,7 +293,10 @@ def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float |from sprite_gen.frames.extract import detect_background_key_rgb, remove_chroma_backgroundtarget = KEY_TARGETS[kind]- painted = detect_background_key_rgb(image, target)+ if background_key is None:+ painted = detect_background_key_rgb(image, target)+ else:+ painted = (int(background_key[0]), int(background_key[1]), int(background_key[2]))extra: dict[str, Any] = {}if spill_max_fraction is not None:extra["spill_max_fraction"] = spill_max_fraction@@ -301,8 +308,10 @@ def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float |if decontam != "off":extra.update(decontam=decontam, decontam_fit=decontam_fit, decontam_palette=decontam_palette,decontam_stats=decontam_stats)+ # the colour detected above, not a second detection of the same bordersresult = remove_chroma_background(- image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA, **extra+ image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA,+ background_key=painted, **extra)stats: dict[str, Any] = {"route": f"extract:{kind}",diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex e1ce1f9..0811305 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -313,9 +313,14 @@ def _border_key_candidate_field(rgb: np.ndarray, keyed_channels: list[int], unkereturn _key_family_field(rgb, keyed_channels, unkeyed_channels) | signature-def _key_detect_sample_mask(height: int, width: int) -> np.ndarray:- """Corner patches (w/5 x h/5) plus the 1-px border — where the background lives."""- mask = np.zeros((height, width), dtype=bool)+def _key_detect_sample_mask(height: int, width: int, top: int = 0, bottom: int | None = None) -> np.ndarray:+ """Corner patches (w/5 x h/5) plus the 1-px border — where the background lives.++ Rows `top` to `bottom` of the (height, width) mask, so an image can be sampled a band+ of rows at a time.+ """+ bottom = height if bottom is None else bottom+ mask = np.zeros((bottom - top, width), dtype=bool)if height == 0 or width == 0:return maskcorner_w = width // _KEY_DETECT_CORNER_DIV@@ -324,15 +329,24 @@ def _key_detect_sample_mask(height: int, width: int) -> np.ndarray:corner_w = widthif corner_h < 2:corner_h = height- mask[:corner_h, :corner_w] = True- mask[:corner_h, width - corner_w:] = True- mask[height - corner_h:, :corner_w] = True- mask[height - corner_h:, width - corner_w:] = True- mask[0, :] = mask[-1, :] = True+ rows = np.arange(top, bottom)+ corner_rows = (rows < corner_h) | (rows >= height - corner_h)+ mask[corner_rows, :corner_w] = True+ mask[corner_rows, width - corner_w:] = True+ mask[(rows == 0) | (rows == height - 1), :] = Truemask[:, 0] = mask[:, -1] = Truereturn mask+_KEY_DETECT_BAND_ROWS = 64 # rows sampled at a time: a large still is never one int32 array+++def _rgba_rows(image: Image.Image, top: int, bottom: int) -> np.ndarray:+ """Rows `top` to `bottom` of `image` as an RGBA uint8 array, converting only those rows."""+ rows = image.crop((0, top, image.width, bottom))+ return np.asarray(rows if rows.mode == "RGBA" else rows.convert("RGBA"))++def detect_background_key_rgb(image: Image.Image, chroma_key: tuple[int, int, int]) -> tuple[int, int, int]:@@ -350,29 +364,39 @@ def detect_background_key_rgb(such background, the subject crowds every border, a degenerate key — thedeclared key comes back unchanged, which keeps `remove_chroma_background`byte-identical to its pre-detection behaviour on exact-key backgrounds.++ The image is read a band of rows at a time (any mode, each band converted to RGBA+ on its own) into a count and a channel sum per bin, so the corners of a large+ still cost a histogram, not an array of samples."""keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)if not keyed_channels:return tuple(chroma_key) # type: ignore[return-value]- rgba = image if image.mode == "RGBA" else image.convert("RGBA")- data = np.array(rgba, dtype=np.uint8)- height, width = data.shape[:2]- sample = _key_detect_sample_mask(height, width) & (data[..., 3] != 0)- if not sample.any():- return tuple(chroma_key) # type: ignore[return-value]- rgb = data[..., :3].astype(np.int32)- family = sample & _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels)- family_count = int(np.count_nonzero(family))- if family_count < int(np.count_nonzero(sample)) * _KEY_DETECT_MIN_FRACTION:+ width, height = image.size+ bits = 8 - _KEY_DETECT_BIN_SHIFT+ # one slot per bin, ordered by (R, G, B) bin: the lowest slot is the lowest bin+ counts = np.zeros(1 << (3 * bits), dtype=np.int64)+ sums = np.zeros((3, 1 << (3 * bits)), dtype=np.float64) # integers far below 2**53: exact+ sampled = family_count = 0+ for top in range(0, height, _KEY_DETECT_BAND_ROWS):+ bottom = min(height, top + _KEY_DETECT_BAND_ROWS)+ band = _rgba_rows(image, top, bottom)+ sample = _key_detect_sample_mask(height, width, top, bottom) & (band[..., 3] != 0)+ rgb = band[sample][:, :3].astype(np.int32)+ family = _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels)+ sampled += len(rgb)+ family_count += int(np.count_nonzero(family))+ colors = rgb[family]+ bins = colors >> _KEY_DETECT_BIN_SHIFT+ slots = (bins[:, 0] << (2 * bits)) | (bins[:, 1] << bits) | bins[:, 2]+ counts += np.bincount(slots, minlength=len(counts))+ for channel in range(3):+ sums[channel] += np.bincount(slots, weights=colors[:, channel], minlength=len(counts))+ if not sampled or family_count < sampled * _KEY_DETECT_MIN_FRACTION:return tuple(chroma_key) # type: ignore[return-value]- colors = rgb[family] # (N, 3)- bins = (colors >> _KEY_DETECT_BIN_SHIFT).astype(np.int64)- slots = (bins[:, 0] << 16) | (bins[:, 1] << 8) | bins[:, 2]- unique, inverse, counts = np.unique(slots, return_inverse=True, return_counts=True)mode = int(np.argmax(counts)) # first max = lowest slot on a tie: deterministic- members = colors[inverse == mode]- mean = members.sum(axis=0, dtype=np.int64) // len(members)- return (int(mean[0]), int(mean[1]), int(mean[2]))+ members = int(counts[mode])+ return tuple(int(sums[channel][mode]) // members for channel in range(3)) # type: ignore[return-value]# remove_chroma_background pixel classes, decided once on the source colors.@@ -425,6 +449,53 @@ def hard_key_mask(source_rgb: np.ndarray, alpha: np.ndarray, chroma_key: tuple[ireturn (alpha == 0) | (key_distance <= threshold), key_distance+_WINDOW_BAND_ROWS = 64 # rows `subject_window` widens to int32 at a time+++def subject_window(image: Image.Image, chroma_key: tuple[int, int, int], threshold: float, margin: int,+ painted_key: tuple[int, int, int] | None = None) -> tuple[int, int, int, int] | None:+ """The box outside which `remove_chroma_background` erases every pixel, grown by `margin`.++ `hard_key_mask` keys, whatever their alpha, every pixel within `threshold` of the+ declared key and, when the painted colour differs, every pixel within `threshold` of+ the painted colour that carries the key's border signature (`is_border_key_candidate`).+ Only the other pixels can stay opaque. Returns their bounding box grown by `margin`+ and clipped to the image, as (left, top, right, bottom), or None when there are none+ (the whole image keys out). Pass the painted colour the engine will use.++ Keying the crop instead of the image changes no pixel inside it, provided `margin` is+ at least 1 and the same painted colour, detected on the whole image, is passed as+ `background_key`. Every pixel of the margin is keyed and would seed the painted ball,+ so from any pixel inside, a keyed pixel beyond the crop is never nearer than the+ margin pixel on the way to it: the unmix depth, a fringe band counted on the result,+ and a painted-ball path all come out the same. Spill clusters and the subject count+ lie inside the box. A still that is mostly key, such as a canvas padded for motion+ room, is then keyed at the size of its subject.++ Scanned in bands of rows, each converted to RGBA on its own, so a large image is never+ converted or widened to int32 as a whole.+ """+ keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)+ ball = painted_key is not None and tuple(painted_key) != tuple(chroma_key) and bool(keyed_channels)+ width, height = image.size+ rows = np.zeros(height, dtype=bool)+ cols = np.zeros(width, dtype=bool)+ for top in range(0, height, _WINDOW_BAND_ROWS):+ rgb = _rgba_rows(image, top, min(height, top + _WINDOW_BAND_ROWS))[..., :3].astype(np.int32)+ erased = _key_distance_field(rgb, chroma_key) <= threshold+ if ball:+ erased |= ((_key_distance_field(rgb, painted_key) <= threshold)+ & _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels))+ rows[top:top + len(rgb)] = ~erased.all(axis=1)+ cols |= ~erased.all(axis=0)+ if not rows.any():+ return None+ ys = np.flatnonzero(rows)+ xs = np.flatnonzero(cols)+ return (max(0, int(xs[0]) - margin), max(0, int(ys[0]) - margin),+ min(width, int(xs[-1]) + 1 + margin), min(height, int(ys[-1]) + 1 + margin))++def key_material_pixels(image: Image.Image, chroma_key: tuple[int, int, int],min_tint: float = _SPILL_MIN_TINT, *, require_hue: bool = False,ignore_fringe: int = 0) -> tuple[int, int]:diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex 7e33b61..d3431f5 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -30,6 +30,7 @@ from __future__ import annotationsimport argparseimport json+import mathimport shutilimport subprocessfrom pathlib import Path@@ -37,6 +38,7 @@ from typing import Anyfrom PIL import Image+from sprite_gen._deps import npfrom sprite_gen.frames.cutout import cutoutfrom sprite_gen.frames.decontam import palette_from_statsfrom sprite_gen.frames.extract import is_border_key_candidate@@ -54,6 +56,14 @@ SPILL_MODES = ("auto", "small", "full")SPILL_FULL_FRACTION = 1.0 # every tinted cluster is spill, whatever its sizeSPILL_FULL_MIN_TINT = _SPILL_FULL_MIN_TINT # ... and whatever its strength (see extract.py)SPILL_REFERENCE_MAX = 0.005 # the still's own key material ≤ the engine's small-cluster share → full+# The reference is keyed on its subject window only (`extract.subject_window`). A canvas padded+# for motion room is mostly key, and the matte's memory grows with every pixel it keys, so keying+# the whole canvas made the judgment grow with the padding. One keyed ring around the window is+# enough for the window to give the whole still's counts (see `subject_window`). A window over the+# pixel budget is keyed on every n-th pixel each way instead, reported as `reference_stride`, so+# no still costs more than the budget to judge.+SPILL_REFERENCE_MARGIN = 1+SPILL_REFERENCE_MAX_PIXELS = 6_000_000EDGE_MAX_PIXELS = 0 # any opaque pixel on the top/left/right edge band = contact# Edge decontamination (`sprite_gen.frames.decontam`). A decoded frame's chroma is blurred by# 4:2:0 while its luma is not, so frames use the video fit. One palette serves the whole clip,@@ -139,27 +149,61 @@ def classify_edge_contact(raw: Image.Image, keyed: Image.Image, chroma_key: tuplreturn {"subject": subject, "residual": residual}+def _reference_window(reference: Path, key: str) -> tuple[str, Image.Image | None, tuple[int, int, int] | None, dict[str, Any]]:+ """What `decide_spill` keys: (key kind, subject window or None, painted key, report fields).++ The painted key is read on the whole still, whose borders the window no longer has. The+ still is kept in the mode it was decoded in and read a band of rows at a time; only the+ window is converted to RGBA, and the full-size image is released before it is keyed.+ """+ from sprite_gen.frames.cutout import KEY_TARGETS, _EXTRACT_KEY_THRESHOLD, _corner_average, _detect_key_kind+ from sprite_gen.frames.extract import detect_background_key_rgb, subject_window++ image = Image.open(reference)+ image.load()+ kind = _detect_key_kind(_corner_average(image)) if key == "auto" else key+ if kind not in ("green", "magenta"):+ return kind, None, None, {}+ target = KEY_TARGETS[kind]+ painted = detect_background_key_rgb(image, target)+ box = subject_window(image, target, _EXTRACT_KEY_THRESHOLD, SPILL_REFERENCE_MARGIN, painted)+ facts: dict[str, Any] = {"reference_size": list(image.size), "reference_window": list(box) if box else None,+ "reference_stride": 1}+ if box is None: # every pixel is within the hard cut of the key: nothing of the still survives+ return kind, None, painted, facts+ window = image.crop(box).convert("RGBA")+ stride = math.ceil(math.sqrt(window.width * window.height / SPILL_REFERENCE_MAX_PIXELS))+ if stride > 1:+ window = Image.fromarray(np.ascontiguousarray(np.asarray(window)[::stride, ::stride]))+ facts["reference_stride"] = stride+ return kind, window, painted, facts++def decide_spill(reference: Path, key: str) -> dict[str, Any]:"""`auto`: key the reference still with the same matte and measure its own- key-coloured material. None worth the name → `full`; some → `small`."""- from sprite_gen.frames.cutout import KEY_TARGETS, _corner_average, _detect_key_kind, extract_route+ key-coloured material. None worth the name → `full`; some → `small`.++ Only the still's subject window is keyed (`reference_window`); a window over+ `SPILL_REFERENCE_MAX_PIXELS` is keyed on every `reference_stride`-th pixel each way."""+ from sprite_gen.frames.cutout import KEY_TARGETS, extract_routefrom sprite_gen.frames.extract import key_material_pixels- image = Image.open(reference).convert("RGBA")- kind = _detect_key_kind(_corner_average(image)) if key == "auto" else key+ kind, window, painted, facts = _reference_window(reference, key)if kind not in ("green", "magenta"):return {"mode": "small", "reference": str(reference), "reason": f"key {kind!r} has no spill pass"}- keyed, _ = extract_route(image, kind)- # judged at the bar `full` would treat with, so a subject that owns a mild key tint- # is not first called "no key material" and then scrubbed of it- material, subject = key_material_pixels(keyed, KEY_TARGETS[kind], SPILL_FULL_MIN_TINT,- require_hue=True, ignore_fringe=DEFAULT_UNMIX_REACH)+ material = subject = 0+ if window is not None:+ keyed, _ = extract_route(window, kind, background_key=painted)+ # judged at the bar `full` would treat with, so a subject that owns a mild key tint+ # is not first called "no key material" and then scrubbed of it+ material, subject = key_material_pixels(keyed, KEY_TARGETS[kind], SPILL_FULL_MIN_TINT,+ require_hue=True, ignore_fringe=DEFAULT_UNMIX_REACH)share = material / subject if subject else 0.0mode = "full" if share <= SPILL_REFERENCE_MAX else "small"return {"mode": mode, "reference": str(reference), "key": kind, "key_material_px": material,"subject_px": subject, "key_material_share": round(share, 5), "share_max": SPILL_REFERENCE_MAX,"material_metric": "key-channel-excess", "reference_fringe_ignored_px": DEFAULT_UNMIX_REACH,- "reference_fringe_policy": "dark-only"}+ "reference_fringe_policy": "dark-only", **facts}def key_frames(diff --git a/tests/frames/test_key_detect_banded.py b/tests/frames/test_key_detect_banded.pynew file mode 100644index 0000000..58d06d5--- /dev/null+++ b/tests/frames/test_key_detect_banded.py@@ -0,0 +1,111 @@+"""`detect_background_key_rgb` reads the image a band of rows at a time and must answer as the+whole-image form did. `_whole_image_detect` is that form, frozen: every sample widened to+int32 at once, then `np.unique` over the bins. The banded form keeps a count and a channel+sum per bin instead, so a large still costs a histogram rather than an array of samples.+"""+from __future__ import annotations++import numpy as np+import pytest+from PIL import Image++from sprite_gen.frames.cutout import _corner_average+from sprite_gen.frames.extract import (_KEY_DETECT_BAND_ROWS, _KEY_DETECT_BIN_SHIFT, _KEY_DETECT_CORNER_DIV,+ _KEY_DETECT_MIN_FRACTION, _border_key_candidate_field, _key_channel_split,+ detect_background_key_rgb)++GREEN = (0, 255, 0)+MAGENTA = (255, 0, 255)+++def _whole_image_mask(height: int, width: int) -> np.ndarray:+ mask = np.zeros((height, width), dtype=bool)+ if height == 0 or width == 0:+ return mask+ corner_w = width // _KEY_DETECT_CORNER_DIV+ corner_h = height // _KEY_DETECT_CORNER_DIV+ if corner_w < 2:+ corner_w = width+ if corner_h < 2:+ corner_h = height+ mask[:corner_h, :corner_w] = True+ mask[:corner_h, width - corner_w:] = True+ mask[height - corner_h:, :corner_w] = True+ mask[height - corner_h:, width - corner_w:] = True+ mask[0, :] = mask[-1, :] = True+ mask[:, 0] = mask[:, -1] = True+ return mask+++def _whole_image_detect(image: Image.Image, chroma_key: tuple[int, int, int]) -> tuple[int, int, int]:+ keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)+ if not keyed_channels:+ return tuple(chroma_key)+ data = np.array(image.convert("RGBA"), dtype=np.uint8)+ height, width = data.shape[:2]+ sample = _whole_image_mask(height, width) & (data[..., 3] != 0)+ if not sample.any():+ return tuple(chroma_key)+ rgb = data[..., :3].astype(np.int32)+ family = sample & _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels)+ if int(np.count_nonzero(family)) < int(np.count_nonzero(sample)) * _KEY_DETECT_MIN_FRACTION:+ return tuple(chroma_key)+ colors = rgb[family]+ bins = (colors >> _KEY_DETECT_BIN_SHIFT).astype(np.int64)+ slots = (bins[:, 0] << 16) | (bins[:, 1] << 8) | bins[:, 2]+ _, inverse, counts = np.unique(slots, return_inverse=True, return_counts=True)+ members = colors[inverse == int(np.argmax(counts))]+ mean = members.sum(axis=0, dtype=np.int64) // len(members)+ return (int(mean[0]), int(mean[1]), int(mean[2]))+++def _noisy(size: tuple[int, int], colour: tuple[int, int, int], spread: int, seed: int) -> np.ndarray:+ rng = np.random.default_rng(seed)+ base = np.asarray(colour, dtype=np.int16) + rng.integers(-spread, spread + 1, size=(size[1], size[0], 3))+ return np.clip(base, 0, 255).astype(np.uint8)+++def _images() -> list[tuple[str, Image.Image]]:+ rng = np.random.default_rng(7)+ out: list[tuple[str, Image.Image]] = []+ for width, height in [(1, 1), (2, 3), (5, 4), (13, 9), (9, 131), (300, 7), (97, 301), (211, 5 * _KEY_DETECT_BAND_ROWS + 3)]:+ painted = _noisy((width, height), (8, 162, 24), 9, width * 1000 + height)+ subject = rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8)+ # a subject over the middle third: the corners and borders stay background+ mixed = painted.copy()+ mixed[height // 3: 2 * height // 3 + 1, width // 3: 2 * width // 3 + 1] = subject[height // 3: 2 * height // 3 + 1, width // 3: 2 * width // 3 + 1]+ out.append((f"painted {width}x{height}", Image.fromarray(mixed)))+ out.append((f"random {width}x{height}", Image.fromarray(subject)))+ alpha = (rng.random((height, width)) > 0.4).astype(np.uint8) * 255+ out.append((f"holes {width}x{height}", Image.fromarray(np.dstack([mixed, alpha]))))+ # two clusters of equal size on the border: the tie goes to the lowest bin+ tie = np.zeros((40, 40, 3), dtype=np.uint8)+ tie[:, :20] = (8, 162, 24)+ tie[:, 20:] = (8, 170, 24)+ out.append(("tie", Image.fromarray(tie)))+ # a tie between bins that order one way by red and the other by blue+ tie[:, :20] = (8, 162, 40)+ tie[:, 20:] = (16, 162, 24)+ out.append(("tie across channels", Image.fromarray(tie)))+ grok = _noisy((120, 90), (216, 46, 147), 6, 11)+ out.append(("grok magenta", Image.fromarray(grok)))+ out.append(("palette", Image.fromarray(_noisy((64, 80), (8, 162, 24), 12, 3)).convert("P")))+ return out++[email protected]("key", [GREEN, MAGENTA, (128, 128, 128)])+def test_banded_detection_answers_as_the_whole_image_form(key: tuple[int, int, int]) -> None:+ for name, image in _images():+ assert detect_background_key_rgb(image, key) == _whole_image_detect(image, key), name+++def test_the_detected_colour_is_the_painted_one() -> None:+ painted = Image.fromarray(_noisy((300, 2 * _KEY_DETECT_BAND_ROWS + 10), (8, 162, 24), 2, 5))+ assert detect_background_key_rgb(painted, GREEN) != GREEN+ r, g, b = detect_background_key_rgb(painted, GREEN)+ assert abs(r - 8) <= 3 and abs(g - 162) <= 3 and abs(b - 24) <= 3+++def test_corner_average_reads_any_mode_as_rgba() -> None:+ for _, image in _images():+ assert _corner_average(image) == _corner_average(image.convert("RGBA"))diff --git a/tests/video/test_spill_reference_window.py b/tests/video/test_spill_reference_window.pynew file mode 100644index 0000000..9d7a3c1--- /dev/null+++ b/tests/video/test_spill_reference_window.py@@ -0,0 +1,173 @@+"""`video-frames --spill auto` keys only the subject window of its reference still.++A canvas padded for motion room is mostly key, and keying all of it made the reference+judgment's memory grow with the padding. The judgment keys the box of pixels the hard+cut cannot erase, grown by a margin that covers the matte's reach, with the painted key+read on the whole still. It has to give the counts keying the whole still gives, which+`_whole_still_judgment` (the judgment as it was) checks on synthetic stills.+"""+from __future__ import annotations++from pathlib import Path++import numpy as np+import pytest+from PIL import Image, ImageDraw++from sprite_gen.frames import cutout as cutout_mod+from sprite_gen.frames.cutout import KEY_TARGETS, extract_route+from sprite_gen.frames.extract import DEFAULT_UNMIX_REACH, key_material_pixels, subject_window+from sprite_gen.video import frames as frames_mod++GREEN_PAINTED = (8, 162, 24) # a model's green, off the pure key+GROK_MAGENTA = (216, 46, 147)+# green material of the subject's own, far from both keys: a brighter leaf green would sit inside the+# painted colour's ball with the key's signature, and the matte erases that as background+MOSS = (80, 115, 90)+++def _whole_still_judgment(path: Path, kind: str) -> tuple[int, int]:+ """(key material, subject) with the whole still through the matte: the judgment before the window."""+ keyed, _ = extract_route(Image.open(path).convert("RGBA"), kind)+ return key_material_pixels(keyed, KEY_TARGETS[kind], frames_mod.SPILL_FULL_MIN_TINT,+ require_hue=True, ignore_fringe=DEFAULT_UNMIX_REACH)+++def _figure(width: int, height: int, background: tuple[int, int, int], *, patch: tuple[int, int, int] | None,+ spill: tuple[int, int, int] | None = None) -> Image.Image:+ """A figure drawn at 4x and box-reduced, so its outline, strands and patches meet the key as blends."""+ big = Image.new("RGB", (width * 4, height * 4), background)+ draw = ImageDraw.Draw(big)+ draw.ellipse((40, 60, width * 4 - 40, height * 4 - 20), fill=(200, 205, 212), outline=(20, 30, 22), width=10)+ for index in range(9): # red strands, 1-3 px wide after the reduction+ x = 60 + index * (width * 4 - 120) // 9+ draw.line((x, 8, x + 30, height * 2), fill=(170, 30, 40), width=4 + (index % 3) * 4)+ if patch is not None:+ draw.rectangle((width, height, width * 3, height * 2), fill=patch)+ if spill is not None: # a small key-tinted cluster inside the subject+ draw.rectangle((width * 2, height * 3, width * 2 + 16, height * 3 + 16), fill=spill)+ return big.reduce(4)+++def _canvas(path: Path, size: tuple[int, int], background: tuple[int, int, int], figures: list[tuple[int, int, Image.Image]],+ *, seed: int = 0) -> Path:+ """Figures pasted on a flat painted key, then +-5 noise on every channel of every pixel."""+ canvas = Image.new("RGB", size, background)+ for left, top, figure in figures:+ canvas.paste(figure, (left, top))+ noise = np.random.default_rng(seed).integers(-5, 6, size=(size[1], size[0], 3))+ Image.fromarray(np.clip(np.asarray(canvas).astype(np.int16) + noise, 0, 255).astype(np.uint8)).save(path)+ return path+++def _scenes(tmp_path: Path) -> dict[str, tuple[Path, str]]:+ clean = _figure(120, 150, GREEN_PAINTED, patch=None, spill=(60, 235, 70))+ leafy = _figure(120, 150, GREEN_PAINTED, patch=MOSS)+ teal = _figure(120, 150, GROK_MAGENTA, patch=(40, 150, 150), spill=(230, 60, 215))+ # a subject that fills its own box, large enough that the ring of background around it is+ # under the detector's 12 % of the window's samples: only the painted colour read on the+ # whole still keys that ring+ block = Image.new("RGB", (240, 260), (190, 195, 205))+ ImageDraw.Draw(block).rectangle((50, 60, 170, 200), fill=MOSS)+ scenes = {+ "padded": (_canvas(tmp_path / "padded.png", (620, 460), GREEN_PAINTED, [(300, 170, clean)]), "green"),+ "touches the bottom edge": (_canvas(tmp_path / "edge.png", (400, 300), GREEN_PAINTED, [(40, 150, clean)], seed=1), "green"),+ "two subjects": (_canvas(tmp_path / "two.png", (700, 400), GREEN_PAINTED, [(10, 10, clean), (560, 240, leafy)], seed=2), "green"),+ "own green material": (_canvas(tmp_path / "leafy.png", (500, 420), GREEN_PAINTED, [(200, 130, leafy)], seed=3), "green"),+ "grok magenta": (_canvas(tmp_path / "magenta.png", (520, 400), GROK_MAGENTA, [(150, 90, teal)], seed=4), "magenta"),+ "fills its box": (_canvas(tmp_path / "block.png", (600, 500), GREEN_PAINTED, [(180, 120, block)], seed=5), "green"),+ }+ # transparent pixels far from the key: keyed by their alpha, whatever their colour+ rgba = Image.open(scenes["padded"][0]).convert("RGBA")+ ImageDraw.Draw(rgba).rectangle((20, 20, 90, 60), fill=(200, 40, 40, 0))+ rgba.save(tmp_path / "transparent.png")+ scenes["transparent corner"] = (tmp_path / "transparent.png", "green")+ return scenes++[email protected]("scene", ["padded", "touches the bottom edge", "two subjects", "own green material",+ "grok magenta", "fills its box", "transparent corner"])+def test_the_window_gives_the_whole_stills_counts(tmp_path: Path, scene: str) -> None:+ path, kind = _scenes(tmp_path)[scene]+ material, subject = _whole_still_judgment(path, kind)+ decision = frames_mod.decide_spill(path, kind)+ assert (decision["key_material_px"], decision["subject_px"]) == (material, subject)+ assert decision["reference_stride"] == 1+ assert subject > 0+ share = material / subject+ assert decision["mode"] == ("full" if share <= frames_mod.SPILL_REFERENCE_MAX else "small")+ left, top, right, bottom = decision["reference_window"]+ width, height = decision["reference_size"]+ assert (right - left) * (bottom - top) < width * height # the padding was not keyed+++def test_the_scenes_cover_both_modes(tmp_path: Path) -> None:+ scenes = _scenes(tmp_path)+ assert frames_mod.decide_spill(*scenes["padded"])["mode"] == "full"+ assert frames_mod.decide_spill(*scenes["own green material"])["mode"] == "small"+++def test_the_matte_sees_the_window_not_the_canvas(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path, kind = _scenes(tmp_path)["padded"]+ keyed_sizes: list[tuple[int, int]] = []+ real = cutout_mod.extract_route++ def spy(image: Image.Image, route: str, **kwargs: object) -> tuple[Image.Image, dict]:+ keyed_sizes.append(image.size)+ return real(image, route, **kwargs)++ monkeypatch.setattr(cutout_mod, "extract_route", spy)+ decision = frames_mod.decide_spill(path, kind)+ left, top, right, bottom = decision["reference_window"]+ assert keyed_sizes == [(right - left, bottom - top)]+ assert keyed_sizes[0][0] * keyed_sizes[0][1] < 620 * 460 // 4+++def test_a_window_over_the_budget_is_keyed_on_a_stride(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ scenes = _scenes(tmp_path)+ budget = 6000+ monkeypatch.setattr(frames_mod, "SPILL_REFERENCE_MAX_PIXELS", budget)+ keyed_sizes: list[tuple[int, int]] = []+ real = cutout_mod.extract_route++ def spy(image: Image.Image, route: str, **kwargs: object) -> tuple[Image.Image, dict]:+ keyed_sizes.append(image.size)+ return real(image, route, **kwargs)++ monkeypatch.setattr(cutout_mod, "extract_route", spy)+ clean = frames_mod.decide_spill(*scenes["padded"])+ leafy = frames_mod.decide_spill(*scenes["own green material"])+ for decision, (width, height) in zip((clean, leafy), keyed_sizes):+ left, top, right, bottom = decision["reference_window"]+ stride = decision["reference_stride"]+ assert stride > 1+ assert (width, height) == (-(-(right - left) // stride), -(-(bottom - top) // stride))+ assert width * height <= budget * 1.5+ # a clear call stays the same call on the sparser grid+ assert clean["mode"] == "full" and leafy["mode"] == "small"+++def test_a_reference_that_is_all_key_keys_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path = _canvas(tmp_path / "empty.png", (300, 200), GREEN_PAINTED, [])+ monkeypatch.setattr(cutout_mod, "extract_route", lambda *a, **k: pytest.fail("nothing to key"))+ decision = frames_mod.decide_spill(path, "green")+ assert decision["reference_window"] is None+ assert (decision["key_material_px"], decision["subject_px"], decision["mode"]) == (0, 0, "full")+++def test_subject_window_bounds_what_the_hard_cut_cannot_erase() -> None:+ image = Image.new("RGBA", (50, 40), (0, 255, 0, 255))+ image.putpixel((10, 12), (0, 250, 5, 255)) # near the key: erased, outside the box+ image.putpixel((20, 15), (200, 30, 30, 255))+ image.putpixel((31, 22), (200, 30, 30, 0)) # far, transparent: the box ignores alpha+ assert subject_window(image, (0, 255, 0), 96.0, 3) == (17, 12, 35, 26)+ assert subject_window(image, (0, 255, 0), 96.0, 40) == (0, 0, 50, 40)+ assert subject_window(Image.new("RGB", (8, 8), (0, 255, 0)), (0, 255, 0), 96.0, 3) is None+++def test_subject_window_erases_the_painted_key_like_the_matte() -> None:+ # 96.38 from the pure key: only the painted colour's ball erases this background+ image = Image.new("RGB", (60, 30), GREEN_PAINTED)+ image.putpixel((40, 10), (200, 30, 30))+ assert subject_window(image, (0, 255, 0), 96.0, 2) == (0, 0, 60, 30)+ assert subject_window(image, (0, 255, 0), 96.0, 2, GREEN_PAINTED) == (38, 8, 43, 13)