Skip to content

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

fix(resample): the places that moved or scaled a keyed picture with BICUBIC map it with coverage and colour apart

Soohong Kimb2fd548f21e8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a9cc48..20dbb17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
- **ZCRE (지크) is that route's first source**: its remote MCP, signed in with your own ZCRE account and credits, has `grok-imagine-video-1.5` (Grok Imagine Pro) for image-to-video, with no end frame and no Lite model. `--no-last-frame` refuses what `video-set` films pinned — idle, attack, a walk or run in a diagonal — and `--unpinned` films one anyway with a warning (the loop is searched instead of cut whole and may not close). Walk, run and jump from the side, front and back are supported.
- **`video-frames` reads the picture of a clip that carries more**: it takes the first video stream that is not a cover image (`attached_pic`, `stream_index`), and records `codec`, `pix_fmt`, `audio_streams` and `cover_streams`. A ZCRE clip always has an AAC track and an mjpeg cover; the audio is never extracted and the loop outputs carry no sound.
- Measured once end to end: one side walk, 720p 3 s, 52 credits, 33.6 s to generate; the clip was 960×960 H.264 `yuv420p` with an AAC track and a cover, and it cut to a periodic 20-frame loop.
+- **The places that moved or scaled a keyed picture with BICUBIC map it with coverage and colour apart** (`transform_cell`, beside `resize_cell` in `sprite_gen/util/resample.py`): the gait fallback's scaled-back frames (`video-loop --anchor motion-auto` on a walk that grows or shrinks through the clip) and a curated move, scale, rotation or shear baked on a smooth row (`curation.apply_transform`, so `compose`, the GIF, the PNG export and the cycle bake). BICUBIC over premultiplied RGBA has the same negative lobe as LANCZOS, smaller, and drew the same lighter rim and key tint at the edge. On the synthetic outlined figure (`tests/keyed_figure.py`) it left 1,088 to 1,864 pixels with a colour none of the four source pixels under them had when a frame was scaled back by 0.84x to 1.19x, and 840 to 2,102 for a half-pixel move, a 10° rotation, a 0.75x shrink, a shear and a 1.3x grow with a 15° rotation; none are left. Coverage keeps BICUBIC's edge, held to the coverage of the 2 x 2 source pixels the colour mixes from; colour is a BILINEAR mix of premultiplied colour, so it is no longer sharpened. A pixel row's curated transform (`fit.pixel_unfake`, NEAREST and re-snapped) and an identity transform are unchanged. The scene GIF's downscale stays LANCZOS: it scales opaque composited frames, where there is no coverage to divide by. [docs/video-pipeline.md](docs/video-pipeline.md), [docs/loop-review.md](docs/loop-review.md), [docs/curation.md](docs/curation.md), [docs/pixel-unfake.md](docs/pixel-unfake.md).
## v2.20.0 - A keyed picture is scaled without a light rim or a green tint at the edge wherever the engine scales one: a row frame, a sliced sheet, a scene layer
diff --git a/docs/curation.md b/docs/curation.md
index 96a8d26..3f768fd 100644
--- a/docs/curation.md
+++ b/docs/curation.md
@@ -264,7 +264,7 @@ The chosen layout source is always reported (`manifest` / `grid-explicit` / `aut
[`recolor.md`](recolor.md).
- `selected` — 0-based frame indices in play order. Absent/empty → all extracted frames in order.
- `order` — optional, webview-owned: the full display order (sequence row then candidate-pool row) so reopening the curator restores the exact arrangement of both rows. `compose` / `state_plan` ignore it and key off `selected`.
-- `transforms` — keyed by 0-based frame index. `rotate` degrees (counter-clockwise positive, PIL convention), `scale` multiplier about center, `dx`/`dy` pixel offsets in the cell (+x right, +y down), `shx`/`shy` shear, `flipX` (0|1) horizontal mirror. Absent → identity. On a `fit.pixel_unfake` run, rows baking the pixel variant re-snap the transformed result onto the fixed logical grid (`apply_transform(snap_scale=…)`, mirrored live by the webview) — see [`pixel-unfake.md`](pixel-unfake.md).
+- `transforms` — keyed by 0-based frame index. `rotate` degrees (counter-clockwise positive, PIL convention), `scale` multiplier about center, `dx`/`dy` pixel offsets in the cell (+x right, +y down), `shx`/`shy` shear, `flipX` (0|1) horizontal mirror. Absent → identity. On a `fit.pixel_unfake` run, rows baking the pixel variant re-snap the transformed result onto the fixed logical grid (`apply_transform(snap_scale=…)`, mirrored live by the webview) — see [`pixel-unfake.md`](pixel-unfake.md). Every other row bakes the transform with its coverage and its colour mapped apart (`transform_cell`, [`video-pipeline.md`](video-pipeline.md) "Cells"), so a rotated or scaled keyed frame gets no lighter rim or key tint at its edge.
- A state missing from the sidecar uses the all-frames identity default.
- The transform is applied at compose time inside the request-sized cell, so atlas geometry never changes. `manifest.json.animation.rows.<state>.frames` reflects the curated frame count, and `manifest.json.curation_applied` records whether a sidecar was used.
diff --git a/docs/loop-review.md b/docs/loop-review.md
index cd224d6..d2039a4 100644
--- a/docs/loop-review.md
+++ b/docs/loop-review.md
@@ -100,7 +100,9 @@ front or back gait does that the first search cannot see past:
sometimes comes closer, and the body grows through the clip, so the same pose never matches
itself in size. A straight-line fit of the subject's opaque height measures it; at 3 % or
more over the clip (`SCALE_DRIFT_MIN`) every frame is scaled back to the first frame's fitted
- height about its fitted foot point, premultiplied so the soft edge keeps its colour. The
+ height about its fitted foot point, with its coverage and its colour mapped apart
+ (`transform_cell`, [video-pipeline.md](video-pipeline.md) "Cells") so the soft edge keeps its
+ colour and gets no lighter rim or key tint from the resample. The
search, the cells and the seam gate then all read the scaled-back frames. On the walk clips
we have kept, the median change is 0.5 % and nine in ten stay under 2.7 %.
- **It walked slowly.** A calm walk in long clothing can take longer than half the clip per
diff --git a/docs/pixel-unfake.md b/docs/pixel-unfake.md
index 3ab17eb..4fa180b 100644
--- a/docs/pixel-unfake.md
+++ b/docs/pixel-unfake.md
@@ -107,7 +107,7 @@ AI 개입은 **raw 생성 한 곳뿐**이다 (`SKILL.md` 필수 게이트). 픽
`fit.pixel_unfake` 런에서 추출은 픽셀 언페이크 결과(`frame-N.png`, canonical)와 함께 **적용 전 쌍둥이 두 개**를 저장한다: **셀 크기 `frame-N.plain.png`**(굽기용 — 아틀라스 슬롯이 셀 크기라 compose 가 이걸 읽는다)와 **고해상 `orig/frame-N.png`**(표시 전용 — S×셀, pp 해제 표시가 셀 확대 흐림 없이 원본 화질. S 는 행별 네이티브 배율: 프레임들의 컴포넌트 crop/최종 콘텐츠 bbox 비율 최대값의 ceil, 상한 `2048//cell` — 리샘플이 경미한 업스케일이 되도록 해 다운스케일 뭉갬을 금지한다. 구 고정 ×4 캡은 고피치 raw 를 눌러 "원본" 뷰가 원본이 아니게 됐다, maintainer 2026-07-23). 두 쌍둥이 모두 **픽셀 언페이크 프레임의 최종 콘텐츠 bbox 와 같은 풋프린트**에 앉힌다(`fit_component_to_bbox`) — 토글이 크기 변화 없이 픽셀 처리 품질만 비교하고, plain 굽기도 pp 줄과 같은 캐릭터 크기를 유지한다. (이전엔 legacy fit 이 가용영역을 채워 pp 결과보다 ~8% 크게 앉았고 토글 순간 크기가 튀었다.) 빈 프레임은 warning 으로 관측, 해당 쌍둥이만 빠진다.
-**변형 굽기도 격자를 지킨다**: 픽셀 변형을 굽는 줄의 큐레이션 변형(이동/확대/회전/기울이기/반전)은 BICUBIC 이 아니라 **NEAREST 샘플 + 셀 고정 논리 격자 재양자화**(`apply_transform(snap_scale=…)`, 스케일 SSoT = `curation.pixel_snap_scale`)로 굽는다 — 어떤 변형도 픽셀 격자를 뭉갤 수 없다. 큐레이션 웹뷰는 같은 양자화를 캔버스로 미러링해(`drawFrameInto`) **드래그하는 동안에도 스프라이트가 고정 격자에 실시간 스냅되어 보인다** (격자는 셀에 고정, 그림이 격자 단위로 이동). plain 변형을 굽는 줄은 격자 예술이 아니므로 기존 BICUBIC 유지.
+**변형 굽기도 격자를 지킨다**: 픽셀 변형을 굽는 줄의 큐레이션 변형(이동/확대/회전/기울이기/반전)은 BICUBIC 이 아니라 **NEAREST 샘플 + 셀 고정 논리 격자 재양자화**(`apply_transform(snap_scale=…)`, 스케일 SSoT = `curation.pixel_snap_scale`)로 굽는다 — 어떤 변형도 픽셀 격자를 뭉갤 수 없다. 큐레이션 웹뷰는 같은 양자화를 캔버스로 미러링해(`drawFrameInto`) **드래그하는 동안에도 스프라이트가 고정 격자에 실시간 스냅되어 보인다** (격자는 셀에 고정, 그림이 격자 단위로 이동). plain 변형을 굽는 줄은 격자 예술이 아니므로 부드럽게 굽는다 — 커버리지와 색을 나눠 매핑한다(`transform_cell`, [video-pipeline.md](video-pipeline.md) "Cells"). BICUBIC 으로 바로 굽던 때는 키잉 그림 가장자리에 소스에 없던 밝은 테두리와 키 색이 남았다.
토글은 **줄(state) 단위**다: 쌍둥이가 실재하는 각 줄의 "생성 재료" 줄 우측(프레임 이미지 바로 위)에 **줄별 "픽셀 언페이크" 체크박스**가 뜨고, 우측 상단 체크박스는 **전체 토글**(모든 줄을 한번에 설정; 줄별 값이 섞이면 indeterminate 표시)이다. 픽셀 격자 오버레이도 같은 모양이다 — 격자를 아는 줄마다 줄별 "픽셀 격자" 체크박스 + 상단 "픽셀 격자 전체" 토글(표시 전용, 저장 안 함). 각 토글이 그 줄의 **표시와 굽기를 함께 결정**한다(별도 보기 토글 없음; curator `src/display.js`·`src/row-controls.js`, run-contract §3 원본화질 토글 행과 일치). 켠 줄은 canonical `frame-N.png`(픽셀 언페이크)를 표시·굽고, 끈 줄은 표시는 `orig/` 고해상본 우선(없으면 `.plain.png`)·굽기는 셀 크기 `.plain.png` 변형으로 전환하며(끈 줄은 스냅 격자가 아니므로 픽셀 격자 오버레이도 숨긴다) `curation.json` 의 `states.<state>.pixel_unfake`(줄별) + top-level `pixel_unfake`(전줄 균일할 때만 기록되는 런 기본값)에 저장된다. 해석 순서(줄별 > top-level > 기본 on)의 SSoT 는 `curation.frame_variant(curation, state)` 이고 compose·GIF·PNG export 전부 이 리졸버를 쓴다. 끈 줄의 plain 파일이 없으면 조용한 폴백 없이 에러다. report/manifest 에는 줄별 `animation.rows.<state>.frame_variant` 와 top-level 요약(`pixel`/`plain`/`mixed`)이 기록된다. 표시 계약 SSoT 는 [`run-contract.md`](run-contract.md) §3.
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 26b5037..e8c309d 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -574,7 +574,19 @@ Outputs:
GIF and WebP are cut from these cells. The function lives in `sprite_gen/util/resample.py`
and is the resample of every place that scaled a keyed picture with LANCZOS: a row frame fitted to its cell and the twin
beside a pixel-unfake frame (`extract`), a sliced sheet's figures (`slice-sheet`) and a
- scene's layers (`scene-render`) go through it too.
+ scene's layers (`scene-render`) go through it too. Its twin for an affine map,
+ `transform_cell`, does the same for the places that moved, scaled, rotated or sheared a keyed
+ picture with BICUBIC: the gait fallback's scaled-back frames (`video-loop`, "The gait
+ fallback" in [loop-review.md](loop-review.md)) and a curated transform on a smooth row
+ (`curation.apply_transform`). Coverage keeps BICUBIC's edge, held to the coverage of the
+ 2 x 2 source pixels the colour mixes from, and colour is a BILINEAR mix of premultiplied
+ colour. BICUBIC has the same negative lobe, smaller: on the synthetic figure it left 1,088 to
+ 1,864 pixels with a colour none of the four source pixels under them had when a frame was
+ scaled back by 0.84x to 1.19x, and 840 to 2,102 for a half-pixel move, a 10° rotation, a
+ 0.75x shrink, a shear and a 1.3x grow with a 15° rotation; `transform_cell` leaves none. The
+ same cost applies: colour is not sharpened. A pixel row's curated transform samples NEAREST
+ and is untouched. The scene GIF's ffmpeg downscale stays LANCZOS: it scales opaque composited
+ frames, where nothing is divided by a low coverage.
- `<name>.gif` — `n_out` frames evenly across the cycle, 1-bit alpha, disposal 2, `loop=0`.
`n_out` is a **playback density, not a fixed count**: `round(cycle_seconds × --gif-fps)`
(default 24 fps = the source rate, so every cycle frame is kept; floor 4, never more than
diff --git a/sprite_gen/compose/compose_atlas.py b/sprite_gen/compose/compose_atlas.py
index 484741f..ecd9ac1 100644
--- a/sprite_gen/compose/compose_atlas.py
+++ b/sprite_gen/compose/compose_atlas.py
@@ -100,7 +100,7 @@ def _run(args: argparse.Namespace):
# missing — a plain bake must never silently fall back to pixel.
variants = {state: frame_variant(curation, state) for state in states}
# pixel-variant rows of a fit.pixel_unfake run re-snap curated transforms to the
- # logical grid (plain rows keep the smooth BICUBIC bake — they are not grid art).
+ # logical grid (plain rows keep the smooth bake, `transform_cell` — they are not grid art).
snap_scale = pixel_snap_scale(request)
# 아틀라스 셀 재사용 (maintainer 승인 2026-07-16): 같은 (원본 프레임, 변형, 픽셀편집)으로
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.py
index 8bd94d0..7427c52 100644
--- a/sprite_gen/curate/curation.py
+++ b/sprite_gen/curate/curation.py
@@ -160,6 +160,7 @@ from PIL import Image
from sprite_gen.spec.layout import raw_rel
from sprite_gen.spec.runio import load_request
+from sprite_gen.util.resample import transform_cell
CURATION_FILENAME = "curation.json"
SCHEMA_VERSION = 1
@@ -1118,7 +1119,9 @@ def apply_transform(
c = -(ia * cout_x + ib * cout_y) + cin_x
f = -(id_ * cout_x + ie * cout_y) + cin_y
if not snap_scale:
- return src.transform((cw, ch), Image.AFFINE, (ia, ib, c, id_, ie, f), resample=Image.BICUBIC)
+ # Coverage and colour mapped apart: BICUBIC over the keyed frame drew a light rim and a
+ # key tint around the outline (docs/video-pipeline.md "Cells").
+ return transform_cell(src, (cw, ch), (ia, ib, c, id_, ie, f))
out = src.transform((cw, ch), Image.AFFINE, (ia, ib, c, id_, ie, f), resample=Image.NEAREST)
if snap_scale > 1:
logical_w, logical_h = max(1, cw // snap_scale), max(1, ch // snap_scale)
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index 502891d..8c934b0 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -423,7 +423,7 @@ def reference_key(*, state: str, variant: str, request_stamp: str, source_index:
"""기준 프레임의 **정체성** — 그 프레임을 만드는 입력들로만 만든다. 픽셀은 안 읽는다.
예전엔 이게 *변형 결과 RGBA* 의 해시였다. 그런데 굽기는 `apply_transform` 에서
- **BICUBIC** 으로 리샘플하고(`snap_scale` 없는 런 = 기본 런 전부) 웹뷰 캔버스는
+ 부드럽게 리샘플하고(당시 BICUBIC, 지금 `transform_cell`; `snap_scale` 없는 런 = 기본 런 전부) 웹뷰 캔버스는
`imageSmoothingEnabled=false`, 즉 **NEAREST** 다. 같은 원본에 같은 변형을 걸어도 두 쪽이
만드는 그림이 다르니 지문은 **영구 불일치**였다 — 회전·확대가 걸린 줄은 프리뷰가 영원히
원본으로 떨어지고 영상 내보내기가 영구 차단됐으며, 안내대로 "해부를 갱신" 해도 라우트가
diff --git a/sprite_gen/scene/render.py b/sprite_gen/scene/render.py
index 52e52ca..a8fa4bb 100644
--- a/sprite_gen/scene/render.py
+++ b/sprite_gen/scene/render.py
@@ -183,6 +183,8 @@ def encode_frames(work: Path, scene: Scene, formats: set, settings: dict):
if gif["fps"] != scene.fps:
filters.append(f"fps={gif['fps']}")
if gif["width"] != scene.width:
+ # LANCZOS stays here: the frames are opaque composites, so nothing is divided by a
+ # low coverage (the ring `resize_cell` removes from keyed layers cannot form).
filters.append(f"scale={gif['width']}:-1:flags=lanczos")
chain = ",".join(filters)
pal, dest = work / "palette.png", work / "scene.gif"
diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.js
index 4a44448..b8a55f4 100644
--- a/sprite_gen/serve/curator/src/breathe.js
+++ b/sprite_gen/serve/curator/src/breathe.js
@@ -129,7 +129,7 @@ function breatheCanon(v) {
}
// 파이썬 `breathe.reference_key` 미러 — **픽셀을 안 읽는다.**
-// 굽기는 BICUBIC(`apply_transform`), 웹뷰 캔버스는 NEAREST 라 같은 원본·같은 변형에도
+// 굽기는 부드러운 리샘플(`apply_transform`), 웹뷰 캔버스는 NEAREST 라 같은 원본·같은 변형에도
// 두 쪽이 만드는 그림이 다르다. 결과 픽셀을 해시하던 옛 지문이 회전·확대가 걸린 줄에서
// 영구 불일치였던 이유다 (validator 실측 2026-07-26).
// 파이썬 `curation.normalize_transform` 미러 — 항상 7키 전체.
diff --git a/sprite_gen/serve/curator/src/i18n.js b/sprite_gen/serve/curator/src/i18n.js
index 1a37092..1275c3c 100644
--- a/sprite_gen/serve/curator/src/i18n.js
+++ b/sprite_gen/serve/curator/src/i18n.js
@@ -63,7 +63,7 @@ const STR = {
breatheTorsoHint: "drag the torso half-width — outside these lines counts as appendage (arms/wings): pushed sideways, never stretched. Drag inward to protect more.",
breatheFail: "breathe failed: ",
breatheResample: (rows) =>
- `heads-up: ${rows} has a rotate/scale transform. the bake resamples BICUBIC, this canvas `
+ `heads-up: ${rows} has a rotate/scale transform. the bake resamples smoothly, this canvas `
+ `NEAREST — the exported file will differ from the GIF by a few edge pixels.`,
opProgress: (p, pct) => `re-deriving ${p.done}/${p.total} (${pct}%) — ${p.label} · ${p.phase}`,
healTitle: "Updating frames for the new engine",
@@ -233,7 +233,7 @@ const STR = {
breatheTorsoHint: "몸통 반폭을 드래그 — 이 선 바깥은 부속(팔·날개)으로 취급되어 늘어나지 않고 밀리기만 합니다. 안쪽으로 끌수록 보호가 넓어집니다.",
breatheFail: "호흡 실패: ",
breatheResample: (rows) =>
- `참고: ${rows} 에 회전/확대 변형이 걸려 있다. 굽기는 BICUBIC, 이 캔버스는 NEAREST 로 `
+ `참고: ${rows} 에 회전/확대 변형이 걸려 있다. 굽기는 부드럽게, 이 캔버스는 NEAREST 로 `
+ `리샘플하므로 내보낸 파일이 GIF 와 가장자리 몇 px 다르다.`,
opProgress: (p, pct) => `재추출 ${p.done}/${p.total} (${pct}%) — ${p.label} · ${p.phase === "components" ? "컴포넌트" : "픽셀 언페이크"}`,
healTitle: "엔진 갱신 반영 중 — 프레임 재계산",
diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.js
index 086469f..f5e6ac5 100644
--- a/sprite_gen/serve/curator/src/store.js
+++ b/sprite_gen/serve/curator/src/store.js
@@ -347,7 +347,7 @@ function breatheGeometryFrame(stateName, fallbackIdx) {
// 이 줄의 기준 프레임에 **정수 이동이 아닌** 변형이 걸려 있나.
//
-// 굽기는 `apply_transform` 에서 BICUBIC 으로 리샘플하고(`snap_scale` 없는 런 = 기본 런
+// 굽기는 `apply_transform` 에서 부드럽게 리샘플하고(`transform_cell`, `snap_scale` 없는 런 = 기본 런
// 전부) 이 웹뷰는 `imageSmoothingEnabled=false` 캔버스, 즉 NEAREST 다. 회전·확대가
// 걸리면 같은 입력에도 두 쪽 그림이 다르다 (실측: rotate 3° 에서 12/12 위상 최대
// 1803px 상이). 원인은 표시 파이프라인이라 호흡이 고칠 수 있는 게 아니지만, `row-export`
@@ -365,7 +365,7 @@ function breatheResamplesDifferently(stateName) {
// 파이썬 `breathe.reference_key` 의 재료를 사이드카에서 모은다 — **줄의 기준 프레임**
// (`playList[0]`, 굽기의 `images[0]`) 하나에 대해서만.
//
-// 픽셀을 안 읽는다: 굽기는 BICUBIC 으로 리샘플하고 캔버스는 NEAREST 라 결과 픽셀은
+// 픽셀을 안 읽는다: 굽기는 부드럽게 리샘플하고 캔버스는 NEAREST 라 결과 픽셀은
// 구조적으로 다르다. 여기 들어가는 값은 전부 사이드카(사람의 의도)와 서버가 준 스탬프다.
// 재료가 하나라도 없으면 **null 을 돌려 거부시킨다** — 없는 값을 기본값으로 메우면
// 서로 다른 프레임이 같은 키를 갖는다.
diff --git a/sprite_gen/serve/curator/src/zoom-editor.js b/sprite_gen/serve/curator/src/zoom-editor.js
index cdc5a95..a117b95 100644
--- a/sprite_gen/serve/curator/src/zoom-editor.js
+++ b/sprite_gen/serve/curator/src/zoom-editor.js
@@ -1049,7 +1049,7 @@ function openZoom(stateName, idx, keepWidth) {
// 굽기가 해부를 확정하는 프레임 = 재생 첫 슬롯. 신선도 판정은 이 프레임으로만 한다
// (프레임마다 보면 깜빡임처럼 정상적으로 다른 프레임까지 거부해 프리뷰가 죽는다).
- // 그림이 아니라 **키**다. 굽기(BICUBIC)와 캔버스(NEAREST)는 같은 원본·같은 변형에도
+ // 그림이 아니라 **키**다. 굽기(`transform_cell`)와 캔버스(NEAREST)는 같은 원본·같은 변형에도
// 다른 픽셀을 만들어서, 여기서 프레임을 다시 그려 지문을 찍으면 영구 불일치가 된다.
const breatheRef = () => breatheReferenceKey(stateName);
diff --git a/sprite_gen/util/resample.py b/sprite_gen/util/resample.py
index 0698b55..96bab5d 100644
--- a/sprite_gen/util/resample.py
+++ b/sprite_gen/util/resample.py
@@ -4,7 +4,9 @@
The places that scaled a keyed picture with LANCZOS go through `resize_cell`: a loop's cells
(`video-loop`), a row frame fitted to its cell and the twins beside a
pixel-unfake frame (`extract`), a sliced sheet's figures (`slice-sheet`) and a scene's layers
-(`scene`). docs/video-pipeline.md "Cells".
+(`scene`). The places that mapped one with a BICUBIC affine go through `transform_cell`: the
+gait fallback's scaled-back frames (`video-loop`) and a curated transform on a smooth row
+(`curation.apply_transform`). docs/video-pipeline.md "Cells".
"""
from __future__ import annotations
@@ -66,3 +68,34 @@ def resize_cell(image: Image.Image, size: tuple[int, int]) -> Image.Image:
colour = np.where((cover > 0)[..., None], np.round(mix / np.maximum(mix_alpha, 1e-3)[..., None]), 0)
out = np.dstack([np.clip(colour, 0, 255), np.clip(cover, 0, 255)]).astype(np.uint8)
return Image.fromarray(out, "RGBA")
+
+
+def transform_cell(image: Image.Image, size: tuple[int, int], inverse: tuple[float, ...]) -> Image.Image:
+ """`resize_cell` for an affine map: one RGBA cell moved, scaled, rotated or sheared into `size`.
+
+ `inverse` is Pillow's AFFINE data, the output -> input map. BICUBIC over premultiplied RGBA
+ rings the way LANCZOS does (a smaller negative lobe, the same division by low coverage at
+ the edge), so coverage and colour are mapped apart here too. Coverage keeps BICUBIC's edge,
+ held to the range of the 2 x 2 source pixels the colour mixes from; colour is a BILINEAR mix
+ of premultiplied colour, a filter with no negative lobe. docs/video-pipeline.md "Cells"."""
+ w, h = size
+ src = np.asarray(image.convert("RGBA"), dtype=np.float32)
+ alpha = src[..., 3]
+ a, b, c, d, e, f = inverse
+
+ def mapped(channel: np.ndarray, resample: Image.Resampling, dx: float = 0.0, dy: float = 0.0) -> np.ndarray:
+ layer = Image.fromarray(np.ascontiguousarray(channel), "F")
+ return np.asarray(layer.transform(size, Image.Transform.AFFINE, (a, b, c + dx, d, e, f + dy), resample=resample),
+ dtype=np.float32)
+
+ mix_alpha = mapped(alpha, Image.Resampling.BILINEAR)
+ mix = np.stack([mapped(src[..., k] * alpha, Image.Resampling.BILINEAR) for k in range(3)], axis=-1)
+ # The four source pixels BILINEAR reads sit half a pixel either side of the mapped centre;
+ # NEAREST at those four offsets reads exactly them (nothing outside the source: alpha 0).
+ corners = [mapped(alpha, Image.Resampling.NEAREST, dx, dy) for dx in (-0.5, 0.5) for dy in (-0.5, 0.5)]
+ low, high = np.minimum.reduce(corners), np.maximum.reduce(corners)
+ cover = np.clip(mapped(alpha, Image.Resampling.BICUBIC), low, high)
+ cover = np.where(mix_alpha > 1e-3, np.round(cover), 0)
+ colour = np.where((cover > 0)[..., None], np.round(mix / np.maximum(mix_alpha, 1e-3)[..., None]), 0)
+ out = np.dstack([np.clip(colour, 0, 255), np.clip(cover, 0, 255)]).astype(np.uint8)
+ return Image.fromarray(out, "RGBA")
diff --git a/sprite_gen/video/gait_fallback.py b/sprite_gen/video/gait_fallback.py
index f49b9d3..febbe28 100644
--- a/sprite_gen/video/gait_fallback.py
+++ b/sprite_gen/video/gait_fallback.py
@@ -22,6 +22,7 @@ from pathlib import Path
from PIL import Image
from sprite_gen._deps import np
+from sprite_gen.util.resample import transform_cell
# Height change over the clip, from the fitted trend, at which the frames are scaled back.
# Nine in ten walk clips stay under it (median 0.5 %): their change is a head bob and hair.
@@ -66,8 +67,9 @@ def scale_drift(frames: list[Image.Image]) -> dict:
def undo_scale(frames: list[Image.Image], measured: dict) -> list[Image.Image]:
"""Each frame scaled to the first frame's fitted height about its fitted foot point.
- Premultiplied while it is resampled, so the soft edge does not pick up the colour that
- sits under fully transparent pixels.
+ Coverage and colour are resampled apart (`transform_cell`), so the soft edge neither picks
+ up the colour under fully transparent pixels nor rings into a colour the frame did not have:
+ BICUBIC over the keyed frame drew a light rim and a key tint around the outline.
"""
height, foot_x, foot_y = measured["height"], measured["foot_x"], measured["foot_y"]
out = []
@@ -76,9 +78,7 @@ def undo_scale(frames: list[Image.Image], measured: dict) -> list[Image.Image]:
ax, ay = float(foot_x[k]), float(foot_y[k])
# Output (x, y) reads input anchor + (x - anchor) / s.
inverse = (1 / s, 0.0, ax * (1 - 1 / s), 0.0, 1 / s, ay * (1 - 1 / s))
- resampled = frame.convert("RGBa").transform(frame.size, Image.Transform.AFFINE, inverse,
- resample=Image.Resampling.BICUBIC)
- out.append(resampled.convert("RGBA"))
+ out.append(transform_cell(frame, frame.size, inverse))
return out
diff --git a/tests/curate/test_transform_resample.py b/tests/curate/test_transform_resample.py
new file mode 100644
index 0000000..cd504d2
--- /dev/null
+++ b/tests/curate/test_transform_resample.py
@@ -0,0 +1,53 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A curated move, scale, rotation or shear is baked without a ring at the frame's edge.
+
+`apply_transform` sampled a smooth row's transform with BICUBIC over premultiplied RGBA, which
+drew a lighter rim and a key tint around a keyed sprite that the sprite did not have; it maps
+through `transform_cell` (coverage and colour apart). A pixel row (`snap_scale`) samples
+NEAREST and is not touched. The tests fail with BICUBIC put back.
+"""
+from __future__ import annotations
+
+import pytest
+from PIL import Image
+
+from keyed_figure import colour_outside_mapped, figure
+from sprite_gen.curate.curation import apply_transform, normalize_transform, transform_matrix
+from sprite_gen.util.resample import transform_cell
+
+TRANSFORMS = {
+ "move half a pixel": {"dx": 0.5, "dy": -0.5},
+ "rotate": {"rotate": 10},
+ "shrink": {"scale": 0.75},
+ "shear": {"shx": 0.2, "shy": -0.1},
+ "grow and rotate": {"scale": 1.3, "rotate": 15},
+}
+
+
+def inverse_of(transform: dict, src: Image.Image, cell: tuple[int, int]) -> tuple[float, ...]:
+ """The output -> input map `apply_transform` builds (about the centres, then moved)."""
+ t = normalize_transform(transform)
+ m00, m01, m10, m11 = transform_matrix(t)
+ det = m00 * m11 - m01 * m10
+ ia, ib, id_, ie = m11 / det, -m01 / det, -m10 / det, m00 / det
+ ox, oy = cell[0] / 2 + t["dx"], cell[1] / 2 + t["dy"]
+ return (ia, ib, src.width / 2 - ia * ox - ib * oy, id_, ie, src.height / 2 - id_ * ox - ie * oy)
+
+
[email protected]("name", list(TRANSFORMS))
+def test_a_baked_transform_carries_no_colour_the_frame_did_not_have(name: str) -> None:
+ src = figure()
+ cell = src.size
+ out = apply_transform(src, TRANSFORMS[name], cell)
+ inverse = inverse_of(TRANSFORMS[name], src, cell)
+ assert colour_outside_mapped(src, out, inverse) == 0
+ assert out.tobytes() == transform_cell(src, cell, inverse).tobytes()
+ bicubic = src.transform(cell, Image.Transform.AFFINE, inverse, resample=Image.Resampling.BICUBIC)
+ assert colour_outside_mapped(src, bicubic, inverse) > 50
+
+
+def test_a_pixel_row_still_samples_nearest() -> None:
+ src = figure()
+ out = apply_transform(src, {"rotate": 10}, src.size, snap_scale=2)
+ colours = set(map(tuple, src.get_flattened_data()))
+ assert set(map(tuple, out.get_flattened_data())) <= colours | {(0, 0, 0, 0)}
diff --git a/tests/keyed_figure.py b/tests/keyed_figure.py
index e0e8e2a..0404dda 100644
--- a/tests/keyed_figure.py
+++ b/tests/keyed_figure.py
@@ -4,7 +4,8 @@
The figure is area-sampled: a dark-outlined body (a skin half and a white half), a light rim
outside part of the outline, green-tinted ink along another part, a 1 px line across the body,
a hair cap with strands 0.5-1.4 px wide — the edge a keyer leaves. Shared by the tests of every
-place the engine scales a keyed picture (`sprite_gen.util.resample.resize_cell`).
+place the engine scales or maps a keyed picture (`sprite_gen.util.resample.resize_cell`,
+`transform_cell`).
"""
from __future__ import annotations
@@ -104,3 +105,26 @@ def colour_outside(src: Image.Image, out: Image.Image) -> int:
seen = o[..., 3] >= 38
outside = ((o[..., :3] < lo - 1) | (o[..., :3] > hi + 1)).any(axis=-1)
return int(np.count_nonzero(seen & outside))
+
+
+def colour_outside_mapped(src: Image.Image, out: Image.Image, inverse: tuple[float, ...]) -> int:
+ """`colour_outside` for an affine map (Pillow's AFFINE data, output -> input): the colour range
+ of the visible source pixels among the 2 x 2 around each output pixel's mapped centre."""
+ s = np.asarray(src).astype(int)
+ pad = np.zeros((s.shape[0] + 2, s.shape[1] + 2, 4), int)
+ pad[1:-1, 1:-1] = s
+ a, b, c, d, e, f = inverse
+ v, u = np.mgrid[0 : out.height, 0 : out.width] + 0.5
+ x0 = np.floor(a * u + b * v + c - 0.5).astype(int)
+ y0 = np.floor(d * u + e * v + f - 0.5).astype(int)
+ lo = np.full((out.height, out.width, 3), 256)
+ hi = np.full((out.height, out.width, 3), -1)
+ for dy in (0, 1):
+ for dx in (0, 1):
+ px = pad[np.clip(y0 + dy, -1, s.shape[0]) + 1, np.clip(x0 + dx, -1, s.shape[1]) + 1]
+ seen = (px[..., 3] > 0)[..., None]
+ lo = np.where(seen, np.minimum(lo, px[..., :3]), lo)
+ hi = np.where(seen, np.maximum(hi, px[..., :3]), hi)
+ o = np.asarray(out).astype(int)
+ outside = ((o[..., :3] < lo - 1) | (o[..., :3] > hi + 1)).any(axis=-1)
+ return int(np.count_nonzero((o[..., 3] >= 38) & outside))
diff --git a/tests/video/test_gait_fallback_resample.py b/tests/video/test_gait_fallback_resample.py
new file mode 100644
index 0000000..d358586
--- /dev/null
+++ b/tests/video/test_gait_fallback_resample.py
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The gait fallback scales a frame back without a ring at its edge.
+
+`undo_scale` used BICUBIC over premultiplied RGBA, which drew a lighter rim and a key tint
+around the keyed subject that the frame did not have; it maps through `transform_cell`
+(coverage and colour apart). The tests fail with BICUBIC put back.
+"""
+from __future__ import annotations
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from keyed_figure import colour_outside_mapped, figure
+from sprite_gen.util.resample import transform_cell
+from sprite_gen.video import gait_fallback
+
+FOOT = (80.0, 170.0)
+
+
+def scaled_back(scale: float) -> tuple[Image.Image, Image.Image, tuple[float, ...]]:
+ """A second frame `1 / scale` the first's height, scaled back about the foot point."""
+ src = figure()
+ measured = {"height": np.array([100.0, 100.0 / scale]), "foot_x": np.full(2, FOOT[0]), "foot_y": np.full(2, FOOT[1])}
+ first, second = gait_fallback.undo_scale([src, src], measured)
+ assert first.tobytes() == src.tobytes() # the first frame is the reference: not resampled
+ inverse = (1 / scale, 0.0, FOOT[0] * (1 - 1 / scale), 0.0, 1 / scale, FOOT[1] * (1 - 1 / scale))
+ return src, second, inverse
+
+
[email protected]("scale", (0.84, 0.95, 1.05, 1.19))
+def test_a_scaled_back_frame_carries_no_colour_it_did_not_have(scale: float) -> None:
+ src, out, inverse = scaled_back(scale)
+ assert colour_outside_mapped(src, out, inverse) == 0
+ assert out.tobytes() == transform_cell(src, src.size, inverse).tobytes()
+ bicubic = src.convert("RGBa").transform(src.size, Image.Transform.AFFINE, inverse, resample=Image.Resampling.BICUBIC)
+ assert colour_outside_mapped(src, bicubic.convert("RGBA"), inverse) > 100