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(video): add explicit XY motion correction for reviewed loops

Soohong Kimbb839ad5f45e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37fc891..17cfa03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+## Unreleased
+
+- Add explicit `video-loop --anchor motion` for reviewed fixed cuts with head and torso regions. Masked XY registration and boundary velocity determine one integer translation ramp; padded cycle PNGs retain the original keyed pixels. Reports record the inputs and shifts, and the unchanged seam threshold measures the rendered output. Automatic cycle selection and existing anchor defaults are unchanged; batch generation rejects this review-only mode before provider work.
+
## v2.5.6 - Walk and run loops close their wrap with one ramp
- Walk and run loops close their wrap with one ramp. `video-loop --anchor body` (now the default for `walk` and `run`) measures how far the last frame's head and torso sit from the first's, once, by whole-pixel registration over the top of the first frame's box, and shifts frame k by that offset times k/L. It never fits frame by frame: per-frame fitting turns a head bob into a full-body shiver, and the feet anchor pins the planted foot, which a quadruped moves every step. A cycle whose wrap already lands (most bipeds) is left byte-identical; the strip sidecar records `wrap_dx_px` and `seam_ratio_after_anchor`. `--anchor feet` and `--anchor none` are unchanged, and other states keep `none`.
diff --git a/docs/loop-review.md b/docs/loop-review.md
index 3017c7b..7f50f4f 100644
--- a/docs/loop-review.md
+++ b/docs/loop-review.md
@@ -7,7 +7,8 @@ sprite-gen video-loop --frames-dir keyed/ --out-dir loop/ --state run --fps 24
```
The caller must pass the **measured source fps**, not always 24. `video-set` obtains it
-from `video-frames`. The default anchor is `none` in both commands. The default clip
+from `video-frames`. `video-loop` defaults to `body` for walk/run and `none` otherwise;
+`video-set` defaults to `none`. The default clip
request remains 3 seconds; it does not determine the playback speed.
## What the script decides
@@ -66,9 +67,42 @@ Do not double a frame count unconditionally or duplicate existing frames. Choose
continuous interval in the original sequence. `--min-len/--max-len` can instead narrow
an evidenced search interval while leaving the exact cut to the detector.
+### Explicit XY motion correction
+
+For a visually reviewed fixed cut, `--anchor motion` measures both XY placement and
+the average movement at the wrap. Supply two rectangles in the **first selected
+source frame**, head first and torso second, excluding swinging hair, limbs and
+accessories. Coordinates are original pixels, with exclusive right/bottom edges:
+
+```bash
+sprite-gen video-loop --frames-dir keyed/ --out-dir reviewed/ --state walk \
+ --fps 24 --cycle fixed --start 4 --length 24 --anchor motion \
+ --anchor-region 60,20,90,50 --anchor-region 50,50,100,100
+```
+
+The rectangles are explicit inputs, not automatically detected regions. This mode
+requires at least six frames and is unavailable in `video-set`, where the cycle and
+its regions have not been reviewed. Existing automatic selection and default anchors
+are unchanged. A fixed cut remains `kind=fixed`; correction does not prove a gait cycle.
+
+Masked normalized cross-correlation of premultiplied RGBA (head weight 0.7, torso
+0.3) matches the first/last three frames against the first. With measured last-frame
+translation `m`, mean boundary velocity `v` and length `L`, the correction endpoint
+is `round((m-v)*(L-1)/L)`. One integer XY ramp runs from zero to that endpoint;
+it does not pin each frame or remove the original bob. Empty/flat regions and
+search-boundary matches are errors, never a fallback to another anchor.
+
+Cycle PNGs preserve the supplied keyed pixels (no additional speck removal), with
+common transparent padding to avoid clipping. Strip scaling, GIF palette conversion
+and output frame-density settings still apply. The sidecar/report records regions,
+measurements, endpoint, every shift and padding. For this mode the unchanged seam
+limit gates the **rendered, resampled cells**, recorded as `seam_measurement=rendered-cells`.
+This tests the corrected output, not the drifting input. It cannot repair missing
+poses, changing colors, limb identity or an incorrectly chosen cycle.
+
Use `--anchor feet` only when the source shows slow in-canvas translation. It removes a
linear horizontal trend; it is not a universal stabilizer, does not pin each planted foot,
-and can alter an already stationary subject. Start with the default `none`. Compare with
+and can alter an already stationary subject. Compare with `--anchor none` and
`feet` on identical frames before selecting it. Normal body bounce, clothing motion and
a model's changing anatomy are not position drift.
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 97351aa..8402d1f 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -105,6 +105,8 @@ def run_item(
facing_fix: str = "none",
prepare_side: Callable[[Path], tuple[Path, dict]] | None = None,
) -> dict[str, Any]:
+ if anchor == "motion":
+ raise SystemExit("video-set: motion anchor requires reviewed regions; use video-loop --cycle fixed")
validate_facing(facing, facing_fix)
if facing_fix not in facing_mod.FIXES:
raise SystemExit("video-set: --facing-fix must be mirror or none")
@@ -224,6 +226,8 @@ def run_set(
facing: str = "right",
facing_fix: str = "none",
) -> dict[str, Any]:
+ if anchor == "motion":
+ raise SystemExit("video-set: motion anchor requires reviewed regions; use video-loop --cycle fixed")
validate_facing(facing, facing_fix)
if facing_fix not in facing_mod.FIXES:
raise SystemExit("video-set: --facing-fix must be mirror or none")
@@ -289,7 +293,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--concurrency", type=int, default=3, help="parallel clip generations (starts are staggered regardless)")
parser.add_argument("--start-gap", type=float, default=START_GAP_SECONDS, help="seconds between clip request starts")
parser.add_argument("--shape", choices=canvas_mod.SHAPES, help="force one canvas shape for every state (e.g. wide for a costume or arms that leave a 1:1 frame)")
- parser.add_argument("--anchor", choices=loop_mod.ANCHOR_MODES, default="none", help="feet: remove in-canvas drift so every cell stands on the mean foot line")
+ parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default="none", help="feet: remove in-canvas drift so every cell stands on the mean foot line")
parser.add_argument("--spill", choices=frames_mod.SPILL_MODES, default="auto", help="auto: judge key reflections from each item's canvas still (default); small / full: force")
parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index e557ab4..02a82c7 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -39,6 +39,7 @@ from PIL import Image
from sprite_gen._deps import np
from sprite_gen.spec.runio import atomic_write_text
from sprite_gen.util.gif_utils import save_clean_gif
+from sprite_gen.video import motion_anchor
ANALYSIS_SIZE = 96 # thumbnail edge for the distance matrix
STRIP_MAX_CELLS = 64 # upper bound on cells even when they are narrow
@@ -69,7 +70,7 @@ ONE_SHOT_MIN_LEN = 4 # a one-shot's length is the clip's own fact; only a degen
GAIT_DOUBLE_TOL = 0.25
GAIT_DOUBLE_SEARCH = 3 # frames either side of 2x the step where the full gait's own minimum may sit
GAIT_NEAR_EXACT_STEP_FRACTION = 0.10 # no ambiguity extension when repeat error is tiny compared with a playback step
-ANCHOR_MODES = ("none", "feet", "body")
+ANCHOR_MODES = ("none", "feet", "body", "motion")
BODY_ANCHOR_BAND = 0.6 # --anchor body reads the wrap offset from the top 60 % of the first frame's box: head and torso, not the legs
BODY_ANCHOR_SEARCH = 24 # px either side searched for the last frame's horizontal offset against the first
FOOT_BAND = 0.08 # fraction of the frame's own height, measured up from its lowest opaque row
@@ -138,7 +139,11 @@ def profile_for(state: str | None) -> LoopProfile:
def _load_small(path: Path) -> np.ndarray:
- im = Image.open(path).convert("RGBA")
+ return _small_features(Image.open(path).convert("RGBA"))
+
+
+def _small_features(image: Image.Image) -> np.ndarray:
+ im = image.copy()
im.thumbnail((ANALYSIS_SIZE, ANALYSIS_SIZE))
a = np.asarray(im, dtype=np.float32) / 255.0
rgb = a[..., :3] * a[..., 3:4] # premultiplied: transparent pixels contribute 0
@@ -735,12 +740,17 @@ def run_loop(
strip_height: int = STRIP_MAX_HEIGHT,
body_height: int | None = None,
anchor: str | None = None,
+ anchor_regions: list[motion_anchor.Box] | None = None,
) -> dict[str, Any]:
if anchor is None:
# gaits drift a few pixels over a cycle and the wrap shows it; in-place states do not
anchor = "body" if profile_for(state).gait else "none"
if anchor not in ANCHOR_MODES:
raise SystemExit(f"video-loop: unknown --anchor {anchor!r}; expected one of {', '.join(ANCHOR_MODES)}")
+ try:
+ motion_anchor.validate_request(anchor, cycle_mode, length, anchor_regions)
+ except ValueError as exc:
+ raise SystemExit(f"video-loop: {exc}") from exc
if cycle_mode not in CYCLE_MODES:
raise SystemExit(f"video-loop: unknown --cycle {cycle_mode!r}; expected one of {', '.join(CYCLE_MODES)}")
frames_dir = frames_dir.expanduser().resolve()
@@ -761,6 +771,8 @@ def run_loop(
"out_dir": str(out_dir), "state": state, "fps": fps, "frames_total": n,
"window": [lo, hi], "profile": prof.why, "cycle_mode": cycle_mode,
"seam_max": seam_max,
+ "anchor": anchor,
+ "seam_measurement": "rendered-cells" if anchor == "motion" else "source-frames",
}
cycle = None
try:
@@ -804,17 +816,15 @@ def run_loop(
out_dir = out_dir.expanduser().resolve()
cycle_dir = out_dir / "cycle"
- cycle_dir.mkdir(parents=True, exist_ok=True)
- for old in cycle_dir.glob("frame-*.png"):
- old.unlink()
frames: list[Image.Image] = []
scrubbed = specks = 0
for k, f in enumerate(files[i : i + L]):
im = Image.open(f).convert("RGBA")
- scrubbed += _scrub(im)
- im, d = _drop_specks(im, SPECK_MIN_FRACTION)
- specks += d
- im.save(cycle_dir / f"frame-{k:03d}.png")
+ # Motion review is pixel preserving: cleanup belongs to the keyed input.
+ if anchor != "motion":
+ scrubbed += _scrub(im)
+ im, d = _drop_specks(im, SPECK_MIN_FRACTION)
+ specks += d
frames.append(im)
cycle_seconds = L / fps
@@ -822,9 +832,26 @@ def run_loop(
if anchor == "body":
wrap_dx = body_wrap_offset(frames)
frames = ramp_frames(frames, wrap_dx)
- for k, im in enumerate(frames):
- im.save(cycle_dir / f"frame-{k:03d}.png")
+ motion = None
+ if anchor == "motion":
+ try:
+ frames, motion = motion_anchor.correct_motion(
+ frames, anchor_regions, coarse_dx=body_wrap_offset(frames, search=motion_anchor.COARSE_SEARCH),
+ )
+ except ValueError as exc:
+ error = f"video-loop: {exc}"
+ write_loop_report(target, {**report_base, "status": "failed", "error": error, "cycle": cycle})
+ raise SystemExit(error) from exc
+ report_base["motion_anchor"] = motion
+ cycle_dir.mkdir(parents=True, exist_ok=True)
+ for old in cycle_dir.glob("frame-*.png"):
+ old.unlink()
+ for k, im in enumerate(frames):
+ im.save(cycle_dir / f"frame-{k:03d}.png")
strip, strip_meta = build_strip(frames, max_height=strip_height, cycle_seconds=cycle_seconds, body_height=body_height, anchor="feet" if anchor == "feet" else "none", kind=str(cycle.get("kind") or "periodic"))
+ if motion is not None:
+ strip_meta["foot_anchor"] = "motion"
+ strip_meta["motion_anchor"] = motion
if anchor == "body":
strip_meta["foot_anchor"] = "body"
strip_meta["wrap_dx_px"] = wrap_dx
@@ -849,6 +876,11 @@ def run_loop(
seam_idx = [i + j for j in idx]
resampled_adjacent = float(np.mean([D[seam_idx[k], seam_idx[k + 1]] for k in range(len(seam_idx) - 1)]))
resampled_seam = float(D[seam_idx[-1], seam_idx[0]])
+ if anchor == "motion":
+ # Gate the actual corrected/resampled strip cells, with the same limit.
+ flat = np.stack([_small_features(im) for im in pick])
+ resampled_adjacent = float(np.abs(flat[1:] - flat[:-1]).mean())
+ resampled_seam = float(np.abs(flat[-1] - flat[0]).mean())
seam_ratio = resampled_seam / resampled_adjacent if resampled_adjacent > 0 else math.inf
delay_ms = max(20, round(1000 * cycle_seconds / n_out))
gif_path = out_dir / f"{name}.gif"
@@ -872,6 +904,7 @@ def run_loop(
webp_report = verify_animation(webp_path, expect_frames=n_out, check_stale=True)
payload = {
+ **report_base,
"kind": "sprite-gen-video-loop-report",
"frames_dir": str(frames_dir),
"out_dir": str(out_dir),
@@ -919,6 +952,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--strip-height", type=int, default=STRIP_MAX_HEIGHT, help=f"cell/strip/GIF height cap in px (default {STRIP_MAX_HEIGHT}); the cycle is scaled down to fit, and never up unless --body-height asks for it")
parser.add_argument("--body-height", type=int, help="scale so the STANDING height (tallest floor-contact frame) is this many px — the same value across states gives the same character size; --strip-height stays the cap")
parser.add_argument("--anchor", choices=ANCHOR_MODES, default=None, help="body (default for walk/run): measure the last-to-first head-and-torso offset once and spread it as a ramp over the cycle; feet: remove in-canvas drift (a straight-line trend) so every cell stands on the mean foot line; none: leave placement as filmed (default for other states)")
+ parser.add_argument("--anchor-region", type=motion_anchor.parse_region, action="append", help="motion anchor only: repeat twice with head then torso x0,y0,x1,y1 in the first selected frame; requires --cycle fixed and at least 6 frames")
parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")
parser.add_argument("--report", type=Path)
@@ -933,6 +967,7 @@ def run(**kwargs: object) -> int:
start=kwargs.get("start"), length=kwargs.get("length"), strip_height=int(kwargs.get("strip_height") or STRIP_MAX_HEIGHT), # type: ignore[arg-type]
body_height=kwargs.get("body_height"), # type: ignore[arg-type]
anchor=kwargs.get("anchor"), # None resolves by state inside run_loop
+ anchor_regions=kwargs.get("anchor_region"),
)
summary = {k: payload[k] for k in ("state", "frames_total", "window", "cycle_seconds", "n_out", "delay_ms", "resampled_seam_ratio", "specks_dropped", "report")}
summary["cycle"] = {k: payload["cycle"].get(k) for k in ("kind", "start", "length", "period_global", "ratio", "review_recommended", "half_period_guard")}
diff --git a/sprite_gen/video/motion_anchor.py b/sprite_gen/video/motion_anchor.py
new file mode 100644
index 0000000..e4d3a76
--- /dev/null
+++ b/sprite_gen/video/motion_anchor.py
@@ -0,0 +1,153 @@
+"""Integer XY drift correction from explicitly selected head and torso regions.
+
+Match the first/last three poses, then apply ONE linear translation ramp. This
+preserves the original motion instead of pinning the subject in every frame.
+Region coordinates belong to the first frame of an already selected cycle.
+"""
+from __future__ import annotations
+
+import argparse
+from numbers import Integral
+
+from PIL import Image
+
+from sprite_gen._deps import np
+
+REGION_WEIGHTS = (0.7, 0.3)
+SEARCH_RADIUS = (14, 28)
+COARSE_SEARCH = 64
+Box = tuple[int, int, int, int]
+
+
+def parse_region(value: str) -> Box:
+ try:
+ coordinates = tuple(int(v.strip()) for v in value.split(","))
+ if len(coordinates) != 4:
+ raise ValueError
+ except ValueError:
+ raise argparse.ArgumentTypeError("region must be x0,y0,x1,y1 (four integers)") from None
+ return coordinates
+
+
+def validate_request(anchor: str, cycle_mode: str, length: int | None, regions: list[Box] | None) -> None:
+ if anchor != "motion":
+ if regions is not None:
+ raise ValueError("--anchor-region requires --anchor motion")
+ return
+ if cycle_mode != "fixed" or length is None or length < 6:
+ raise ValueError("--anchor motion requires --cycle fixed and --length >= 6")
+ if regions is None or len(regions) != 2:
+ raise ValueError("--anchor motion needs two --anchor-region values: head, then torso")
+
+
+def _features(image: Image.Image) -> np.ndarray:
+ rgba = np.asarray(image, dtype=np.float32) / 255
+ return np.concatenate((rgba[:, :, :3] * rgba[:, :, 3:4], rgba[:, :, 3:4]), axis=2)
+
+
+def _references(image: np.ndarray, regions: list[Box]) -> list[tuple]:
+ height, width = image.shape[:2]
+ references = []
+ if len(regions) != 2:
+ raise ValueError("motion anchor needs exactly two regions: head, then torso")
+ for box in regions:
+ if len(box) != 4 or any(not isinstance(v, Integral) or isinstance(v, bool) for v in box):
+ raise ValueError("motion anchor regions must have four integer coordinates")
+ x0, y0, x1, y1 = box
+ if not (0 <= x0 < x1 <= width and 0 <= y0 < y1 <= height):
+ raise ValueError(f"motion anchor region outside first frame: {box}")
+ patch = image[y0:y1, x0:x1]
+ mask = patch[:, :, 3] > 0.05
+ if not mask.any():
+ raise ValueError(f"motion anchor region contains no foreground: {box}")
+ for _ in range(2):
+ padded = np.pad(mask, 1)
+ mask = np.logical_or.reduce([
+ padded[y:y + mask.shape[0], x:x + mask.shape[1]]
+ for x, y in ((1, 1), (0, 1), (2, 1), (1, 0), (1, 2))
+ ])
+ flat = patch[mask]
+ if not np.ptp(flat, axis=0).any():
+ raise ValueError(f"motion anchor region has no measurable texture or contour: {box}")
+ centered = flat - flat.mean(axis=0)
+ norm = float(np.sqrt(np.sum(centered ** 2)))
+ if norm <= 1e-12:
+ raise ValueError(f"motion anchor region has no measurable texture or contour: {box}")
+ references.append((box, mask, centered, norm))
+ return references
+
+
+def _register(references: list[tuple], moving: np.ndarray, center: tuple[int, int]) -> dict:
+ cx, cy = center
+ rx, ry = SEARCH_RADIUS
+ candidates = []
+ for dy in range(cy - ry, cy + ry + 1):
+ for dx in range(cx - rx, cx + rx + 1):
+ costs = []
+ for (x0, y0, x1, y1), mask, reference, norm in references:
+ if x0 - dx < 0 or y0 - dy < 0 or x1 - dx > moving.shape[1] or y1 - dy > moving.shape[0]:
+ break
+ patch = moving[y0 - dy:y1 - dy, x0 - dx:x1 - dx][mask]
+ if not np.ptp(patch, axis=0).any():
+ break
+ patch = patch - patch.mean(axis=0)
+ denominator = norm * float(np.sqrt(np.sum(patch * patch)))
+ if denominator <= 1e-12:
+ break
+ costs.append(1 - float(np.sum(reference * patch) / denominator))
+ if len(costs) == 2:
+ candidates.append((sum(w * c for w, c in zip(REGION_WEIGHTS, costs)), dx, dy, costs))
+ if not candidates:
+ raise ValueError("motion anchor found no measurable match inside the search window")
+ candidates.sort()
+ score, dx, dy, costs = candidates[0]
+ if abs(dx - cx) == rx or abs(dy - cy) == ry:
+ raise ValueError("motion anchor match reached search boundary; inspect the cut and regions")
+ return {"dx": dx, "dy": dy, "cost": score, "region_costs": costs}
+
+
+def correct_motion(frames: list[Image.Image], regions: list[Box], *, coarse_dx: int) -> tuple[list[Image.Image], dict]:
+ """Correct drift without changing frame order, RGBA pixels or the local bob.
+
+ ``coarse_dx`` is the horizontal body wrap measurement (search=COARSE_SEARCH).
+ It centers the bounded XY search, not the resulting correction.
+ """
+ if len(frames) < 6:
+ raise ValueError("motion anchor requires at least six cycle frames")
+ if any(im.mode != "RGBA" or im.size != frames[0].size for im in frames):
+ raise ValueError("motion anchor needs RGBA frames with identical dimensions")
+ if abs(coarse_dx) >= COARSE_SEARCH:
+ raise ValueError("motion anchor coarse match reached search boundary")
+ references = _references(_features(frames[0]), regions)
+ length = len(frames)
+ measurements = []
+ for k in (0, 1, 2, length - 3, length - 2, length - 1):
+ center = (round(coarse_dx * k / (length - 1)), 0)
+ measurements.append({"k": k, **_register(references, _features(frames[k]), center)})
+ positions = -np.array([[r["dx"], r["dy"]] for r in measurements], dtype=float)
+ v_start = (positions[2] - positions[0]) / 2
+ v_end = (positions[5] - positions[3]) / 2
+ velocity = (v_start + v_end) / 2
+ match = np.array([measurements[-1]["dx"], measurements[-1]["dy"]], dtype=float)
+ # Equalize the wrap's displacement with the mean adjacent displacement:
+ # -p_last-d = velocity+d/(length-1).
+ endpoint_float = (match - velocity) * (length - 1) / length
+ endpoint = np.rint(endpoint_float).astype(int)
+ shifts = np.rint(np.linspace((0, 0), endpoint, length)).astype(int)
+ # Common origin + enough room for every ORIGINAL canvas, not just its bbox.
+ left, top = (-np.minimum(shifts.min(axis=0), 0)).tolist()
+ right, bottom = np.maximum(shifts.max(axis=0), 0).tolist()
+ width, height = frames[0].size
+ corrected = []
+ for frame, (dx, dy) in zip(frames, shifts.tolist()):
+ canvas = Image.new("RGBA", (width + left + right, height + top + bottom))
+ canvas.paste(frame, (left + dx, top + dy))
+ corrected.append(canvas)
+ return corrected, {
+ "method": "masked-ncc-boundary-velocity-v1", "regions": [list(b) for b in regions],
+ "region_weights": list(REGION_WEIGHTS), "search_radius_xy": list(SEARCH_RADIUS),
+ "coarse_dx_px": coarse_dx, "boundary_measurements": measurements,
+ "raw_start_velocity_xy": v_start.tolist(), "raw_end_velocity_xy": v_end.tolist(),
+ "endpoint_float_xy": endpoint_float.tolist(), "endpoint_xy": endpoint.tolist(),
+ "shifts_xy": shifts.tolist(), "padding_ltrb": [left, top, right, bottom],
+ }
diff --git a/tests/video/test_motion_anchor.py b/tests/video/test_motion_anchor.py
new file mode 100644
index 0000000..a05eeab
--- /dev/null
+++ b/tests/video/test_motion_anchor.py
@@ -0,0 +1,146 @@
+"""Behavior of explicit XY drift correction on synthetic, fully known motion."""
+import json
+import math
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.video import batch, loop, motion_anchor as motion
+
+REGIONS = [(55, 27, 86, 60), (48, 61, 94, 110)]
+
+
+def walker(k, *, drift=True):
+ dx = k if drift else 0
+ dy = round(k / 4) if drift else 0
+ bob = round(3 * math.sin(2 * math.pi * k / 24))
+ im = Image.new("RGBA", (180, 180))
+ draw = ImageDraw.Draw(im)
+ x, y = dx, dy + bob
+ draw.rectangle((60+x, 32+y, 80+x, 54+y), fill=(200, 130, 70, 255))
+ draw.rectangle((72+x, 38+y, 76+x, 42+y), fill=(15, 20, 30, 255))
+ draw.rectangle((53+x, 65+y, 88+x, 105+y), fill=(30, 90, 190, 255))
+ draw.rectangle((65+x, 70+y, 70+x, 100+y), fill=(240, 210, 80, 255))
+ leg = round(10 * math.sin(2 * math.pi * k / 24))
+ draw.rectangle((58+x+leg, 106+y, 65+x+leg, 143+y), fill=(50, 60, 70, 255))
+ draw.rectangle((79+x-leg, 106+y, 85+x-leg, 143+y), fill=(90, 40, 80, 255))
+ draw.point((60+x+leg, 110+y+k % 12), fill=(240, 240, 240, 255))
+ return im
+
+
[email protected](scope="module")
+def corrected():
+ frames = [walker(k) for k in range(24)]
+ return frames, motion.correct_motion(frames, REGIONS, coarse_dx=loop.body_wrap_offset(frames, search=64))
+
+
+def test_removes_xy_drift_but_retains_bob_and_leg_motion(corrected):
+ frames, (output, report) = corrected
+ assert report["endpoint_xy"] == [-23, -6]
+ left, top, _, _ = report["padding_ltrb"]
+ for k, (frame, (dx, dy)) in enumerate(zip(output, report["shifts_xy"])):
+ # The head follows the original periodic bob, within integer quantization.
+ pixels = np.asarray(frame)
+ head = np.all(pixels == (200, 130, 70, 255), axis=2)
+ yy, xx = np.nonzero(head)
+ assert xx.min() == 60 + left
+ assert abs(yy.min() - top - 32 - round(3 * math.sin(2 * math.pi * k / 24))) <= 1
+ # Every source pixel, including moving legs, survives one translation.
+ crop = frame.crop((left+dx, top+dy, left+dx+180, top+dy+180))
+ np.testing.assert_array_equal(np.asarray(crop), np.asarray(frames[k]))
+ assert pixels[:, :, 3].sum() == np.asarray(frames[k])[:, :, 3].sum()
+
+
+def test_padding_preserves_pixels_at_all_canvas_edges():
+ frames = [walker(k) for k in range(6)]
+ for im in frames:
+ for xy in [(0, 0), (179, 0), (0, 179), (179, 179)]:
+ im.putpixel(xy, (201, 51, 101, 128))
+ im.putpixel((1, 1), (123, 45, 67, 0))
+ output, report = motion.correct_motion(frames, REGIONS, coarse_dx=-5)
+ left, top, _, _ = report["padding_ltrb"]
+ for source, target, (dx, dy) in zip(frames, output, report["shifts_xy"]):
+ np.testing.assert_array_equal(np.asarray(target.crop((left+dx, top+dy, left+dx+180, top+dy+180))), np.asarray(source))
+
+
[email protected]("regions,error", [
+ ([(0, 0, 10, 10), REGIONS[1]], "no foreground"),
+ ([(61, 45, 69, 50), REGIONS[1]], "no measurable texture"),
+ ([(-1, 0, 10, 10), REGIONS[1]], "outside"),
+ ([(1.5, 0, 10, 10), REGIONS[1]], "integer"),
+ ([REGIONS[0]], "exactly two"),
+])
+def test_invalid_regions_fail_explicitly(regions, error):
+ with pytest.raises(ValueError, match=error):
+ motion.correct_motion([walker(0)] * 6, regions, coarse_dx=0)
+
+
+def test_search_boundary_and_short_cycle_are_errors():
+ with pytest.raises(ValueError, match="coarse match reached"):
+ motion.correct_motion([walker(0)] * 6, REGIONS, coarse_dx=64)
+ with pytest.raises(ValueError, match="at least six"):
+ motion.correct_motion([walker(0)] * 5, REGIONS, coarse_dx=0)
+ reference = motion._references(motion._features(walker(0)), REGIONS)
+ # Best match lands exactly at dx=-14, the bounded fine search edge.
+ shifted = Image.new("RGBA", (180, 180))
+ shifted.paste(walker(0), (14, 0))
+ with pytest.raises(ValueError, match="search boundary"):
+ motion._register(reference, motion._features(shifted), (0, 0))
+
+
+def test_cli_writes_corrected_cycle_and_gates_rendered_cells(tmp_path, corrected):
+ source, (expected, report) = corrected
+ keyed = tmp_path / "keyed"
+ keyed.mkdir()
+ for k, im in enumerate(source):
+ im.save(keyed / f"{k:03}.png")
+ out = tmp_path / "output"
+ args = ["--frames-dir", str(keyed), "--out-dir", str(out), "--state", "walk",
+ "--cycle", "fixed", "--start", "0", "--length", "24", "--anchor", "motion",
+ "--anchor-region", "55,27,86,60", "--anchor-region", "48,61,94,110"]
+ assert loop.main(args) == 0
+ result = json.loads((out / "loop.loop.report.json").read_text())
+ assert result["status"] == "passed"
+ assert result["cycle"]["start"] == 0 and result["cycle"]["length"] == 24
+ assert result["cycle"]["kind"] == "fixed"
+ assert result["motion_anchor"] == report
+ assert result["seam_measurement"] == "rendered-cells"
+ assert result["scrubbed_rgb_pixels"] == result["specks_dropped"] == 0
+ assert result["resampled_seam_ratio"] <= 2
+ for path, im in zip(sorted((out / "cycle").glob("*.png")), expected):
+ np.testing.assert_array_equal(np.asarray(Image.open(path)), np.asarray(im))
+ # Changing the limit still refuses the output; motion mode never skips the gate.
+ with pytest.raises(SystemExit, match="loop seam ratio"):
+ loop.main(args + ["--seam-max", "0.001"])
+ assert json.loads((out / "loop.loop.report.json").read_text())["status"] == "failed"
+
+
+def test_contract_refused_before_reading_files_or_generating(tmp_path):
+ with pytest.raises(SystemExit, match="requires --cycle fixed"):
+ loop.main(["--frames-dir", "/missing", "--out-dir", str(tmp_path), "--anchor", "motion"])
+ with pytest.raises(ValueError, match="requires --anchor motion"):
+ motion.validate_request("body", "fixed", 24, REGIONS)
+ with pytest.raises(ValueError, match="two --anchor-region"):
+ motion.validate_request("motion", "fixed", 24, None)
+ with pytest.raises(SystemExit, match="reviewed regions"):
+ batch.run_set(bases={}, states=["walk"], root=tmp_path / "batch", character=None,
+ duration=3, resolution="720p", key="green", concurrency=1,
+ force=False, gap=0, anchor="motion")
+ assert not (tmp_path / "batch").exists()
+
+
+def test_failed_registration_writes_a_report_before_output(tmp_path):
+ keyed = tmp_path / "keyed"
+ keyed.mkdir()
+ for k in range(6):
+ walker(k).save(keyed / f"{k}.png")
+ out = tmp_path / "result"
+ with pytest.raises(SystemExit, match="no foreground"):
+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(out), "--cycle", "fixed",
+ "--start", "0", "--length", "6", "--anchor", "motion",
+ "--anchor-region", "0,0,10,10", "--anchor-region", "48,61,94,110"])
+ report = json.loads((out / "loop.loop.report.json").read_text())
+ assert report["status"] == "failed" and report["anchor"] == "motion"
+ assert not (out / "cycle").exists()