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): a walk is held at its first frame's size before the cycle search, and scaling a frame back up widens it instead of cutting the crown

Soohong Kim0ebcfacd0431
diff --git a/sprite_gen/video/gait_fallback.py b/sprite_gen/video/gait_fallback.py
index febbe28..baac865 100644
--- a/sprite_gen/video/gait_fallback.py
+++ b/sprite_gen/video/gait_fallback.py
@@ -12,8 +12,11 @@ Two things a front or back gait does that the first search cannot see past:
the most the first search confirms. The second search allows a cycle up to
`LONG_CYCLE_FRACTION` of the clip: it is still seen once whole and repeating for the rest.
-Only a failed search reaches this, so a clip that loops today is cut exactly as before. What
-was done is recorded in the report (`gait_fallback`).
+Only a failed search reaches the long window. The size is also held before the first search
+(`video-loop --size-hold auto`, the default for `--anchor motion-auto`): a clip that changes size
+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`).
"""
from __future__ import annotations
@@ -27,6 +30,11 @@ 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.
SCALE_DRIFT_MIN = 0.03
+# Height change over the clip at which a walk or run is held at its first frame's size before the
+# first cycle search (`video-loop --size-hold auto`). Below it the fitted trend is a head bob and
+# hair; above it a clip filmed from its first frame only grows or shrinks enough that the loop's
+# last frame is a different size from its first, and the loop pops at the wrap.
+SIZE_HOLD_MIN = 0.01
# The longest cycle the second search accepts, as a share of the clip and in seconds.
LONG_CYCLE_FRACTION = 0.6
LONG_CYCLE_SECONDS = 2.0
@@ -64,21 +72,51 @@ def scale_drift(frames: list[Image.Image]) -> dict:
"height": height, "foot_x": foot_x, "foot_y": foot_y}
-def undo_scale(frames: list[Image.Image], measured: dict) -> list[Image.Image]:
+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.
+
+ A clip that shrinks is scaled up about its feet, and what was near the top of the frame (the
+ crown) or its sides is carried past the edge. Each frame's subject box is mapped the way
+ `undo_scale` maps it; the room is how far the furthest one reaches past each edge. All
+ frames get the same room, so they stay one size. Nothing reaches out: (0, 0, 0, 0)."""
+ boxes = subject_boxes(frames)
+ height, foot_x, foot_y = measured["height"], measured["foot_x"], measured["foot_y"]
+ width, rows = frames[0].size
+ reach = [0.0, 0.0, 0.0, 0.0]
+ for k, (x0, y0, x1, y1) in enumerate(boxes):
+ if np.isnan(x0):
+ continue
+ s = float(height[0] / height[k])
+ ax, ay = float(foot_x[k]), float(foot_y[k])
+ reach[0] = max(reach[0], -(ax + (x0 - ax) * s))
+ reach[1] = max(reach[1], -(ay + (y0 - ay) * s))
+ reach[2] = max(reach[2], ax + (x1 - ax) * s - width)
+ reach[3] = max(reach[3], ay + (y1 - ay) * s - rows)
+ # A pixel's bilinear footprint reaches one past its mapped edge.
+ return tuple(int(np.ceil(r)) + 1 if r > 0 else 0 for r in reach) # type: ignore[return-value]
+
+
+def undo_scale(frames: list[Image.Image], measured: dict, pad: tuple[int, int, int, int] | None = None) -> list[Image.Image]:
"""Each frame scaled to the first frame's fitted height about its fitted foot point.
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.
+
+ The frames are widened by `pad` (left, top, right, bottom; `undo_padding` when not given), so
+ a part scaled up past the frame's edge is kept. A crown carried above the frame was cut off
+ in every frame it reached. With no room needed the frames keep their size and bytes.
"""
height, foot_x, foot_y = measured["height"], measured["foot_x"], measured["foot_y"]
+ left, top, right, bottom = undo_padding(frames, measured) if pad is None else pad
out = []
for k, frame in enumerate(frames):
s = float(height[0] / height[k])
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))
- out.append(transform_cell(frame, frame.size, inverse))
+ # Output (x, y) reads input anchor + (x - room - anchor) / s.
+ inverse = (1 / s, 0.0, ax * (1 - 1 / s) - left / s, 0.0, 1 / s, ay * (1 - 1 / s) - top / s)
+ size = (frame.width + left + right, frame.height + top + bottom)
+ out.append(transform_cell(frame, size, inverse))
return out
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 3bc409b..dcdb6ec 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -90,11 +90,15 @@ FOOT_BAND = 0.08 # fraction of the frame's own height, measured up from its low
# no RIFE fails the loop — a caller that asked for the repair is never handed less; off: the loop
# is cut as filmed, and says so.
REPAIR_MODES = ("auto", "on", "off")
+SIZE_HOLD_MODES = ("auto", "off")
FACINGS = ("right", "left")
# Where `video-cycle-align` keeps the cut as filmed (sprite_gen/video/align.py). A new cut makes
# the kept one stale, so writing the cycle removes it: an alignment after a re-cut (say, once RIFE
# is installed and the jumps are repaired) reads the new cut, not the old one.
CYCLE_SOURCE_DIR = "cycle.source"
+# The strip as it was before `video-follow` moved a region of it; a later follow-through reads
+# from it, and a new cut or alignment removes it (docs/video-pipeline.md section 6).
+FOLLOW_SOURCE = "follow.source.png"
# A gait's period is a fact about the body, not about how long the clip runs: the
@@ -847,7 +851,10 @@ def run_loop(
interpolate: rife_mod.Interpolate | None = None,
jolt_max: float | None = None,
head_step_max: float | None = None,
+ size_hold: str = "auto",
) -> dict[str, Any]:
+ if size_hold not in SIZE_HOLD_MODES:
+ raise SystemExit(f"video-loop: unknown --size-hold {size_hold!r}; expected one of {', '.join(SIZE_HOLD_MODES)}")
if repair not in REPAIR_MODES:
raise SystemExit(f"video-loop: unknown --repair {repair!r}; expected one of {', '.join(REPAIR_MODES)}")
if facing not in FACINGS:
@@ -891,6 +898,22 @@ def run_loop(
try:
if anchor == "motion-auto":
source_frames = [Image.open(f).convert("RGBA") for f in files]
+ if size_hold == "auto":
+ # A walk or run filmed from its first frame only grows or shrinks as it plays, so the
+ # 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)
+ 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")}}
+ 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)
+ files = gait_fallback.write_frames(source_frames, [f.name for f in files], out_dir.expanduser().resolve() / FALLBACK_FRAMES_DIR)
+ hold.update(applied=True, padding_ltrb=list(pad))
+ report_base["size_hold"] = hold
+ else:
+ report_base["size_hold"] = {"applied": False, "why": "--size-hold off"}
D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)
report_base["automatic_motion_analysis"] = analysis
detect = dict(gait_floor=round(prof.min_seconds*fps), periodicity_min=PERIODICITY_MIN,
@@ -904,7 +927,8 @@ def run_loop(
fallback = {"reason": str(first), "scale_drift": {k: drift[k] for k in ("height_first_px", "height_last_px", "drift")},
"scale_drift_min": gait_fallback.SCALE_DRIFT_MIN, "scale_undone": False}
if abs(drift["drift"]) >= gait_fallback.SCALE_DRIFT_MIN:
- source_frames = gait_fallback.undo_scale(source_frames, drift)
+ fallback["padding_ltrb"] = list(gait_fallback.undo_padding(source_frames, drift))
+ source_frames = gait_fallback.undo_scale(source_frames, drift, pad=tuple(fallback["padding_ltrb"]))
files = gait_fallback.write_frames(source_frames, [f.name for f in files], out_dir.expanduser().resolve() / FALLBACK_FRAMES_DIR)
D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)
report_base["automatic_motion_analysis"] = analysis
@@ -1045,6 +1069,8 @@ def run_loop(
for old in cycle_dir.glob("frame-*.png"):
old.unlink()
shutil.rmtree(out_dir / CYCLE_SOURCE_DIR, ignore_errors=True)
+ # A new cut makes a follow-through over the old strip stale (`video-follow` reads this source).
+ (out_dir / FOLLOW_SOURCE).unlink(missing_ok=True)
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"),
@@ -1171,6 +1197,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("--name", default="loop", help="basename for strip/gif/webp outputs")
parser.add_argument("--report", type=Path)
@@ -1188,6 +1215,7 @@ def run(**kwargs: object) -> int:
anchor_regions=kwargs.get("anchor_region"),
repair=str(kwargs.get("repair") or "auto"), facing=str(kwargs.get("facing") or "right"),
jolt_max=kwargs.get("jolt_max"), head_step_max=kwargs.get("head_step_max"), # type: ignore[arg-type]
+ size_hold=str(kwargs.get("size_hold") or "auto"),
)
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/tests/video/test_gait_fallback.py b/tests/video/test_gait_fallback.py
index 7f52974..14b97eb 100644
--- a/tests/video/test_gait_fallback.py
+++ b/tests/video/test_gait_fallback.py
@@ -101,10 +101,100 @@ def test_an_explicit_max_len_stays_the_ceiling(tmp_path):
assert report['gait_fallback']['window'] == [12, 36]
-def test_a_walk_toward_the_camera_is_scaled_back_before_the_second_search(tmp_path):
+def test_a_walk_toward_the_camera_is_held_at_its_size_before_the_first_search(tmp_path):
+ frames = [walker(k, grow=0.2) for k in range(73)]
+ code, report, output = run(tmp_path, frames)
+ assert code == 0
+ assert abs(report['cycle']['length']-24) <= 1
+ hold = report['size_hold']
+ assert hold['applied'] is True and hold['drift'] > gait_fallback.SIZE_HOLD_MIN
+ # Held first, the first search cuts it: the fallback never runs.
+ assert 'gait_fallback' not in report
+ 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
+ assert not (output/loop.FALLBACK_FRAMES_DIR).exists()
+
+
+def test_a_small_change_of_size_is_held_too(tmp_path):
+ # Under the fallback's 3 %, over the hold's 1 %: held, the walker loops at its size; searched as
+ # filmed, the growing walker never matches itself and the fallback does not scale it back.
+ frames = [walker(k, grow=0.025) for k in range(73)]
+ code, report, output = run(tmp_path, frames)
+ assert code == 0 and report['size_hold']['applied'] is True
+ assert abs(report['cycle']['length']-24) <= 1
+ (tmp_path/'off').mkdir()
+ code_off, report_off, _ = run(tmp_path/'off', frames, '--size-hold', 'off')
+ assert str(code_off).startswith('video-loop: no periodic cycle found')
+ assert report_off['size_hold'] == {'applied': False, 'why': '--size-hold off'}
+ fallback = report_off['gait_fallback']
+ assert fallback['scale_undone'] is False and fallback['scale_drift']['drift'] < gait_fallback.SCALE_DRIFT_MIN
+
+
+def test_a_clip_that_keeps_its_size_is_not_held(tmp_path):
+ code, report, output = run(tmp_path, [walker(k) for k in range(73)])
+ assert code == 0
+ assert report['size_hold']['applied'] is False
+ assert abs(report['size_hold']['drift']) < gait_fallback.SIZE_HOLD_MIN
+ assert 'padding_ltrb' not in report['size_hold']
+
+
+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."""
+ image = walker(k, grow=-0.15, frames=frames)
+ rows = 40 + round(20*k/(frames-1))
+ out = Image.new('RGBA', image.size)
+ out.alpha_composite(image.crop((0, rows, image.width, image.height)), (0, 0))
+ return out
+
+
+def test_scaling_back_up_keeps_a_crown_carried_past_the_top():
+ # Scaled back up about feet that have risen, the late frames' crown lands above the frame.
+ # Widened first, nothing is cut.
+ frames = [walking_away(k) for k in range(73)]
+ measured = gait_fallback.scale_drift(frames)
+ pad = gait_fallback.undo_padding(frames, measured)
+ assert pad[1] > 0
+ kept = gait_fallback.subject_boxes(gait_fallback.undo_scale(frames, measured))
+ cut = gait_fallback.subject_boxes(gait_fallback.undo_scale(frames, measured, pad=(0, 0, 0, 0)))
+ first = frames[0].getchannel('A').getbbox()
+ first_height = first[3]-first[1]
+ # Widened, the last frame stands as tall as the first; not widened, its crown is gone.
+ assert abs((kept[-1, 3]-kept[-1, 1])-first_height) <= 2
+ assert (cut[-1, 3]-cut[-1, 1]) < first_height-8
+ assert cut[-1, 1] == 0
+ # The first frame is the reference: only moved into the wider frame, not resampled.
+ left, top, right, bottom = pad
+ widened = Image.new('RGBA', (frames[0].width+left+right, frames[0].height+top+bottom))
+ widened.paste(frames[0], (left, top))
+ assert gait_fallback.undo_scale(frames, measured)[0].tobytes() == widened.tobytes()
+
+
+def test_no_room_is_added_when_nothing_reaches_out():
frames = [walker(k, grow=0.2) for k in range(73)]
+ measured = gait_fallback.scale_drift(frames)
+ assert gait_fallback.undo_padding(frames, measured) == (0, 0, 0, 0)
+ undone = gait_fallback.undo_scale(frames, measured)
+ assert all(f.size == frames[0].size for f in undone)
+
+
+def test_the_held_loop_of_a_shrinking_walk_keeps_its_crown(tmp_path):
+ frames = [walking_away(k) for k in range(73)]
code, report, output = run(tmp_path, frames)
assert code == 0
+ assert report['size_hold']['applied'] is True and report['size_hold']['padding_ltrb'][1] > 0
+ first = frames[0].getchannel('A').getbbox()
+ cells = sorted((output/'cycle').glob('frame-*.png'))
+ boxes = gait_fallback.subject_boxes([Image.open(p).convert('RGBA') for p in cells])
+ # Every cell stands about as tall as the first frame did: no cell lost its crown.
+ assert np.all(np.abs((boxes[:, 3]-boxes[:, 1])-(first[3]-first[1])) <= 6)
+
+
+def test_a_walk_toward_the_camera_is_scaled_back_before_the_second_search(tmp_path):
+ frames = [walker(k, grow=0.2) for k in range(73)]
+ code, report, output = run(tmp_path, frames, '--size-hold', 'off')
+ assert code == 0
assert abs(report['cycle']['length']-24) <= 1
fallback = report['gait_fallback']
assert fallback['scale_undone'] is True
diff --git a/tests/video/test_gait_fallback_resample.py b/tests/video/test_gait_fallback_resample.py
index d358586..20458e8 100644
--- a/tests/video/test_gait_fallback_resample.py
+++ b/tests/video/test_gait_fallback_resample.py
@@ -22,7 +22,9 @@ 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)
+ # No room added: the colour is the subject here (the room for a part scaled past the edge is
+ # tested in test_gait_fallback.py).
+ first, second = gait_fallback.undo_scale([src, src], measured, pad=(0, 0, 0, 0))
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