Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(chroma): remove faint spill with consistent reference thresholds
Soohong Kim3aa8a608092b
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 6d2dc70..b96a48c 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -140,16 +140,17 @@ The still the clip was made from settles it. `video-frames --spill` takes:| Mode | What is corrected ||---|---|| `small` (default) | only small key-tinted clusters — the still pipeline's rule, byte-identical output |-| `full` | every key-tinted cluster, whatever its size (colour only: alpha is unchanged) |-| `auto` | keys `--reference` (the still) with the same matte and counts its strongly key-tinted pixels; a share ≤ 0.5 % means the still has no key-coloured material of its own → `full`, otherwise `small` |+| `full` | key-tinted clusters of any size, including faint tints (colour only: alpha is unchanged) |+| `auto` | keys `--reference` (the still) with the same matte and counts its key-tinted pixels at the same threshold used by `full`; a share ≤ 0.5 % means the still has no key-coloured material of its own → `full`, otherwise `small` |`video-set` passes `--spill auto` with each item's `canvas.png` as the reference (overridewith `--spill small|full`), so a green-free character loses the reflections while acharacter that *is* green keeps its colour. The decision and its numbers are recorded inthe frames report under `spill`. The correction is the engine's own `despill_color` blendmodel (observed = (1−k)·subject + k·key, solved for the subject), so colours without key-tint are untouched. Faint tints whose cluster never crosses the strong-tint bar are left-as they are.+tint are untouched. `small` keeps the conservative tint threshold of 40; `full` lowers it to 8.+The `auto` reference check also uses 8, so faint key-coloured material in the+original character keeps the conservative correction.## 3b. Canvas shape for raised limbs and wide costumesdiff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.pyindex 452a372..978147a 100644--- a/sprite_gen/frames/cutout.py+++ b/sprite_gen/frames/cutout.py@@ -271,7 +271,8 @@ def _matte_route(}-def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float | None = None) -> tuple[Image.Image, dict[str, Any]]:+def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float | None = None,+ spill_min_tint: float | 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@@ -285,7 +286,11 @@ def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float |target = KEY_TARGETS[kind]painted = detect_background_key_rgb(image, target)- extra = {} if spill_max_fraction is None else {"spill_max_fraction": spill_max_fraction}+ extra: dict[str, float] = {}+ if spill_max_fraction is not None:+ extra["spill_max_fraction"] = spill_max_fraction+ if spill_min_tint is not None:+ extra["spill_min_tint"] = spill_min_tintresult = remove_chroma_background(image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA, **extra)@@ -307,12 +312,14 @@ def cutout(tolerance: int = CHROMA_TOLERANCE,white_check_dir: Path | None = None,spill_max_fraction: float | None = None,+ spill_min_tint: float | None = None,) -> dict[str, Any]:"""Cut a uniform-background imported image to a clean transparent RGBA PNG.`key`: "auto" (detect from corners) | "white" (matte) | "magenta" | "green"(reuse the extract chroma engine). `spill_max_fraction` overrides the chroma- engine's trapped-spill cluster cap (None = the engine default). Returns a stats dict. Raises SystemExit if+ engine's trapped-spill cluster cap and `spill_min_tint` its tint bar (None = the+ engine default for either). Returns a stats dict. Raises SystemExit ifthe key is unknown, the background cannot be located, or any transparent pixelkeeps non-zero RGB (No Silent Fallback)."""@@ -324,7 +331,8 @@ def cutout(route = _detect_key_kind(_corner_average(image)) if key == "auto" else keyif route in ("magenta", "green"):- result, route_stats = extract_route(image, route, spill_max_fraction=spill_max_fraction)+ result, route_stats = extract_route(image, route, spill_max_fraction=spill_max_fraction,+ spill_min_tint=spill_min_tint)else:result, route_stats = _matte_route(image, input_path, strength, band, erode, tolerance)diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex 15de7d0..ef1d324 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -362,19 +362,27 @@ _IN_BAND_UNMIX_KEY_DEPTH = 2# channel clears every unkeyed channel by >40): warm subject colors (skin)# score a marginal tint just above fringe_delta and must not be "corrected"._SPILL_MIN_TINT = 40.0+# Full correction also admits faint key tints. Auto mode must inspect the+# reference at this same threshold before choosing full correction.+_SPILL_FULL_MIN_TINT = 8.0-def key_material_pixels(image: Image.Image, chroma_key: tuple[int, int, int]) -> tuple[int, int]:- """Opaque pixels that are strongly key-tinted (the trapped-spill bar, `_SPILL_MIN_TINT`),- and all opaque pixels, of an already keyed RGBA image. A still that has almost none- carries no key-coloured material of its own."""+def key_material_pixels(image: Image.Image, chroma_key: tuple[int, int, int],+ min_tint: float = _SPILL_MIN_TINT) -> tuple[int, int]:+ """Opaque pixels that are key-tinted past `min_tint` (the trapped-spill bar), and all+ opaque pixels, of an already keyed RGBA image. A still that has almost none carries no+ key-coloured material of its own.++ The bar is a parameter because the decision and the treatment have to read the same+ one: judging a reference at 40 and then despilling it down to 8 would call a subject+ with a mild green of its own "no key material" and then scrub that green away."""keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)data = np.asarray(image.convert("RGBA")).astype(np.int32)opaque = data[..., 3] > 0if not keyed_channels:return 0, int(opaque.sum())tint = _key_tint_field(data[..., :3], keyed_channels, unkeyed_channels)- return int((opaque & (tint > _SPILL_MIN_TINT)).sum()), int(opaque.sum())+ return int((opaque & (tint > min_tint)).sum()), int(opaque.sum())def remove_chroma_background(@@ -386,6 +394,7 @@ def remove_chroma_background(*,unmix_reach: int = 4,spill_max_fraction: float = 0.005,+ spill_min_tint: float = _SPILL_MIN_TINT,background_key: tuple[int, int, int] | None = None,) -> Image.Image:"""Key `chroma_key` out of `image` (hard cut + soft-alpha fringe unmix + trapped-spill despill).@@ -520,8 +529,13 @@ def remove_chroma_background(# the image, and a pixel it despilled is no longer a spill candidate.current_tint = _key_tint_field(data[..., :3].astype(np.int32),keyed_channels, unkeyed_channels)+ # Candidacy and acceptance read the same bar: a cluster can never be accepted+ # below `spill_min_tint`, so admitting only pixels at or above `fringe_delta`+ # would silently keep the lowered bar from reaching anything when it is the+ # smaller of the two.+ candidate_tint = min(fringe_delta, spill_min_tint)candidates = np.flatnonzero(- ((data[..., 3] != 0) & (current_tint >= fringe_delta)).reshape(-1)+ ((data[..., 3] != 0) & (current_tint >= candidate_tint)).reshape(-1))tints_left: dict[int, float] = dict(zip(candidates.tolist(), current_tint.reshape(-1)[candidates].tolist())@@ -547,7 +561,7 @@ def remove_chroma_background(stack.append(neighbor)if len(cluster) > spill_limit:continue- if max(tints_left[index] for index in cluster) <= _SPILL_MIN_TINT:+ if max(tints_left[index] for index in cluster) <= spill_min_tint:continuefor index in cluster:x = index % widthdiff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex 5d266f0..4c13174 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -33,6 +33,7 @@ from PIL import Imagefrom sprite_gen.frames.cutout import cutoutfrom sprite_gen.frames.extract import is_border_key_candidate+from sprite_gen.frames.extract import _SPILL_FULL_MIN_TINTfrom sprite_gen.spec.runio import atomic_write_textEDGE_ROWS = 4 # rows/cols inspected at each edge@@ -44,6 +45,7 @@ EDGE_ROWS = 4 # rows/cols inspected at each edge# key tint in the clip was painted by the model and is spill.SPILL_MODES = ("auto", "small", "full")SPILL_FULL_FRACTION = 1.0 # every tinted cluster is spill, whatever its size+SPILL_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 → fullEDGE_MAX_PIXELS = 0 # any opaque pixel on the top/left/right edge band = contact@@ -135,7 +137,9 @@ def decide_spill(reference: Path, key: str) -> dict[str, Any]: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)- material, subject = key_material_pixels(keyed, KEY_TARGETS[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)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,@@ -152,13 +156,15 @@ def key_frames() -> dict[str, Any]:if spill not in ("small", "full"):raise SystemExit(f"video-frames: key_frames takes a resolved spill mode (small|full), got {spill!r}")+ # Full correction lowers the tint threshold as well as lifting the size cap.spill_max = SPILL_FULL_FRACTION if spill == "full" else None+ spill_tint = SPILL_FULL_MIN_TINT if spill == "full" else Nonekeyed_dir.mkdir(parents=True, exist_ok=True)rows: list[dict[str, Any]] = []contacts: list[dict[str, Any]] = []for src in raw_files:dst = keyed_dir / src.name- stats = cutout(src, dst, key=key, spill_max_fraction=spill_max)+ stats = cutout(src, dst, key=key, spill_max_fraction=spill_max, spill_min_tint=spill_tint)image = Image.open(dst).convert("RGBA")hist = image.getchannel("A").histogram()w, h = image.sizediff --git a/tests/frames/test_despill_full_tint_bar.py b/tests/frames/test_despill_full_tint_bar.pynew file mode 100644index 0000000..76a71ef--- /dev/null+++ b/tests/frames/test_despill_full_tint_bar.py@@ -0,0 +1,82 @@+"""Full spill correction removes faint tint and preserves reference material."""++from __future__ import annotations++from pathlib import Path++from PIL import Image++from sprite_gen._deps import np+from sprite_gen.frames.cutout import KEY_TARGETS, extract_route+from sprite_gen.frames.extract import _SPILL_FULL_MIN_TINT, _SPILL_MIN_TINT, key_material_pixels+from sprite_gen.video import frames as frames_mod+++def _green_canvas_with_tinted_subject(path: Path, *, tint: int, share: float = 1.0) -> Path:+ """A pale subject on a green field. `share` of the subject's area carries `tint`+ added to its green channel — the key light bouncing off it, which is what a video+ model can paint onto a neutral subject.+ """+ key = KEY_TARGETS["green"]+ size, box = 160, (32, 32, 128, 128) # a 96x96 subject: 9,216 px, so 1 px is 0.01 %+ im = Image.new("RGB", (size, size), key)+ left, top, right, bottom = box+ area = (right - left) * (bottom - top)+ lit = max(1, round(area * share))+ painted = 0+ for y in range(top, bottom):+ for x in range(left, right):+ on = painted < lit+ im.putpixel((x, y), (230, min(255, 225 + (tint if on else 0)), 225))+ painted += on+ im.save(path)+ return path+++def _residual_tint(image: Image.Image) -> np.ndarray:+ data = np.asarray(image.convert("RGBA")).astype(np.int32)+ opaque = data[..., 3] > 0+ tint = data[..., 1] - (data[..., 0] + data[..., 2]) / 2.0+ return tint[opaque]+++def test_the_full_bar_reaches_a_tint_the_default_bar_leaves_alone(tmp_path: Path) -> None:+ src = _green_canvas_with_tinted_subject(tmp_path / "in.png", tint=20) # between the bars+ image = Image.open(src).convert("RGBA")++ default_keyed, _ = extract_route(image, "green", spill_max_fraction=1.0)+ full_keyed, _ = extract_route(image, "green", spill_max_fraction=1.0,+ spill_min_tint=_SPILL_FULL_MIN_TINT)++ assert _SPILL_FULL_MIN_TINT < 20 < _SPILL_MIN_TINT+ assert _residual_tint(default_keyed).max() > 15, "the default bar is above this tint"+ assert _residual_tint(full_keyed).max() < 15, "the full bar has to reach it"+++def test_lifting_only_the_size_cap_is_not_enough(tmp_path: Path) -> None:+ """The bug as it stood: `full` moved `spill_max_fraction` and nothing changed."""+ src = _green_canvas_with_tinted_subject(tmp_path / "in.png", tint=20)+ image = Image.open(src).convert("RGBA")+ small, _ = extract_route(image, "green")+ size_cap_only, _ = extract_route(image, "green", spill_max_fraction=1.0)+ assert _residual_tint(small).max() == _residual_tint(size_cap_only).max()+++def test_a_subject_that_owns_key_material_is_still_judged_small(tmp_path: Path) -> None:+ """The decision reads the bar the treatment will use, so a genuinely green subject+ keeps its green: it is `small`, and `full`'s lowered bar never touches it."""+ # a subject that is green material: most of it carries the key hue+ owns_green = _green_canvas_with_tinted_subject(tmp_path / "green-subject.png", tint=90)+ # a clean subject carrying only what the key bounced onto its lower edge+ clean = _green_canvas_with_tinted_subject(tmp_path / "pale-subject.png", tint=20, share=0.003)+ assert frames_mod.decide_spill(owns_green, "green")["mode"] == "small"+ assert frames_mod.decide_spill(clean, "green")["mode"] == "full"+++def test_key_material_is_measured_at_the_bar_it_is_given(tmp_path: Path) -> None:+ src = _green_canvas_with_tinted_subject(tmp_path / "in.png", tint=20)+ keyed, _ = extract_route(Image.open(src).convert("RGBA"), "green")+ at_default, subject = key_material_pixels(keyed, KEY_TARGETS["green"])+ at_full, subject_again = key_material_pixels(keyed, KEY_TARGETS["green"], _SPILL_FULL_MIN_TINT)+ assert subject == subject_again+ assert at_default < at_full, "a lower bar must see at least as much key material"