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(loop): the size hold reads a walk's change one cycle on, so a first pose that settles into the walk is not a change of size

Soohong Kim0fcbc95861c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00c04c0..cc41b4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,8 +2,10 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
-## Unreleased - A follow-through that would fold its region can take the largest gain that does not
+## Unreleased - The size hold reads a walk's change of size one cycle on, and a follow-through that would fold its region can take the largest gain that does not
+- **Output change: which walk and run loops are held at their size.** `video-loop --anchor motion-auto` with `--size-hold auto` (the default) reads the clip's change of size one cycle on instead of off a line fitted through the clip (`gait_fallback.cycle_drift`). A clip whose reading crosses 1 % one way or the other is cut differently: one that starts from a standing pose and settles into the walk is no longer held (the line read the settle as a shrinking body), and one whose settle pulled the line under 1 % while the body did grow is now held. A clip held either way is scaled back by the change one cycle on, not by the line's, so its frames differ too: a clip whose first frames zoom in reads its walk's own change, not the zoom, and can find a cycle it did not find scaled by the line. A clip under 1 % both ways, and every clip with `--size-hold off`, is cut exactly as before. `video-follow` with its default `--on-fold refuse` writes what 2.24.0 wrote.
+- **Fix: a first pose that settles into the walk read as a change of size.** The hold fitted a line to the subject's height over the clip, and a clip that stands tall in its first frames and then walks a few pixels lower read as a body shrinking the whole way: at 1 % or more it was scaled back. The hold now finds the lag at which the pose (cut out about its feet) matches itself best, compares each frame's height — to a fraction of a pixel, the rows' coverage summed — with the frames one, two, … of those lags later, and carries the median change per frame over the clip; the few frames of the first pose do not move the median of the rest. On a synthetic walker that stands 6 px taller for its first frames and walks at one size, the line read −2.2 % and, scaled back by it, the clip found no cycle; it now reads 0 and is cut as filmed. A walker that settles and grows 2.5 % read +0.6 % on the line and was not held, and found no cycle either; it is now held and cut. `size_hold` in the report carries the evidence: `method`, `lag`, `pose_match`, `pairs`, `per_lag` and `drift_fitted_line` (what the line would have read). The gait fallback after a failed search still reads the line at 3 %. [docs/video-pipeline.md](docs/video-pipeline.md#4-loop--period-first-seam-second-then-the-gait-floor).
- **New `video-follow --on-fold lower`**: a move that would fold a region over itself is no longer only refused. The move is the gain times the move at gain 1, so the gain at which a region folds is known (2 · radius / (π · move at gain 1)); `lower` takes the largest gain under it, in steps of 0.01 and no more than `--gain`, one gain for the strip set by the region with the smallest radius, and names it on stderr. It never goes under 1, the mass as measured: a region too small for that is still refused, and the message names the largest gain that would not fold. The record says what was asked and what was used (`gain_requested`, `gain`, `on_fold`, and `fold`: lowered or not, the move asked for, the move at gain 1, per region the smaller radius, how near the used move is to folding it, and the gain at which it folds). The default stays `--on-fold refuse`: the same strip, GIF, WebP and refusal message as 2.24.0, byte for byte; the record only gains those keys. [docs/video-pipeline.md](docs/video-pipeline.md#6-follow-through--video-follow).
## v2.25.0 - Every view of an aligned walk starts as the same foot lands, read off the legs, and RIFE leaves no black between crossing legs
diff --git a/docs/loop-review.md b/docs/loop-review.md
index eb81518..cfc51e3 100644
--- a/docs/loop-review.md
+++ b/docs/loop-review.md
@@ -95,9 +95,11 @@ fallback below looks past the state's window, and only after this search found n
When the local search finds no cycle, `motion-auto` looks once more, for two things a
front or back gait does that the first search cannot see past. (Since 2.24.0 a clip that changes
-size by 1 % or more is held at its first frame's size before the first search —
-[video-pipeline.md](video-pipeline.md) section 4, `size_hold` — so the fallback below finds
-nothing left to scale back unless `--size-hold off` was passed.)
+size by 1 % or more, read one cycle on, is held at its first frame's size before the first
+search — [video-pipeline.md](video-pipeline.md) section 4, `size_hold` — so the fallback below
+seldom finds anything left to scale back unless `--size-hold off` was passed. It still reads the
+line through the clip, so a clip the hold left as filmed, whose line reads 3 % or more, is scaled
+back here if the first search found no cycle.)
- **It walked toward the camera, or away from it.** Asked to walk in place, a front walk
sometimes comes closer, and the body grows through the clip, so the same pose never matches
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 42d87f1..19f4abd 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -639,14 +639,32 @@ for the visual review contract and manual overrides.
A walk or run filmed from its first frame only (no end frame) often grows or shrinks as it plays:
a front walk comes a little closer with every step, a back walk goes away. The loop is then cut on
frames that change size, so the frame one cycle after the first is not the first's size and the
-loop pops at the wrap. A straight-line fit of the subject's opaque height over the clip measures
-it (`gait_fallback.scale_drift`); at 1 % or more (`SIZE_HOLD_MIN`) every frame is scaled back to
-the first frame's fitted height about its fitted foot point before the cycle search, so the
-search, the seam and the cells all read frames of one size. Below 1 % the fit is a head bob and
-hair and the frames are searched as filmed. The report says what was measured and done
-(`size_hold`: `drift`, `applied`, `padding_ltrb`). `--size-hold off` searches the frames as
-filmed, as before 2.24.0. Measured on one front catwalk filmed from its first frame (+2.0 % over
-3 s): the engine's seam ratio of the cut went from 1.44 to 1.19.
+loop pops at the wrap. The change is read one cycle on (`gait_fallback.cycle_drift`): the lag at
+which the pose, cut out about its feet, matches itself best (in the state's window, at most half
+the clip), and each frame's height (to a fraction of a pixel: the rows' coverage summed) against
+the frames one, two, … of those lags later. The median of those changes per frame, carried over
+the clip, is the `drift`. At 1 % or more (`SIZE_HOLD_MIN`) every frame is scaled back to the
+first frame's size about its fitted foot point before the cycle search, so the search, the seam
+and the cells all read frames of one size. Below 1 % the frames are searched as filmed.
+
+Why one cycle on, and not a line through the clip (2.24.0): a clip that starts from a standing
+pose and settles into the walk over its first steps (knees bending, the body leaning in) is a few
+pixels shorter from then on, and a line through every frame reads that one change of pose as a
+body that shrinks the whole way, and held it. The same pose a cycle later is the same size
+unless the body really changes, and the few frames of the first pose do not move a median of the
+rest. The other way round, a settle can
+pull the line flat over a walk that does grow; one cycle on, that growth is still read and held.
+On a synthetic walker that stands 6 px taller for its first frames and then walks at one size,
+the line read −2.2 % and the hold, so scaled, then found no cycle at all; one cycle on reads 0
+and the clip is cut as filmed (`tests/video/test_gait_fallback.py`).
+
+The report says what was measured and done (`size_hold`: `drift`, `applied`, `padding_ltrb`, and
+the evidence: `method: one-cycle-on`, `lag`, `pose_match` — the pose's mismatch at that lag over
+its mean across the window, 0 for an exact repeat — `pairs`, `per_lag`, the change over one lag,
+and `drift_fitted_line`, what a line through the clip would have read). `--size-hold off` searches
+the frames as filmed, as before 2.24.0. When the hold came in (2.24.0, read off the line) it was
+measured on one front catwalk filmed from its first frame (+2.0 % over 3 s): the engine's seam
+ratio of the cut went from 1.44 to 1.19.
**Nothing is cut when a frame is scaled up.** A clip that shrinks is scaled up about its feet,
and when the feet also rose in the frame (a back walk going away toward the horizon) the crown
diff --git a/sprite_gen/video/gait_fallback.py b/sprite_gen/video/gait_fallback.py
index baac865..156e78f 100644
--- a/sprite_gen/video/gait_fallback.py
+++ b/sprite_gen/video/gait_fallback.py
@@ -17,6 +17,14 @@ Only a failed search reaches the long window. The size is also held before the f
by `SIZE_HOLD_MIN` or more is scaled back first, so the loop is cut on frames of one size and its
last frame leads into its first. What was done is recorded in the report (`size_hold`,
`gait_fallback`).
+
+The hold reads the change one cycle on (`cycle_drift`), not off a line fitted through the
+clip: a clip that starts from a standing pose and settles into the walk over its first steps
+(knees bending, the body leaning in) is shorter from then on, and a line through every frame
+reads that one change of pose as a body that shrinks all the way. The same pose a cycle later
+is the same size unless the body really grows or shrinks, so the hold compares each frame's
+height with the frames whole pose-matched lags later and takes the middle of those changes; the
+few frames of the first pose do not move a median of the rest.
"""
from __future__ import annotations
@@ -72,6 +80,83 @@ def scale_drift(frames: list[Image.Image]) -> dict:
"height": height, "foot_x": foot_x, "foot_y": foot_y}
+POSE_EDGE = 48 # px: the pose thumbnail's longer side, the body cut out about its feet
+
+
+def _poses(frames: list[Image.Image], boxes: np.ndarray) -> np.ndarray:
+ """Per frame: the body's thumbnail, cut out about its own feet (the bottom middle of its box),
+ so a body that walks across the frame or bobs still matches itself a cycle later."""
+ known = ~np.isnan(boxes[:, 0])
+ width = int(np.ceil(np.max(boxes[known, 2] - boxes[known, 0]))) + 2
+ height = int(np.ceil(np.max(boxes[known, 3] - boxes[known, 1]))) + 2
+ scale = POSE_EDGE / max(width, height)
+ size = (max(1, round(width * scale)), max(1, round(height * scale)))
+ out = []
+ for frame, (x0, _, x1, y1) in zip(frames, boxes):
+ if np.isnan(x0):
+ out.append(np.full(size[0] * size[1] * 4, np.nan, np.float32))
+ continue
+ left, top = round((x0 + x1) / 2 - width / 2), round(y1 - height)
+ cut = frame.crop((left, top, left + width, top + height)).resize(size, Image.Resampling.BOX)
+ a = np.asarray(cut, np.float32) / 255
+ out.append(np.concatenate([a[..., :3] * a[..., 3:4], a[..., 3:4]], axis=-1).reshape(-1))
+ return np.stack(out)
+
+
+def coverage_heights(frames: list[Image.Image]) -> np.ndarray:
+ """Per frame: the subject's height to a fraction of a pixel, the rows' coverage summed (each
+ row counts as much as its most opaque pixel) from three rows over the solid crown to three
+ under the solid feet. A soft edge row adds its part, so a body 0.4 px taller reads 0.4 px
+ taller rather than 0 or 1. A frame with no solid row is NaN."""
+ out = []
+ for frame in frames:
+ rows = np.asarray(frame.getchannel("A"), np.float64).max(axis=1) / 255
+ solid = np.nonzero(rows >= ALPHA_SUBJECT / 255)[0]
+ out.append(float(rows[max(0, solid[0] - 3): solid[-1] + 4].sum()) if len(solid) else np.nan)
+ return np.asarray(out)
+
+
+def cycle_drift(frames: list[Image.Image], *, min_lag: int, max_lag: int) -> dict:
+ """The subject's change of size one cycle on, as `scale_drift` reports it.
+
+ The lag is the one in [min_lag, max_lag] (no more than half the clip, so every frame of the
+ first half has a partner) at which the pose matches itself best: the cycle, or one step of a
+ gait whose two halves look alike (the same size either way). Each frame's height
+ (`coverage_heights`) is compared with the frame one, two, … lags later, and the median of
+ those changes per frame is the rate, so a pose seen only at the start (a standing first frame)
+ is outvoted by the walk, and the longer spans keep a pixel's rounding from reading as a trend.
+ `drift` is that rate carried over the clip, on the same scale as the fitted line
+ (`drift_fitted_line`), and the heights `undo_scale` holds to grow by the same factor every
+ frame. No lag in range (a clip too short to show a cycle twice): `lag` is None and the drift 0."""
+ boxes = subject_boxes(frames)
+ n = len(frames)
+ heights = coverage_heights(frames)
+ fitted = scale_drift(frames)
+ hi = min(max_lag, n // 2)
+ base = {"method": "one-cycle-on", "drift_fitted_line": fitted["drift"],
+ "foot_x": fitted["foot_x"], "foot_y": fitted["foot_y"]}
+ if hi < max(1, min_lag) or np.isnan(heights).all():
+ return {**base, "lag": None, "pairs": 0, "per_lag": 1.0, "pose_match": None, "drift": 0.0,
+ "height_first_px": fitted["height_first_px"], "height_last_px": fitted["height_first_px"],
+ "height": np.full(n, fitted["height"][0])}
+ poses = _poses(frames, boxes)
+ profile = {lag: float(np.nanmean(np.abs(poses[lag:] - poses[:-lag]))) for lag in range(max(1, min_lag), hi + 1)}
+ lag = min(profile, key=lambda k: (profile[k], k))
+ rates = np.concatenate([np.log(heights[span:] / heights[:-span]) / span for span in range(lag, n, lag)])
+ rates = rates[np.isfinite(rates)]
+ rate = float(np.exp(np.median(rates)))
+ model = rate ** np.arange(n, dtype=np.float64)
+ level = float(np.nanmedian(heights / model))
+ height = level * model
+ # How well the pose matches itself at that lag, against the mean over the lags tried (0 is
+ # exact); None when no lag differs from another (a body that never moves).
+ mean = float(np.mean(list(profile.values())))
+ return {**base, "lag": lag, "pairs": int(len(rates)), "per_lag": round(rate ** lag, 4),
+ "pose_match": round(profile[lag] / mean, 3) if mean > 0 else None,
+ "drift": round(float(rate ** (n - 1) - 1), 4), "height_first_px": round(float(height[0]), 2),
+ "height_last_px": round(float(height[-1]), 2), "height": height}
+
+
def undo_padding(frames: list[Image.Image], measured: dict) -> tuple[int, int, int, int]:
"""Left, top, right, bottom room every frame needs so `undo_scale` cuts nothing.
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index dcdb6ec..db85215 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -903,9 +903,12 @@ def run_loop(
# frame one cycle on is not the size of the first and the loop pops at the wrap. Hold
# the clip at its first frame's size before the search (`size_hold`), so the cut is
# chosen on frames of one size. The gait fallback below then finds nothing to undo.
- measured = gait_fallback.scale_drift(source_frames)
+ # The change is read one cycle on, so a first pose that settles into the walk is
+ # not taken for a body that shrinks (gait_fallback.cycle_drift).
+ measured = gait_fallback.cycle_drift(source_frames, min_lag=lo, max_lag=hi)
hold: dict[str, Any] = {"applied": False, "min": gait_fallback.SIZE_HOLD_MIN,
- **{k: measured[k] for k in ("height_first_px", "height_last_px", "drift")}}
+ **{k: measured[k] for k in ("height_first_px", "height_last_px", "drift", "method",
+ "lag", "pairs", "per_lag", "pose_match", "drift_fitted_line")}}
if abs(measured["drift"]) >= gait_fallback.SIZE_HOLD_MIN:
pad = gait_fallback.undo_padding(source_frames, measured)
source_frames = gait_fallback.undo_scale(source_frames, measured, pad=pad)
@@ -1197,7 +1200,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--jolt-max", type=float, default=None, help=f"walk/run: fail the repaired loop when its jolt index (how far each step strays from its neighbours' mean, over the median step) exceeds this. Default: no gate — the index is reported and a value over {repair_mod.JOLT_REFERENCE} is a warning line")
parser.add_argument("--head-step-max", type=float, default=None, help=f"walk/run: fail the repaired loop when the head's largest sideways move in one frame exceeds this %% of the body height. Default: no gate — reported, and over {repair_mod.HEAD_STEP_REFERENCE} is a warning line")
parser.add_argument("--facing", choices=FACINGS, default="right", help="which way the body faces in the frames (default right): the hair the jump search watches is behind it")
- parser.add_argument("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="--anchor motion-auto: auto (default) scales a clip whose fitted height changes by 1 %% or more back to its first frame's size before the cycle search, so the loop's last frame is the size of its first (recorded as size_hold); off: search the frames as filmed")
+ parser.add_argument("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="--anchor motion-auto: auto (default) scales a clip whose height, read one cycle on (the same pose a cycle later), changes by 1 %% or more over the clip back to its first frame's size before the cycle search, so the loop's last frame is the size of its first (recorded as size_hold, with the evidence); off: search the frames as filmed")
parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")
parser.add_argument("--report", type=Path)
diff --git a/tests/video/test_gait_fallback.py b/tests/video/test_gait_fallback.py
index 14b97eb..589b4d2 100644
--- a/tests/video/test_gait_fallback.py
+++ b/tests/video/test_gait_fallback.py
@@ -45,6 +45,23 @@ def walker(k, *, period=24, grow=0.0, frames=73):
resample=Image.Resampling.BICUBIC).convert('RGBA')
+def settling(k, *, settle=10, rise=6, grow=0.0, frames=73):
+ """A walker that stands tall on straight legs in its first frame and settles into the walk: its
+ legs start `rise` px longer and ease to their walking length over `settle` frames. The body
+ above the hips does not move, and nothing changes size."""
+ image = walker(k, grow=grow, frames=frames)
+ lift = round(rise*0.5*(1+math.cos(math.pi*min(k, settle)/settle)), 2)
+ if lift <= 0:
+ return image
+ hips = FOOT[1]-41
+ legs = image.crop((0, hips, image.width, FOOT[1]))
+ out = image.copy()
+ out.paste((0, 0, 0, 0), (0, hips, image.width, image.height))
+ stretched = legs.convert('RGBa').resize((image.width, round((FOOT[1]-hips+lift)*SS)), Image.Resampling.BICUBIC)
+ out.alpha_composite(stretched.resize((image.width, FOOT[1]-hips+math.ceil(lift)), Image.Resampling.BOX).convert('RGBA'), (0, hips))
+ return out
+
+
def run(tmp_path, frames, *extra):
keyed = tmp_path/'keyed'
keyed.mkdir()
@@ -139,6 +156,52 @@ def test_a_clip_that_keeps_its_size_is_not_held(tmp_path):
assert 'padding_ltrb' not in report['size_hold']
+def test_the_size_is_read_one_cycle_on():
+ grows = gait_fallback.cycle_drift([walker(k, grow=0.025) for k in range(73)], min_lag=12, max_lag=36)
+ # The pose matches itself one cycle on; each height is compared with the frames one, two and
+ # three cycles later (49 + 25 + 1 pairs), and a cycle on it is 24/72 of the clip's growth more.
+ assert grows['method'] == 'one-cycle-on' and grows['lag'] == 24 and grows['pairs'] == 49+25+1
+ # (The drawn walker grows 2.5 %; a soft crown's coverage does not follow a sub-pixel move
+ # exactly, so its height reads a few tenths of a percent off either way.)
+ assert 1.007 < grows['per_lag'] < 1.011 and 0.021 < grows['drift'] < 0.032
+ assert abs(grows['drift']-grows['drift_fitted_line']) < 0.005
+ still = gait_fallback.cycle_drift([walker(k) for k in range(73)], min_lag=12, max_lag=36)
+ assert still['lag'] == 24 and still['per_lag'] == 1.0 and still['drift'] == 0.0
+ # A clip too short to show a cycle twice has nothing one cycle on to compare with.
+ short = gait_fallback.cycle_drift([walker(k, grow=0.2) for k in range(20)], min_lag=12, max_lag=36)
+ assert short['lag'] is None and short['drift'] == 0.0
+
+
+def test_a_first_pose_that_settles_into_the_walk_is_not_held(tmp_path):
+ # Stood tall, then walking: a line through every frame reads a body that shrinks; one cycle on,
+ # every pose is the size it was.
+ frames = [settling(k) for k in range(73)]
+ assert gait_fallback.scale_drift(frames)['drift'] <= -gait_fallback.SIZE_HOLD_MIN
+ code, report, output = run(tmp_path, frames)
+ assert code == 0
+ hold = report['size_hold']
+ assert hold['applied'] is False and abs(hold['drift']) < gait_fallback.SIZE_HOLD_MIN
+ assert hold['drift_fitted_line'] <= -gait_fallback.SIZE_HOLD_MIN and hold['lag'] == 24
+ (tmp_path/'off').mkdir()
+ code_off, _, output_off = run(tmp_path/'off', frames, '--size-hold', 'off')
+ assert code_off == 0
+ # Not held, the cut is the cut of the frames as filmed.
+ assert (output/'loop.strip.png').read_bytes() == (output_off/'loop.strip.png').read_bytes()
+
+
+def test_a_settle_does_not_hide_a_walk_that_grows(tmp_path):
+ # The settle pulls the fitted line down by as much as the walk grows: a line reads under 1 %.
+ frames = [settling(k, grow=0.025) for k in range(73)]
+ assert abs(gait_fallback.scale_drift(frames)['drift']) < gait_fallback.SIZE_HOLD_MIN
+ code, report, output = run(tmp_path, frames)
+ assert code == 0 and abs(report['cycle']['length']-24) <= 1
+ hold = report['size_hold']
+ assert hold['applied'] is True and 0.02 < hold['drift'] < 0.03
+ cells = sorted((output/'cycle').glob('frame-*.png'))
+ heights = gait_fallback.subject_boxes([Image.open(p).convert('RGBA') for p in cells])
+ assert np.ptp(heights[:, 3]-heights[:, 1]) <= 6
+
+
def walking_away(k, frames=73):
"""A walker going away from the camera: 15 % smaller by the end and its feet 20 px higher in the
frame (the ground recedes toward the horizon), its crown 10 px under the top at the start."""