Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(gen): --trim-alpha crops a transparent still to its opaque bbox
Soohong Kim49aff9a002b8
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 181cdf1..82e760c 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -176,6 +176,32 @@ def resolve_default_provider() -> tuple[str, dict[str, str] | None]:return default, None+def trim_to_alpha(path: Path, *, threshold: int = 8) -> dict[str, Any]:+ """Crop a transparent PNG in place to the bbox of its opaque pixels.++ A generated still carries an unpredictable band of empty alpha below the feet+ (and around the sides); two stills placed on the same floor line then stand at+ different heights. Trimming makes the image's bottom edge the ground-contact+ line, which is what every placement (scene, strip, runtime) anchors on. The+ subject is never cut — only fully transparent margin goes."""+ from PIL import Image++ with Image.open(path) as im:+ rgba = im.convert("RGBA")+ before = rgba.size+ box = rgba.getchannel("A").point(lambda v: 255 if v >= threshold else 0).getbbox()+ if box is None:+ raise SystemExit(f"gen: --trim-alpha: {path} is fully transparent; nothing to keep")+ cropped = rgba.crop(box)+ cropped.save(path)+ return {+ "bbox": list(box),+ "before": list(before),+ "after": list(cropped.size),+ "margin_px": {"left": box[0], "top": box[1], "right": before[0] - box[2], "bottom": before[1] - box[3]},+ }++def generate_image(provider: str,prompt: str,@@ -188,6 +214,7 @@ def generate_image(alpha_mode: str = ALPHA_MODE_AUTO,chroma_key: str = "magenta",white_check: Path | None = None,+ trim_alpha: bool = False,keep_session: bool = False,workdir: Path | None = None,) -> GenResult:@@ -253,6 +280,11 @@ def generate_image(else:shutil.copyfile(raw, out)verify_png(out)+ trim_stats: dict[str, Any] | None = None+ if trim_alpha:+ if not transparent:+ raise SystemExit("gen: --trim-alpha needs --transparent (there is no alpha to trim on an opaque image)")+ trim_stats = trim_to_alpha(out)# Preserve the pre-chroma raw next to the destination for auditability.raw_keep = out.with_suffix(out.suffix + ".raw.png")@@ -271,7 +303,7 @@ def generate_image(transparent=transparent,alpha=alpha_stats,chroma=chroma_stats,- extra=run.extra,+ extra={**run.extra, **({"trim_alpha": trim_stats} if trim_stats else {})},)finally:if owns_workdir:@@ -313,6 +345,7 @@ def _run(args: argparse.Namespace) -> int:alpha_mode=args.alpha_mode,chroma_key=args.chroma_key,white_check=args.white_check,+ trim_alpha=bool(getattr(args, "trim_alpha", False)),keep_session=args.keep_session,workdir=args.workdir,)@@ -392,6 +425,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:),)parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")+ parser.add_argument("--trim-alpha", action="store_true", help="with --transparent: crop the published PNG to its opaque bbox so the bottom edge is the foot line (margins reported)")parser.add_argument("--white-check", type=Path, help="write a white-composite check image")parser.add_argument("--keep-session", action="store_true", help="codex: do not delete the rollout jsonl")parser.add_argument("--report", type=Path, help="write the generation report JSON here")diff --git a/tests/gen/test_trim_alpha.py b/tests/gen/test_trim_alpha.pynew file mode 100644index 0000000..4916f00--- /dev/null+++ b/tests/gen/test_trim_alpha.py@@ -0,0 +1,38 @@+from pathlib import Path++import pytest+from PIL import Image++from sprite_gen.gen import trim_to_alpha+++def test_trim_to_alpha_crops_to_the_opaque_bbox_and_reports_margins(tmp_path: Path) -> None:+ p = tmp_path / "still.png"+ im = Image.new("RGBA", (100, 150), (0, 0, 0, 0))+ for y in range(20, 120): # subject occupies y 20..119, x 30..69 — 30 px of empty alpha below the feet+ for x in range(30, 70):+ im.putpixel((x, y), (200, 60, 60, 255))+ im.save(p)+ stats = trim_to_alpha(p)+ with Image.open(p) as out:+ assert out.size == (40, 100)+ assert stats["bbox"] == [30, 20, 70, 120]+ assert stats["before"] == [100, 150] and stats["after"] == [40, 100]+ assert stats["margin_px"] == {"left": 30, "top": 20, "right": 30, "bottom": 30}+++def test_trim_to_alpha_ignores_faint_alpha_specks(tmp_path: Path) -> None:+ p = tmp_path / "still.png"+ im = Image.new("RGBA", (50, 50), (0, 0, 0, 0))+ im.putpixel((25, 25), (255, 255, 255, 255))+ im.putpixel((2, 48), (255, 255, 255, 3)) # below the threshold: not part of the subject+ im.save(p)+ stats = trim_to_alpha(p)+ assert stats["bbox"] == [25, 25, 26, 26]+++def test_trim_to_alpha_refuses_a_fully_transparent_image(tmp_path: Path) -> None:+ p = tmp_path / "empty.png"+ Image.new("RGBA", (10, 10), (0, 0, 0, 0)).save(p)+ with pytest.raises(SystemExit, match="fully transparent"):+ trim_to_alpha(p)