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(size-hold): a walk or run cut by hand (--cycle fixed, any anchor) is held as a search's cut is, over the whole clip, before the cut is read — its distances, its step count and the seam the gate reads are the frames held, --anchor motion regions are laid where their parts are held (size_hold.anchor_regions), --size-hold off records why; and the hold holds the feet: where they climb or sink 1 % of the height or more over the clip, read one cycle on (gait_fallback.foot_drift, FOOT_HOLD_MIN), every frame is moved so they stand on the first frame's row (undo_padding/undo_scale lift, held_box), for motion-auto too (size_hold.feet); the gait fallback still holds the size alone, so --size-hold off keeps its bytes

Soohong Kimb7ee538c2349
diff --git a/sprite_gen/video/gait_fallback.py b/sprite_gen/video/gait_fallback.py
index 1b7154c..dad81ec 100644
--- a/sprite_gen/video/gait_fallback.py
+++ b/sprite_gen/video/gait_fallback.py
@@ -13,10 +13,13 @@ Two things a front or back gait does that the first search cannot see past:
`LONG_CYCLE_FRACTION` of the clip: it is still seen once whole and repeating for the rest.
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`).
+(`video-loop --size-hold auto`, the default for `--anchor motion-auto` and for a fixed cut of a walk
+or run, before the cut is read): 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. The hold
+holds the feet too where they climb or sink in the frame (`foot_drift`): a walk away from the camera
+shrinks as the ground recedes up the frame, and held at its size about feet left where they were
+filmed its last frame stands higher than 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
@@ -61,6 +64,11 @@ SCALE_DRIFT_MIN = 0.03
# 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
+# How far the feet climb or sink in the frame over the clip, read one cycle on (`foot_drift`), as a share of the
+# first frame's height, at which a clip the size hold holds has its feet held on the first frame's row as well.
+# Under it the feet's row is the box's rounding; a walk away from the camera whose ground recedes up the frame
+# climbs by several percent of the body.
+FOOT_HOLD_MIN = 0.01
# How far off the one-cycle-on model a frame is when it is not yet walking at the clip's size: a first frame
# whose height and size are both this far off, the same way, opens a lead-in, and the frames whose height
# stays this far off, that way, are in it (`lead_in`).
@@ -189,6 +197,36 @@ def cycle_drift(frames: list[Image.Image], *, min_lag: int, max_lag: int) -> dic
"height_last_px": round(float(height[-1]), 2), "height": height}
+def foot_drift(frames: list[Image.Image], measured: dict) -> dict:
+ """How far the subject's feet climb (negative) or sink in the frame over the clip, read one cycle on, and how far
+ each frame's feet are moved to stand on the first frame's row when the size is held (`lift`, for `undo_padding`
+ and `undo_scale`).
+
+ A walk away from the camera shrinks and its feet climb the frame: the ground recedes toward the horizon. Held at
+ its first frame's size about feet that stay where they were filmed, the loop's last frame stands higher than its
+ first and the wrap jumps up. The motion anchor's fine search does not reach that jump once the feet climb further
+ over the cut than it looks (`motion_anchor.SEARCH_RADIUS`, rows), and the body anchor moves the frames sideways
+ only. The bottom of each frame's subject is compared with the frame one, two, … lags later (`measured["lag"]`,
+ `cycle_drift`'s: the pose a cycle on), and the median of those changes per frame is the rate, as for the size: a
+ first pose that stands on longer legs and settles into the walk is outvoted, where a line through every bottom
+ reads it as feet that climb. `change_px` is that rate carried over the clip. `lift` is each frame's move back to
+ the first frame's row, None where the change is under FOOT_HOLD_MIN of the first frame's height (the feet stay
+ where they were filmed) or the clip is too short to read a cycle on."""
+ n = len(frames)
+ base = {"min": FOOT_HOLD_MIN, "method": "one-cycle-on"}
+ lag = measured["lag"]
+ if lag is None:
+ return {**base, "change_px": 0.0, "held": False, "lift": None}
+ bottoms = subject_boxes(frames)[:, 3]
+ rates = np.concatenate([(bottoms[span:] - bottoms[:-span]) / span for span in range(lag, n, lag)])
+ rates = rates[np.isfinite(rates)]
+ rate = float(np.median(rates)) if len(rates) else 0.0
+ change = rate * (n - 1)
+ held = abs(change) >= FOOT_HOLD_MIN * float(measured["height"][0])
+ return {**base, "change_px": round(change, 2), "held": held,
+ "lift": -rate * np.arange(n, dtype=np.float64) if held else None}
+
+
def lead_in(frames: list[Image.Image], *, min_lag: int, max_lag: int) -> dict:
"""The frames the clip opens on before its subject walks at the clip's size. There are some when the
first frame's height (`coverage_heights`) and size (the square root of its summed coverage) are
@@ -258,13 +296,13 @@ def size_change(first: tuple[float, float, float] | None, cut: list[tuple[float,
"breadth": round(float(off[2]), 4), **base}
-def undo_padding(frames: list[Image.Image], measured: dict) -> tuple[int, int, int, int]:
+def undo_padding(frames: list[Image.Image], measured: dict, lift: np.ndarray | None = None) -> 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)."""
+ `undo_scale` maps it (with the same `lift`); 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
@@ -274,16 +312,21 @@ def undo_padding(frames: list[Image.Image], measured: dict) -> tuple[int, int, i
continue
s = float(height[0] / height[k])
ax, ay = float(foot_x[k]), float(foot_y[k])
+ # Where the feet stand once held: where they were filmed, or `lift` lower on the first frame's row.
+ ty = ay if lift is None else ay + float(lift[k])
reach[0] = max(reach[0], -(ax + (x0 - ax) * s))
- reach[1] = max(reach[1], -(ay + (y0 - ay) * s))
+ reach[1] = max(reach[1], -(ty + (y0 - ay) * s))
reach[2] = max(reach[2], ax + (x1 - ax) * s - width)
- reach[3] = max(reach[3], ay + (y1 - ay) * s - rows)
+ reach[3] = max(reach[3], ty + (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.
+def undo_scale(frames: list[Image.Image], measured: dict, pad: tuple[int, int, int, int] | None = None,
+ lift: np.ndarray | None = None) -> list[Image.Image]:
+ """Each frame scaled to the first frame's fitted height about its fitted foot point, and moved
+ `lift[k]` px down (up, negative) where it is given (`foot_drift`), so the feet stand on the first
+ frame's row; without it they stay where they were filmed.
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:
@@ -294,18 +337,35 @@ def undo_scale(frames: list[Image.Image], measured: dict, pad: tuple[int, int, i
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
+ left, top, right, bottom = undo_padding(frames, measured, lift) 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 - room - anchor) / s.
- inverse = (1 / s, 0.0, ax * (1 - 1 / s) - left / s, 0.0, 1 / s, ay * (1 - 1 / s) - top / s)
+ # Output (x, y) reads input anchor + (x - room - anchor) / s; held, y - room - anchor - lift.
+ ry = ay * (1 - 1 / s) - top / s
+ if lift is not None:
+ ry -= float(lift[k]) / s
+ inverse = (1 / s, 0.0, ax * (1 - 1 / s) - left / s, 0.0, 1 / s, ry)
size = (frame.width + left + right, frame.height + top + bottom)
out.append(transform_cell(frame, size, inverse))
return out
+def held_box(box: tuple[int, int, int, int], k: int, measured: dict, pad: tuple[int, int, int, int],
+ lift: np.ndarray | None = None) -> tuple[int, int, int, int]:
+ """Where `undo_scale` lays a box of frame `k` as filmed (x0, y0, x1, y1), in whole pixels that cover it: a region
+ named on the frames as filmed, read on the held ones."""
+ height, foot_x, foot_y = measured["height"], measured["foot_x"], measured["foot_y"]
+ left, top = pad[0], pad[1]
+ s = float(height[0] / height[k])
+ ax, ay = float(foot_x[k]), float(foot_y[k])
+ ty = ay if lift is None else ay + float(lift[k])
+ x0, y0, x1, y1 = box
+ return (int(np.floor(left + ax + (x0 - ax) * s)), int(np.floor(top + ty + (y0 - ay) * s)),
+ int(np.ceil(left + ax + (x1 - ax) * s)), int(np.ceil(top + ty + (y1 - ay) * s)))
+
+
def long_window(lo: int, n: int, fps: float) -> int:
"""The second search's ceiling in frames."""
return max(lo + 2, min(round(LONG_CYCLE_SECONDS * fps), int(n * LONG_CYCLE_FRACTION)))
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 27c9a14..fe33f92 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -1641,6 +1641,31 @@ def _blend_wrap(frames: list[Image.Image], pin_file: Path, *, mode: str, anchor:
return wrap_blend_mod.apply(frames, pin, fps=fps, seam_max=seam_max)
+def _size_hold(frames: list[Image.Image], *, lo: int, hi: int) -> tuple[list[Image.Image] | None, dict[str, Any], Any]:
+ """A walk or run held at its first frame's size, and its feet on the first frame's row, before its cut is chosen
+ (`--size-hold auto`): the frames held (None: the clip changes size by less than SIZE_HOLD_MIN, read one cycle on,
+ and is cut as filmed), the report's `size_hold`, and where a box of a frame as filmed lands in its held frame
+ (`gait_fallback.held_box`, None when not held).
+
+ A clip 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; a walk away from the camera climbs the frame as well, and held at its size
+ with its feet where they were filmed it pops up instead. The change is read one cycle on, so a first pose that
+ settles into the walk is not taken for a body that shrinks, nor for feet that climb (gait_fallback.cycle_drift,
+ foot_drift)."""
+ measured = gait_fallback.cycle_drift(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", "method",
+ "lag", "pairs", "per_lag", "pose_match", "drift_fitted_line")}}
+ if abs(measured["drift"]) < gait_fallback.SIZE_HOLD_MIN:
+ return None, hold, None
+ feet = gait_fallback.foot_drift(frames, measured)
+ lift = feet.pop("lift")
+ pad = gait_fallback.undo_padding(frames, measured, lift)
+ held = gait_fallback.undo_scale(frames, measured, pad=pad, lift=lift)
+ hold.update(applied=True, padding_ltrb=list(pad), feet=feet)
+ return held, hold, partial(gait_fallback.held_box, measured=measured, pad=pad, lift=lift)
+
+
class _Scratch:
"""The folders a run writes the frames a size hold or the gait fallback scaled back into: each a new one of the
run's own in the out dir (`runio.new_stage`: `.gait-fallback-frames.<pid>-<random>`), so a folder already there —
@@ -1817,22 +1842,12 @@ def _cut_loop(
if anchor == "motion-auto":
source_frames = gait_frames[skip:]
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.
- # 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", "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)
- files = gait_fallback.write_frames(source_frames, [f.name for f in files], scratch.new())
- hold.update(applied=True, padding_ltrb=list(pad))
- report_base["size_hold"] = hold
+ # Held before the search (`_size_hold`), the cut is chosen on frames of one size whose feet stand on one
+ # row. The gait fallback below then finds nothing to undo.
+ held, report_base["size_hold"], _ = _size_hold(source_frames, lo=lo, hi=hi)
+ if held is not None:
+ source_frames = held
+ files = gait_fallback.write_frames(held, [f.name for f in files], scratch.new())
else:
report_base["size_hold"] = {"applied": False, "why": "--size-hold off"}
D, trajectory, analysis = auto_motion.analyse(source_frames, fps=fps)
@@ -1897,6 +1912,23 @@ def _cut_loop(
if start is None or length is None:
raise SystemExit("video-loop: --cycle fixed needs --start and --length")
cycle = fixed_cycle(D, start=start, length=length)
+ if gait_frames is not None and size_hold == "auto":
+ # A walk or run cut the caller names is held as a search's cut is (`_size_hold`), read over the whole clip,
+ # and cut on the frames held: the cut's distances, its count and the seam the gate reads are the frames
+ # that play. The clip is then the clip held (a fixed cut leaves no lead-in out).
+ held, report_base["size_hold"], box_of = _size_hold(gait_frames, lo=lo, hi=hi)
+ if held is not None:
+ gait_frames = held
+ files = gait_fallback.write_frames(held, [f.name for f in files], scratch.new())
+ D = distance_matrix(files)
+ clip_files, clip_D = files, D
+ cycle = fixed_cycle(D, start=start, length=length)
+ if anchor_regions is not None:
+ # `--anchor-region` names the cut's first frame as filmed: the same parts of it, held.
+ anchor_regions = [box_of(tuple(box), start) for box in anchor_regions]
+ report_base["size_hold"]["anchor_regions"] = [list(box) for box in anchor_regions]
+ elif gait_frames is not None:
+ report_base["size_hold"] = {"applied": False, "why": "--size-hold off"}
if gait_frames is not None:
# A walk or run loops on two steps: the clip's own count of the cut the caller named, as a search's cut is
# counted. An odd count swaps the legs at the wrap, however close the frames there look.
@@ -2429,7 +2461,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 jolt index's hair, and the size reading video-loop-compare's jump guard reads, are behind it; the jump repair reads the flow either way")
- 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("--size-hold", choices=SIZE_HOLD_MODES, default="auto", help="walk/run, --anchor motion-auto or --cycle fixed: 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 about its feet, and moves its feet back to the first frame's row where they climb or sink by 1 %% of its height or more (a walk away from the camera), before the cycle search or, for a fixed cut, before the cut is read — read over the whole clip — so the loop's last frame is the size of its first and stands where it stands (recorded as size_hold, with the evidence; a cut held is not restored from its source frames); off: the frames as filmed, but for motion-auto's gait fallback, which after a first search that finds nothing still scales back a change of 3 %% or more, by the same reading, its feet where they were filmed (recorded as gait_fallback)")
parser.add_argument("--steps", type=int, choices=STEPS, default=None,
help="--anchor motion-auto: how many steps the cut it takes without this holds, as counted by whoever looked "
"at the loop (how often each foot lands) — the report's `cycle.step_screen` names a cut that may be one "