Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(chroma): decontam auto; stills default to it

Soohong Kim7025aa273517
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5375ff0..7f5b41e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased (v2.7.0)
-- Add opt-in edge decontamination, `decontam: "palette"`. After the matte, each edge pixel is explained as a blend of the locally measured key background with one colour from a palette learned on the subject's own interior. The colour written is that palette colour at the pixel's observed luma, so thin hair strands and outlines come back in the subject's hue: not green, and not the orange that despill's channel gain produces. Available as `cutout --decontam palette`, `gen --transparent --decontam palette` (chroma keying), `video-frames` / `video-set --decontam palette` (video fit, one palette per clip) and request `chroma.decontam` for the row extractor and `inspect`. The default `off` returns every existing output byte for byte. On a procedural ground-truth set, key contamination at the edge falls from 22.5 % to 0.07 % on stills and from 33 % to 11 % on H.264 frames; halo against the true composite shrinks on dark and white backgrounds, and strand recall rises from 84 % to 99 % (stills) and from 82 % to 91 % (frames). Method, guards and limits: [docs/chroma-alpha.md](docs/chroma-alpha.md).
+- Add opt-in edge decontamination, `decontam: "palette"`. After the matte, each edge pixel is explained as a blend of the locally measured key background with one colour from a palette learned on the subject's own interior. The colour written is that palette colour at the pixel's observed luma, so thin hair strands and outlines come back in the subject's hue: not green, and not the orange that despill's channel gain produces. `cutout` and `gen --transparent` (chroma keying) now run it by default (`--decontam auto`: wherever it applies, with the reason recorded where it does not); `--decontam off` returns their previous output byte for byte, and `--decontam palette` demands the pass and fails where it cannot run. `video-frames` / `video-set` (video fit, one palette per clip) and the row extractor (request `chroma.decontam`, also read by `inspect`) keep `off` as their default. On a procedural ground-truth set, key contamination at the edge falls from 22.5 % to 0.07 % on stills and from 33 % to 11 % on H.264 frames; halo against the true composite shrinks on dark and white backgrounds, and strand recall rises from 84 % to 99 % (stills) and from 82 % to 91 % (frames). Method, guards and limits: [docs/chroma-alpha.md](docs/chroma-alpha.md).
## v2.6.0 - Automatic local gait selection and XY motion correction
diff --git a/docs/chroma-alpha.md b/docs/chroma-alpha.md
index fba7ae0..cb64bc9 100644
--- a/docs/chroma-alpha.md
+++ b/docs/chroma-alpha.md
@@ -60,7 +60,7 @@ When unsure, let `--chroma-key auto` sample the base. It excludes the detected f
2. **Soft-alpha unmix** — key-tinted blends near the keyed region are separated into despilled RGB + **partial alpha**: the blend model `observed = (1-k)·subject + k·key` is solved from the key-tint score, so antialiased silhouettes keep their coverage ramp instead of collapsing into a binary staircase. In-band blends (inside `--fringe-key-threshold`) are eligible only at key-distance `<= 2`; out-of-band blends use `--fringe-unmix-reach` (default 4). This preserves deeper key-tinted material while fixing trapped blend pockets between hair strands.
3. **Trapped-spill despill** — a small connected cluster of key-tinted pixels (≤ `--spill-max-fraction` of the subject, default 0.005) containing at least one strongly tinted pixel is generator spill, wherever it sits: its color is corrected in place with alpha kept (no pinholes). Large key-tinted regions are intentional material and are never touched; marginally warm subject colors (skin) never qualify.
-An opt-in fourth pass, edge decontamination (`chroma.decontam: "palette"`, below), then re-explains the edge with the subject's own colours.
+A fourth pass, edge decontamination (`decontam`, below; opt-in for sprite rows through `chroma.decontam`), then re-explains the edge with the subject's own colours.
The unmix/spill tunables live in the run's `sprite-request.json` under `chroma` (`unmix_reach`, `spill_max_fraction`) — the extractor reads them from there, CLI flags override, and the effective values are written back to the request so every run records what produced it. Then it extracts connected components and writes fresh transparent cells. The pixel-unfake path is unaffected: it binarizes alpha downstream (α ≥ 128 → opaque), so soft-alpha input degrades gracefully. This is intentionally closer to hatch-pet than to simple `magick -transparent`.
@@ -78,7 +78,7 @@ Port of perfectpixel-studio's `chroma.go` (MIT, see NOTICE). The default RGB pat
Select with request `chroma.mode: "ycbcr"` or `--chroma-mode ycbcr`. **The default stays `"rgb"`**: on clean flat-key raws the RGB path's exact-solve unmix already removes key tint completely, while ycbcr's fixed-scale despill leaves a small tinted soft-edge halo — ycbcr is for degraded sources (shaded/gradient backgrounds, JPEG chroma noise), not a general upgrade.
-## `decontam: "palette"` — give the edge the subject's own colour back (opt-in)
+## `decontam` — give the edge the subject's own colour back
The unmix above separates a blend by its key-tint score, and that assumes the subject's own colour carries no tint (grey, white). A saturated subject breaks the assumption. A crimson hair strand blended a third of the way into green scores as barely tinted, so it stays opaque and olive; where the full spill pass does reach it, the `1/(1-k)` gain of `despill_color` turns it orange. Video adds a second loss: H.264 4:2:0 has already averaged the key into the chroma of every strand one or two pixels wide. Its luma survives at full resolution.
@@ -101,14 +101,16 @@ Interior pixels are never touched, `off` returns the engine's output byte for by
Two fits. `still` chooses P per pixel. `video` chooses P on a 3×3 mean of the observation, whose chroma is blurred anyway, and averages the projection alpha with a luma-only alpha where P and B differ in luma. `video-frames` uses the video fit and learns one palette per clip on the first frame, so the colours an edge may take cannot change from frame to frame.
-| Entry point | Flag |
-|---|---|
-| `sprite-gen cutout IMAGE` | `--decontam palette` (chroma routes; the white matte refuses it) |
-| `sprite-gen gen … --transparent` | `--decontam palette` (chroma strategy only; refused before the provider is called otherwise) |
-| `sprite-gen video-frames`, `video-set` | `--decontam palette` |
-| row extractor (`extract`, `inspect`) | request `chroma.decontam: "palette"`, or `--decontam palette` to override; written back to the request once in play |
+Three modes: `palette` runs the pass and fails loud where it cannot (no key hue, or no subject pixel deeper than 6 px to learn from); `auto` runs it wherever it applies and records why not elsewhere; `off` leaves the matte as it is.
+
+| Entry point | Default | Flag |
+|---|---|---|
+| `sprite-gen cutout IMAGE` | `auto` (chroma routes; the white matte records that it has no key colour) | `--decontam off\|auto\|palette` |
+| `sprite-gen gen … --transparent` | `auto` (chroma strategy; native alpha is left alone) | `--decontam off\|auto\|palette`; `palette` is refused before the provider is called when it cannot apply |
+| `sprite-gen video-frames`, `video-set` | `off` | `--decontam off\|auto\|palette` |
+| row extractor (`extract`, `inspect`) | `off` | request `chroma.decontam`, or `--decontam` to override; written back to the request once in play |
-Reports record what the pass did under `decontam`: mode, fit, the palette, and changed / refit / tint / recovered / unexplained pixel counts.
+Reports record what the pass did under `decontam`: mode, whether it applied (and why not), fit, the palette, and changed / refit / tint / recovered / unexplained pixel counts.
Measured on a procedural ground-truth set (red strands 0.5–3 px wide, outline and interior ink, highlights, translucent wisps, white cloth and a gold accent on a painted green key; a still, and an H.264 4:2:0 round trip at CRF 16). Key contamination counts edge pixels covered in both output and truth whose hue turned 12° or more toward the key (green residue and the despill's warm drift both turn that way), or, on near-grey truth, whose a*/b* moved toward the key by 8. Halo is the mean CIEDE2000 against the true composite on #0A0A0D and on white:
@@ -121,7 +123,7 @@ Measured on a procedural ground-truth set (red strands 0.5–3 px wide, outline
| H.264 frames | RGB engine + `--spill full` | 33.2 % | 12.79 / 12.43 | 82.1 % |
| H.264 frames | + `decontam` (video fit) | 10.8 % | 9.38 / 8.73 | 91.4 % |
-**The default stays `off`.** It returns the current output byte for byte, and every published run and golden fixture depends on those bytes.
+**Defaults.** Stills cut by `cutout` and `gen --transparent` default to `auto`: on stills the pass removes nearly all key contamination with a smaller halo and more strand coverage, and `off` gives the previous output back byte for byte. The row extractor stays `off`: its frames are a derived cache that `heal` re-derives from raw, so a changed default would silently rewrite every existing run, and pixel-art rows binarize alpha downstream anyway. `video-frames` / `video-set` stay `off` (see the video numbers above).
Limitations:
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 8782838..95a0bbd 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -182,7 +182,7 @@ each edge pixel as a blend of the local key background with one colour the subje
and writes that colour at the pixel's observed luma. It uses the video fit and one palette
per clip, learned on the first frame, so edge colours cannot flicker between palettes. The
default `off` keeps frames byte-identical. Method, guards and measurements:
-[chroma-alpha.md](chroma-alpha.md#decontam-palette--give-the-edge-the-subjects-own-colour-back-opt-in).
+[chroma-alpha.md](chroma-alpha.md#decontam--give-the-edge-the-subjects-own-colour-back).
## 3b. Canvas shape for raised limbs and wide costumes
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index 0dbe65f..9a4367b 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -91,7 +91,7 @@ def _add_extract(p: argparse.ArgumentParser) -> None:
p.add_argument("--fringe-delta", type=float, default=18.0)
p.add_argument("--fringe-unmix-reach", type=int, default=None)
p.add_argument("--spill-max-fraction", type=float, default=None)
- p.add_argument("--decontam", choices=("off", "palette"), default=None)
+ p.add_argument("--decontam", choices=("off", "auto", "palette"), default=None)
p.add_argument("--segmentation", choices=("components", "projection"), default=None)
p.add_argument("--allow-slot-fallback", action="store_true")
p.add_argument("--min-used-pixels", type=int, default=None)
@@ -194,7 +194,7 @@ def _add_inspect(p: argparse.ArgumentParser) -> None:
p.add_argument("--fringe-unmix-reach", type=int, default=None)
p.add_argument("--spill-max-fraction", type=float, default=None)
p.add_argument("--chroma-mode", choices=("rgb", "ycbcr"), default=None)
- p.add_argument("--decontam", choices=("off", "palette"), default=None)
+ p.add_argument("--decontam", choices=("off", "auto", "palette"), default=None)
p.add_argument("--no-write", action="store_true")
diff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.py
index 384e334..b9c9348 100644
--- a/sprite_gen/frames/cutout.py
+++ b/sprite_gen/frames/cutout.py
@@ -327,7 +327,7 @@ def cutout(
spill_max_fraction: float | None = None,
spill_min_tint: float | None = None,
spill_require_hue: bool = False,
- decontam: str = "off",
+ decontam: str = "auto",
decontam_fit: str = "still",
decontam_palette: dict[str, Any] | None = None,
) -> dict[str, Any]:
@@ -336,16 +336,17 @@ def cutout(
`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 and `spill_min_tint` its tint bar (None = the
- engine default for either). `decontam="palette"` adds the engine's edge
- decontamination pass; it needs a chroma key, so on the white matte it fails
- rather than doing nothing. Returns a stats dict. Raises SystemExit if
- the key is unknown, the background cannot be located, or any transparent pixel
- keeps non-zero RGB (No Silent Fallback).
+ engine default for either). `decontam` is the engine's edge decontamination
+ pass: "auto" (the default) runs it on chroma routes where it applies and records
+ why not elsewhere; "palette" demands it and fails where it cannot run (the white
+ matte has no key colour to remove); "off" keeps the matte as it is. Returns a
+ stats dict. Raises SystemExit if the key is unknown, the background cannot be
+ located, or any transparent pixel keeps non-zero RGB (No Silent Fallback).
"""
if key not in ("auto", "white", "magenta", "green"):
raise SystemExit(f"cutout: unknown key {key!r}; expected one of auto|white|magenta|green")
- if decontam not in ("off", "palette"):
- raise SystemExit(f"cutout: unknown decontam {decontam!r}; expected off|palette")
+ if decontam not in ("off", "auto", "palette"):
+ raise SystemExit(f"cutout: unknown decontam {decontam!r}; expected off|auto|palette")
image = Image.open(input_path).convert("RGBA")
width, height = image.size
@@ -357,10 +358,13 @@ def cutout(
decontam=decontam, decontam_fit=decontam_fit,
decontam_palette=decontam_palette)
else:
- if decontam != "off":
+ if decontam == "palette":
raise SystemExit(f"cutout: --decontam {decontam} needs a chroma key background (magenta/green); "
f"{input_path} routed to the white matte, which has no key colour to remove")
result, route_stats = _matte_route(image, input_path, strength, band, erode, tolerance)
+ if decontam == "auto":
+ route_stats["decontam"] = {"mode": "auto", "applied": False,
+ "reason": "the white matte has no key colour to remove"}
out_path.parent.mkdir(parents=True, exist_ok=True)
result.save(out_path)
@@ -436,10 +440,11 @@ def add_arguments(p: Any) -> None:
)
p.add_argument(
"--decontam",
- choices=["off", "palette"],
- default="off",
- help="chroma routes only: re-explain key-tinted edges with the subject's own colours "
- "(palette); off keeps the engine output byte-identical (default off)",
+ choices=["off", "auto", "palette"],
+ default="auto",
+ help="edge decontamination on chroma routes: re-explain key-tinted edges (hair strands, outlines) "
+ "with the subject's own colours. auto (default) runs it where it applies and records why not "
+ "elsewhere; palette demands it; off keeps the chroma engine's output as it was before",
)
@@ -457,7 +462,7 @@ def run(**kwargs: object) -> int:
erode=float(kwargs.get("erode", ERODE_DEFAULT)), # type: ignore[arg-type]
tolerance=int(kwargs.get("tolerance", CHROMA_TOLERANCE)), # type: ignore[arg-type]
white_check_dir=out_path.parent if white_check else None,
- decontam=str(kwargs.get("decontam") or "off"),
+ decontam=str(kwargs.get("decontam") or "auto"),
)
import json
diff --git a/sprite_gen/frames/decontam.py b/sprite_gen/frames/decontam.py
index d2a6abd..34a0b2c 100644
--- a/sprite_gen/frames/decontam.py
+++ b/sprite_gen/frames/decontam.py
@@ -67,7 +67,9 @@ from typing import Any
from sprite_gen._deps import np
from sprite_gen.frames.extract import _grow_chebyshev, _grow_into, _key_channel_split, _key_excess_field
-DECONTAM_MODES = ("off", "palette")
+# "palette" runs the pass and fails loud when it cannot; "auto" runs it wherever it applies (a
+# chroma key, a subject interior to learn from) and otherwise reports why it did not.
+DECONTAM_MODES = ("off", "auto", "palette")
DECONTAM_FITS = ("still", "video")
BAND_PX = 6 # subject pixels this close (Chebyshev) to the keyed background are re-examined
@@ -195,24 +197,34 @@ def _box3(rgb: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> np.ndarray:
return acc / 9.0
+def not_applicable(keyed: np.ndarray, keyed_mask: np.ndarray, chroma_key: tuple[int, int, int]) -> str | None:
+ """Why the pass cannot run on this image, or None when it can."""
+ keyed_channels, _ = _key_channel_split(chroma_key)
+ if not keyed_channels:
+ return (f"key {tuple(chroma_key)} has no key hue (needs saturated and dark channels); "
+ "edge decontamination only applies to chroma keys such as green or magenta")
+ interior = ~keyed_mask & (_ring_depth(keyed_mask, BAND_PX) > BAND_PX)
+ if not np.count_nonzero(interior & (keyed[..., 3] == 255)):
+ return (f"no subject pixel lies deeper than {BAND_PX} px inside the keyed silhouette, "
+ "so there is no interior to learn the subject's colours from")
+ return None
+
+
def subject_palette(keyed: np.ndarray, keyed_mask: np.ndarray, chroma_key: tuple[int, int, int]) -> dict[str, Any]:
"""The subject's colours, learned from its confident interior (opaque, deeper than `BAND_PX`).
Returns {"palette": (k, 3) float64, "keyfree": bool, "key_material_share": float}. A clip
can learn this once and hand it to every frame, so the colours an edge may take do not
- change from frame to frame.
+ change from frame to frame. Raises SystemExit when `not_applicable` says why it cannot.
"""
+ reason = not_applicable(keyed, keyed_mask, chroma_key)
+ if reason is not None:
+ raise SystemExit(f"decontam: {reason}; run without decontam")
keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)
- if not keyed_channels:
- raise SystemExit(f"decontam: key {tuple(chroma_key)} has no key hue (needs saturated and dark channels); "
- "edge decontamination only applies to chroma keys such as green or magenta")
subject = ~keyed_mask
interior = subject & (_ring_depth(keyed_mask, BAND_PX) > BAND_PX)
confident = interior & (keyed[..., 3] == 255)
confident_count = int(np.count_nonzero(confident))
- if confident_count == 0:
- raise SystemExit(f"decontam: no subject pixel lies deeper than {BAND_PX} px inside the keyed silhouette, "
- "so there is no interior to learn the subject's colours from; run without decontam")
excess = _key_excess_field(keyed[..., :3].astype(np.int32), keyed_channels, unkeyed_channels)
key_material = float(np.count_nonzero(confident & (excess > KEY_HUE_TINT))) / confident_count
keyfree = key_material <= KEY_MATERIAL_MAX_SHARE
@@ -233,19 +245,26 @@ def palette_from_stats(stats: dict[str, Any]) -> dict[str, Any]:
def decontaminate(source_rgb: np.ndarray, keyed: np.ndarray, keyed_mask: np.ndarray,
chroma_key: tuple[int, int, int], *, fit: str = "still", alpha_depth: int = 4,
- palette: dict[str, Any] | None = None) -> tuple[np.ndarray, dict[str, Any]]:
+ palette: dict[str, Any] | None = None, mode: str = "palette") -> tuple[np.ndarray, dict[str, Any]]:
"""Re-explain the edge of an already keyed image. Returns (RGBA uint8, stats).
`source_rgb` (H, W, 3) is the frame as generated, `keyed` (H, W, 4) the engine's
output for it and `keyed_mask` the engine's hard-cut background (transparent input
included). Interior pixels (deeper than `BAND_PX`) are returned byte-identical.
`palette` is a `subject_palette` result to reuse (a clip's); None learns this frame's.
+ `mode="auto"` returns the input unchanged, with the reason in the stats, where the
+ pass does not apply; `mode="palette"` raises SystemExit there instead.
"""
- validate("palette", fit)
+ validate(mode, fit)
+ if mode == "off":
+ raise SystemExit("decontam: decontaminate() called with mode 'off'")
+ if palette is None:
+ reason = not_applicable(keyed, keyed_mask, chroma_key)
+ if reason is not None:
+ if mode == "palette":
+ raise SystemExit(f"decontam: {reason}; run without decontam")
+ return np.array(keyed, dtype=np.uint8, copy=True), {"mode": mode, "applied": False, "reason": reason}
keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)
- if not keyed_channels:
- raise SystemExit(f"decontam: key {tuple(chroma_key)} has no key hue (needs saturated and dark channels); "
- "edge decontamination only applies to chroma keys such as green or magenta")
rgb = np.asarray(source_rgb, dtype=np.float64)[..., :3]
out = np.array(keyed, dtype=np.uint8, copy=True)
subject = ~keyed_mask
@@ -357,7 +376,8 @@ def decontaminate(source_rgb: np.ndarray, keyed: np.ndarray, keyed_mask: np.ndar
recovered = int(np.count_nonzero(flank & (out[..., 3] > 0)))
changed = int(np.count_nonzero((out != np.asarray(keyed, dtype=np.uint8)).any(axis=-1)))
stats = {
- "mode": "palette",
+ "mode": mode,
+ "applied": True,
"fit": fit,
"band_px": BAND_PX,
"alpha_depth": int(alpha_depth),
diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.py
index 4191e75..e1ce1f9 100644
--- a/sprite_gen/frames/extract.py
+++ b/sprite_gen/frames/extract.py
@@ -480,8 +480,8 @@ def remove_chroma_background(
byte-identity gate does that).
`decontam="palette"` re-explains the edge afterwards with the subject's own
- colours (`sprite_gen.frames.decontam`); "off" (the default) returns exactly
- what the passes above produce. `decontam_stats`, when given, receives what
+ colours (`sprite_gen.frames.decontam`; "auto" does so where it applies and reports
+ why not elsewhere); "off" (the default) returns exactly what the passes above produce. `decontam_stats`, when given, receives what
that pass did; `decontam_palette` reuses a palette learned elsewhere.
"""
if decontam != "off":
@@ -647,7 +647,7 @@ def remove_chroma_background(
data[y, x] = (*despilled, alpha)
if decontam != "off":
data, stats = decontam_module.decontaminate(source_rgb, data, keyed_mask, chroma_key, fit=decontam_fit,
- alpha_depth=unmix_reach, palette=decontam_palette)
+ alpha_depth=unmix_reach, palette=decontam_palette, mode=decontam)
if decontam_stats is not None:
decontam_stats.update(stats)
# Back into the converted copy rather than a fresh Image.fromarray, so the
@@ -1034,7 +1034,7 @@ def remove_chroma_background_ycbcr(
keyed_mask, _ = hard_key_mask(source_rgb, source[..., 3], chroma_key, painted, DEFAULT_KEY_THRESHOLD)
data, stats = decontam_module.decontaminate(source_rgb, np.array(out, dtype=np.uint8), keyed_mask, chroma_key,
fit=decontam_fit, alpha_depth=DEFAULT_UNMIX_REACH,
- palette=decontam_palette)
+ palette=decontam_palette, mode=decontam)
if decontam_stats is not None:
decontam_stats.update(stats)
out.frombytes(data.tobytes())
@@ -2580,10 +2580,11 @@ def _build_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
"--decontam",
- choices=("off", "palette"),
+ choices=("off", "auto", "palette"),
default=None,
help="edge decontamination after the matte; overrides request chroma.decontam "
- "(palette = re-explain key-tinted edges with the subject's own colours; default off)",
+ "(palette = re-explain key-tinted edges with the subject's own colours, auto = where it "
+ "applies; default off)",
)
parser.add_argument(
"--segmentation",
@@ -2960,8 +2961,8 @@ def _run_locked(args: argparse.Namespace, run_dir: Path):
if args.decontam is not None
else str(chroma_config.get("decontam", "off"))
)
- if decontam_mode not in ("off", "palette"):
- raise SystemExit("chroma.decontam must be 'off' or 'palette'")
+ if decontam_mode not in ("off", "auto", "palette"):
+ raise SystemExit("chroma.decontam must be 'off', 'auto' or 'palette'")
effective_chroma = {
**chroma_config,
"mode": chroma_mode,
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
index a3787b6..01aceab 100644
--- a/sprite_gen/gen/__init__.py
+++ b/sprite_gen/gen/__init__.py
@@ -257,12 +257,12 @@ def generate_image(
trim_alpha: bool = False,
keep_session: bool = False,
workdir: Path | None = None,
- decontam: str = "off",
+ decontam: str = "auto",
) -> GenResult:
"""Generate one image and return a GenResult. Raises SystemExit on any failure."""
- if decontam not in ("off", "palette"):
- raise SystemExit(f"gen: unknown --decontam {decontam!r}; expected off|palette")
- if decontam != "off" and not transparent:
+ if decontam not in ("off", "auto", "palette"):
+ raise SystemExit(f"gen: unknown --decontam {decontam!r}; expected off|auto|palette")
+ if decontam == "palette" and not transparent:
raise SystemExit("gen: --decontam applies to the chroma key of a --transparent image; add --transparent")
prompt = (prompt or "").strip()
if not prompt:
@@ -284,7 +284,7 @@ def generate_image(
strategy_source: str | None = None
if transparent:
strategy, strategy_source = resolve_transparency_strategy(backend, alpha_mode, refs=refs)
- if decontam != "off" and strategy != TRANSPARENCY_CHROMA:
+ if decontam == "palette" and strategy != TRANSPARENCY_CHROMA:
# before the provider is called: a paid generation must not end in this refusal
raise SystemExit(f"gen: --decontam removes a chroma key; this image would use {strategy} alpha "
"(pass --alpha-mode chroma to key it instead)")
@@ -419,7 +419,7 @@ def _run(args: argparse.Namespace) -> int:
trim_alpha=bool(getattr(args, "trim_alpha", False)),
keep_session=args.keep_session,
workdir=args.workdir,
- decontam=str(getattr(args, "decontam", None) or "off"),
+ decontam=str(getattr(args, "decontam", None) or "auto"),
)
payload = result.to_dict()
# `provider` in the payload is always the backend that actually generated the
@@ -524,10 +524,11 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
)
parser.add_argument(
"--decontam",
- choices=("off", "palette"),
- default="off",
- help="chroma keying only: re-explain key-tinted edges (hair strands, outlines) with the subject's "
- "own colours after the matte (palette); off keeps the matte as is (default off)",
+ choices=("off", "auto", "palette"),
+ default="auto",
+ help="chroma keying: re-explain key-tinted edges (hair strands, outlines) with the subject's own "
+ "colours after the matte. auto (default) runs it where it applies (chroma strategy, a subject "
+ "interior); palette demands it; off publishes the matte as it is",
)
parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")
parser.add_argument("--facing", choices=(*facing_mod.FACINGS, "preserve"), default="preserve", help="with --ref: required direction; preserve (default) leaves prompt and pixels unchanged")
diff --git a/sprite_gen/gen/chroma.py b/sprite_gen/gen/chroma.py
index 7c6a08a..5dd503f 100644
--- a/sprite_gen/gen/chroma.py
+++ b/sprite_gen/gen/chroma.py
@@ -42,13 +42,14 @@ def key_transparent(
*,
key: str = "magenta",
white_check: Path | None = None,
- decontam: str = "off",
+ decontam: str = "auto",
) -> dict[str, Any]:
"""Key a chroma-background PNG to a clean transparent RGBA PNG.
Returns a stats dict (keyed/fringe/cleaned pixel counts, alpha_zero_pct).
- `decontam="palette"` adds the edge decontamination pass after the matte and
- reports it under `decontam`. Raises SystemExit before publishing if no
+ `decontam` is the edge decontamination pass after the matte, reported under
+ `decontam`: "auto" (the default) runs it where it applies, "palette" demands it,
+ "off" publishes the matte as it is. Raises SystemExit before publishing if no
measurable transparent area was made, or if a transparent pixel keeps non-zero RGB.
"""
if key not in KEYS:
diff --git a/sprite_gen/qa/inspect.py b/sprite_gen/qa/inspect.py
index bc1359b..02ab828 100644
--- a/sprite_gen/qa/inspect.py
+++ b/sprite_gen/qa/inspect.py
@@ -40,7 +40,7 @@ def _build_parser() -> argparse.ArgumentParser:
parser.add_argument("--fringe-unmix-reach", type=int, default=None)
parser.add_argument("--spill-max-fraction", type=float, default=None)
parser.add_argument("--chroma-mode", choices=("rgb", "ycbcr"), default=None)
- parser.add_argument("--decontam", choices=("off", "palette"), default=None)
+ parser.add_argument("--decontam", choices=("off", "auto", "palette"), default=None)
parser.add_argument("--no-write", action="store_true")
return parser
diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.py
index 83c43d2..1213a57 100644
--- a/sprite_gen/video/frames.py
+++ b/sprite_gen/video/frames.py
@@ -52,7 +52,7 @@ EDGE_MAX_PIXELS = 0 # any opaque pixel on the top/left/right edge band = contac
# 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,
# learned on the first frame, so the colours an edge may take cannot change between frames.
-DECONTAM_MODES = ("off", "palette")
+DECONTAM_MODES = ("off", "auto", "palette")
DECONTAM_FIT = "video"
DECONTAM_STAT_KEYS = ("changed_px", "refit_px", "tint_px", "recovered_px", "unexplained_px", "key_hue_capped_px")
@@ -172,6 +172,7 @@ def key_frames(
clip_palette: dict[str, Any] | None = None
decontam_first: dict[str, Any] | None = None
decontam_totals = {name: 0 for name in DECONTAM_STAT_KEYS}
+ decontam_applied = 0
# 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 None
@@ -190,12 +191,16 @@ def key_frames(
row = {"frame": src.name, "alpha_zero_pct": alpha_zero_pct, "route": stats.get("route")}
if decontam != "off":
done = stats["decontam"]
- if clip_palette is None:
- clip_palette = palette_from_stats(done)
- decontam_first = done
- row["decontam"] = {name: done[name] for name in DECONTAM_STAT_KEYS}
- for name in DECONTAM_STAT_KEYS:
- decontam_totals[name] += int(done[name])
+ if done.get("applied"):
+ if clip_palette is None:
+ clip_palette = palette_from_stats(done)
+ decontam_first = done | {"frame": src.name}
+ row["decontam"] = {name: done[name] for name in DECONTAM_STAT_KEYS}
+ for name in DECONTAM_STAT_KEYS:
+ decontam_totals[name] += int(done[name])
+ decontam_applied += 1
+ else:
+ row["decontam"] = {"applied": False, "reason": done.get("reason")}
if check_edges:
contact = edge_contact(image)
if any(v > EDGE_MAX_PIXELS for v in contact.values()):
@@ -218,14 +223,15 @@ def key_frames(
report["decontam"] = {
"mode": decontam,
"fit": DECONTAM_FIT,
- "palette_source": f"clip (learned on {rows[0]['frame']})",
+ "palette_source": f"clip (learned on {decontam_first['frame']})",
"palette": decontam_first["palette"],
"palette_keyfree": decontam_first["palette_keyfree"],
"key_material_share": decontam_first["key_material_share"],
+ "applied_frames": decontam_applied,
"totals": decontam_totals,
}
else:
- report["decontam"] = {"mode": decontam}
+ report["decontam"] = {"mode": decontam, "applied_frames": 0}
if contacts and check_edges:
raise SystemExit(_edge_contact_message(contacts))
return report
@@ -287,7 +293,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--report", type=Path, help="report JSON (default <out-dir>/frames.report.json)")
parser.add_argument("--spill", choices=SPILL_MODES, default="small", help="small: correct only small key-tinted clusters (default); full: every key tint in the subject is spill; auto: decide from --reference")
parser.add_argument("--reference", type=Path, help="the still the clip was made from (required by --spill auto)")
- parser.add_argument("--decontam", choices=DECONTAM_MODES, default="off", help="off: the matte as is (default); palette: re-explain key-tinted edges with the subject's own colours (one palette per clip, video fit)")
+ parser.add_argument("--decontam", choices=DECONTAM_MODES, default="off", help="off: the matte as is (default); palette: re-explain key-tinted edges with the subject's own colours (one palette per clip, video fit); auto: the same where it applies, reasons recorded where not")
def run(**kwargs: object) -> int:
diff --git a/tests/frames/test_chroma_decontam.py b/tests/frames/test_chroma_decontam.py
index 1f0f1e0..37656e4 100644
--- a/tests/frames/test_chroma_decontam.py
+++ b/tests/frames/test_chroma_decontam.py
@@ -170,14 +170,40 @@ def test_off_is_the_engine_byte_for_byte():
assert stats == {}
-def test_cutout_default_is_unchanged(tmp_path: Path):
+def test_cutout_defaults_to_auto_and_off_is_the_engine(tmp_path: Path):
F, A = _render()
src = tmp_path / "raw.png"
- Image.fromarray(_composite_on(F, A, GREEN_PAINTED)).save(src)
- plain = cutout(src, tmp_path / "plain.png", key="green")
+ raw = _composite_on(F, A, GREEN_PAINTED)
+ Image.fromarray(raw).save(src)
+ default = cutout(src, tmp_path / "default.png", key="green")
off = cutout(src, tmp_path / "off.png", key="green", decontam="off")
- assert "decontam" not in plain and "decontam" not in off
- assert np.array_equal(np.array(Image.open(tmp_path / "plain.png")), np.array(Image.open(tmp_path / "off.png")))
+ palette = cutout(src, tmp_path / "palette.png", key="green", decontam="palette")
+ assert default["decontam"]["mode"] == "auto" and default["decontam"]["applied"] is True
+ assert "decontam" not in off
+ engine = np.array(remove_chroma_background(Image.fromarray(raw), (0, 255, 0), *KEY_ARGS))
+ assert np.array_equal(np.array(Image.open(tmp_path / "off.png")), engine)
+ assert np.array_equal(np.array(Image.open(tmp_path / "default.png")), np.array(Image.open(tmp_path / "palette.png")))
+ assert palette["decontam"]["mode"] == "palette"
+
+
+def test_auto_reports_why_it_did_not_run(tmp_path: Path):
+ # the white matte has no key colour to remove
+ img = Image.new("RGB", (64, 64), (250, 250, 248))
+ ImageDraw.Draw(img).ellipse([16, 16, 48, 48], fill=(200, 40, 40))
+ img.save(tmp_path / "white.png")
+ stats = cutout(tmp_path / "white.png", tmp_path / "white-out.png", key="auto")
+ assert stats["route"] == "matte" and stats["decontam"] == {
+ "mode": "auto", "applied": False, "reason": "the white matte has no key colour to remove"}
+ # a subject with no interior to learn from: auto keys it as before and says why
+ bar = np.full((80, 160, 3), GREEN_PAINTED, np.uint8)
+ bar[38:41, 20:140] = HAIR
+ Image.fromarray(bar).save(tmp_path / "bar.png")
+ auto = cutout(tmp_path / "bar.png", tmp_path / "bar-auto.png", key="green")
+ cutout(tmp_path / "bar.png", tmp_path / "bar-off.png", key="green", decontam="off")
+ assert auto["decontam"]["applied"] is False and "deeper than" in auto["decontam"]["reason"]
+ assert np.array_equal(np.array(Image.open(tmp_path / "bar-auto.png")), np.array(Image.open(tmp_path / "bar-off.png")))
+ with pytest.raises(SystemExit, match="no subject pixel lies deeper"):
+ cutout(tmp_path / "bar.png", tmp_path / "bar-palette.png", key="green", decontam="palette")
# --------------------------------------------------------------------------- what the pass is for
@@ -336,7 +362,8 @@ def test_video_frames_learn_one_palette_per_clip(tmp_path: Path):
assert all("decontam" in row for row in report["rows"])
assert done["totals"]["changed_px"] == sum(row["decontam"]["changed_px"] for row in report["rows"])
off = frames_mod.key_frames(raws, tmp_path / "plain", key="green", check_edges=False, spill="full")
- assert off["decontam"] == {"mode": "off"}
+ assert off["decontam"] == {"mode": "off", "applied_frames": 0}
+ assert done["applied_frames"] == len(raws)
assert all("decontam" not in row for row in off["rows"])
@@ -410,12 +437,13 @@ def test_gen_decontam_runs_after_the_ycbcr_matte_and_reports(tmp_path: Path, mon
from sprite_gen.gen import base as gen_base
provider = _FakeKeyProvider(gen_base.TRANSPARENCY_CHROMA)
- assert _gen(tmp_path, monkeypatch, provider, out=tmp_path / "off.png", report=tmp_path / "off.json") == 0
- assert _gen(tmp_path, monkeypatch, provider, decontam="palette") == 0
+ assert _gen(tmp_path, monkeypatch, provider, out=tmp_path / "off.png", report=tmp_path / "off.json",
+ decontam="off") == 0
+ assert _gen(tmp_path, monkeypatch, provider) == 0 # the default: auto
off = json.loads((tmp_path / "off.json").read_text())
on = json.loads((tmp_path / "girl.json").read_text())
assert "decontam" not in off["chroma"]
- assert on["chroma"]["decontam"]["mode"] == "palette" and on["chroma"]["decontam"]["changed_px"] > 0
+ assert on["chroma"]["decontam"]["mode"] == "auto" and on["chroma"]["decontam"]["changed_px"] > 0
raw = np.array(Image.open(tmp_path / "girl.png.raw.png").convert("RGB"))
_, interior = _edge(raw)
before, after = np.array(Image.open(tmp_path / "off.png")), np.array(Image.open(tmp_path / "girl.png"))
@@ -441,3 +469,26 @@ def test_gen_decontam_needs_a_transparent_image(tmp_path: Path, monkeypatch):
with pytest.raises(SystemExit, match="add --transparent"):
_gen(tmp_path, monkeypatch, provider, transparent=False, decontam="palette")
assert provider.calls == 0
+
+
+def test_gen_default_auto_leaves_native_alpha_and_opaque_images_alone(tmp_path: Path, monkeypatch):
+ from sprite_gen.gen import base as gen_base
+
+ class _Native(_FakeKeyProvider):
+ def generate(self, request, workdir):
+ self.calls += 1
+ image = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
+ for y in range(2, 6):
+ for x in range(2, 6):
+ image.putpixel((x, y), (200, 90, 20, 255))
+ image.save(request.raw)
+ return gen_base.ProviderRun(provider=self.name, elapsed_seconds=0.1, model=request.model)
+
+ native = _Native(gen_base.TRANSPARENCY_NATIVE)
+ assert _gen(tmp_path, monkeypatch, native, out=tmp_path / "native.png", report=tmp_path / "native.json") == 0
+ payload = json.loads((tmp_path / "native.json").read_text())
+ assert payload["alpha"]["strategy"] == "native" and payload["chroma"] is None
+ opaque = _FakeKeyProvider(gen_base.TRANSPARENCY_CHROMA)
+ assert _gen(tmp_path, monkeypatch, opaque, transparent=False, out=tmp_path / "opaque.png",
+ report=tmp_path / "opaque.json") == 0
+ assert opaque.calls == 1 and json.loads((tmp_path / "opaque.json").read_text())["chroma"] is None
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
index 666435d..9785fc2 100644
--- a/tests/gen/test_gen.py
+++ b/tests/gen/test_gen.py
@@ -430,7 +430,7 @@ def test_chroma_key_transparent_rejects_zero_percent_alpha(
src = tmp_path / "src.png"
Image.new("RGBA", (512, 512), (20, 30, 40, 255)).save(src)
- def ineffective_matte(image, chroma_key, warnings):
+ def ineffective_matte(image, chroma_key, warnings, **_decontam):
result = image.convert("RGBA")
result.putpixel((0, 0), (0, 0, 0, 0))
return result
@@ -769,7 +769,7 @@ def test_generate_image_zero_percent_alpha_fails_without_success_report(
monkeypatch.setattr(
chroma_mod,
"remove_chroma_background_ycbcr",
- lambda image, chroma_key, warnings: image.convert("RGBA"),
+ lambda image, chroma_key, warnings, **_decontam: image.convert("RGBA"),
)
out = tmp_path / "asset.png"