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(video): a made frame that cross-fades two drawings inside its silhouette is measured and named, kept

Soohong Kim802040049886
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.py
index d62a618..e3c9a1c 100644
--- a/sprite_gen/video/align.py
+++ b/sprite_gen/video/align.py
@@ -8,7 +8,8 @@ resampled to the set's median length L*: frame k of the new loop is the source l
k·L/L* (cyclic, offset 0), so a time that lands on a source frame takes that frame as filmed
and only the times between two frames are made by RIFE — each kept unless it smeared, lost its
outline or carries a ghost, where the nearer source frame is taken instead (`--between auto`, the
-default; `rife` keeps every made frame and warns, `nearest` makes none). Every frame delivered,
+default; `rife` keeps every made frame and warns, `nearest` makes none); a made frame kept that
+cross-fades two drawings inside its silhouette is named to look at. Every frame delivered,
filmed or made, passes the ghost screen (`interpolation_quality.ghost_screen`): a filmed frame half
drawn between two drawings gives way to a clean source frame beside it, named in `ghost_at`. Then
each loop is turned to start as a heel lands — read off the stride, the lowest row or the body's
@@ -93,7 +94,7 @@ from sprite_gen.video import legs as legs_mod
from sprite_gen.video import loop as loop_mod
from sprite_gen.video import period as period_mod
from sprite_gen.video import rife as rife_mod
-from sprite_gen.video.interpolation_quality import SMEAR_WARN, OUTLINE_WARN, faults, ghost_screen
+from sprite_gen.video.interpolation_quality import CROSSFADE_LOOK, SMEAR_WARN, OUTLINE_WARN, faults, ghost_screen, looks
SNAP = 0.03 # a sample time within this of a source frame takes that frame
SOURCE_DIR = loop_mod.CYCLE_SOURCE_DIR # removed by video-loop whenever it cuts the loop again
@@ -198,7 +199,9 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Inter
auto keeps a made frame with no fault and takes the nearer source frame where it has one, rife
keeps every made frame, nearest makes none and takes the nearer source frame (the motion keeps the
filmed frames at up to half a frame off their time). Every made frame is listed in `smear` with
- its `method`: rife (kept) or nearest (a source frame beside it taken instead).
+ its `method`: rife (kept) or nearest (a source frame beside it taken instead), and its `crossfade`
+ (`rife.crossfade`: two drawings cross-faded inside its silhouette) with what to `look` at — named,
+ never a reason to give it way.
Every frame delivered passes the ghost screen (`ghost_screen`, the source loop's, recorded as it is):
a source frame it names is not taken under auto or nearest — at a time on it, the frame after it is,
@@ -244,12 +247,13 @@ def resample(frames: list[Image.Image], length: int, interpolate: rife_mod.Inter
raise ValueError(f"frame {k} of {length} falls between source frames and no interpolator is available")
a, b = frames[i % count], frames[(i + 1) % count]
made = interpolate(a, b, frac)
- measure = {**rife_mod.smear(made, a, b), "ghost": rife_mod.ghost(made) if screen["reads"] else None}
+ measure = {**rife_mod.smear(made, a, b), "ghost": rife_mod.ghost(made) if screen["reads"] else None,
+ "crossfade": rife_mod.crossfade(made, a, b, frac)}
wrong = faults(measure)
keep = between == "rife" or not wrong
taken = {"between": [i % count, (i + 1) % count], "t": round(frac, 4)} if keep else {"source": clean(k, nearer, beside)}
(made_at if keep else nearest_at).append(k)
- smears.append({"at": k, "method": "rife" if keep else "nearest", **measure, "faults": wrong})
+ smears.append({"at": k, "method": "rife" if keep else "nearest", **measure, "faults": wrong, "look": looks(measure)})
out.append(made if "between" in taken else frames[taken["source"]])
if cells_from is not None:
cells_from.append(taken)
@@ -705,6 +709,14 @@ def _fault_line(name: str, m: dict[str, Any], *, other_side: bool = False) -> st
+ "; see it in cycle/, or align with --between auto (the nearer source frame there) or --between nearest")
+def _look_line(name: str, m: dict[str, Any]) -> str:
+ """A made frame kept that cross-fades two drawings inside its silhouette, in words."""
+ return (f"{name}: frame {m['at']} (made by RIFE) may cross-fade two drawings inside its outline — where the source frames "
+ f"beside it differ it shows their blend and lost their strong edges (crossfade {m['crossfade']:.4f}, over {CROSSFADE_LOOK}); "
+ "kept, a reading to look at and not a fault — see it in cycle/, and where the legs show twice, align with "
+ "--between nearest or film the direction again (docs/loop-repair.md section 4)")
+
+
def _ghost_line(name: str, g: dict[str, Any], between: str) -> str:
"""A cell where a filmed ghost frame would have been delivered, and what was instead."""
line = f"{name}: frame {g['at']}: source frame {g['source']} is a filmed ghost ({_ghost_words(g['ghost'])})"
@@ -883,10 +895,14 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:
"strip": {k: merged[k] for k in ("frames", "w", "h", "body_h", "delay_ms")}})
warnings = [_fault_line(r["name"], m, other_side=any(g["at"] == m["at"] and g["taken"] != g["source"] for g in r["ghost_at"]))
for r in rows for m in r.get("smear", []) if m["faults"]]
+ warnings += [_look_line(r["name"], m) for r in rows for m in r.get("smear", []) if m["method"] == "rife" and m["look"]]
retakes = [{"dir": r["dir"], "name": r["name"], **r["retake"]} for r in rows if r["retake"]]
# A loop to film again is named by its directory where two loops share a strip name (each `walk`).
shared = len({r["name"] for r in rows}) < len(rows)
warnings += [_ghost_line(r["dir"] if shared else r["name"], g, between) for r in rows for g in r["ghost_at"]]
+ warnings += [f"{r['dir'] if shared else r['name']}: the ghost screen does not read it — {r['ghost_screen']['why']}; no frame of it "
+ "is named a ghost or given way for one, so look at cycle/ (docs/loop-repair.md section 4)"
+ for r in rows if not r["ghost_screen"]["reads"]]
warnings = cycle_warnings + [_retake_line(r["dir"] if shared else r["name"], r["retake"]) for r in rows if r["retake"]] + warnings
unnamed = [_unnamed_foot(r) for r in rows if r["start_foot"] is None]
if len(rows) > 1 and views is None and unnamed:
@@ -942,7 +958,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
"taken and named in the warnings; rife keeps every made frame and warns on those; nearest takes the nearer "
"source frame — nothing made, no RIFE needed, the motion up to half a frame off its time. Every made frame is "
"measured in the report (`smear`); under auto and nearest a filmed ghost frame gives way to a clean source "
- "frame beside it (`ghost_at`)")
+ "frame beside it (`ghost_at`); a made frame kept that cross-fades two drawings inside its outline is kept "
+ "and named to look at (`look`)")
def parse_cycles(values: list[str]) -> dict[str, int]:
diff --git a/sprite_gen/video/interpolation_quality.py b/sprite_gen/video/interpolation_quality.py
index 5c7dd41..84274c5 100644
--- a/sprite_gen/video/interpolation_quality.py
+++ b/sprite_gen/video/interpolation_quality.py
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
"""The shared acceptance policy for the frames repair and cycle alignment deliver.
-Measurements live in ``rife`` (``smear``, ``ghost``); these are the existing alignment bounds,
-also applied before replacing a filmed middle frame during jump repair, and the ghost screen
-every frame a loop path delivers passes, filmed or made (docs/loop-repair.md section 4).
+Measurements live in ``rife`` (``smear``, ``ghost``, ``crossfade``); these are the existing alignment
+bounds, also applied before replacing a filmed middle frame during jump repair, the ghost screen
+every frame a loop path delivers passes, filmed or made, and the cross-fade a made frame is named
+for, kept (docs/loop-repair.md section 4).
"""
from PIL import Image
@@ -18,6 +19,11 @@ OUTLINE_WARN = 0.05
# model leaves between two held drawings (and the frames made beside them) and the frames seen as clean
# (docs/loop-repair.md section 4).
GHOST_WARN = 0.003
+# A made frame whose `rife.crossfade` is over this is named to look at, never given way for: on drawn
+# walks only the frame seen cross-faded read over it, but on synthetic legs a clean drawing between two
+# far-apart drawings outlined in grey reads over it too, and a cross-fade drawn without outlines mostly
+# under it — the reading does not part the two, so it is no fault (docs/loop-repair.md section 4).
+CROSSFADE_LOOK = 0.015
def faults(measure: dict[str, float | None]) -> list[str]:
@@ -29,6 +35,13 @@ def faults(measure: dict[str, float | None]) -> list[str]:
*(["ghost"] if (measure.get("ghost") or 0.0) > GHOST_WARN else [])])
+def looks(measure: dict[str, float | None]) -> list[str]:
+ """What a person should look at in a made frame, beyond its faults: two drawings cross-faded
+ inside its silhouette (`crossfade` over CROSSFADE_LOOK, where the measure carries it). Named in a
+ warning, the frame kept — never a reason to give it way."""
+ return ["crossfade"] if (measure.get("crossfade") or 0.0) > CROSSFADE_LOOK else []
+
+
def ghost_screen(frames: list[Image.Image]) -> dict:
"""The ghost screen of a loop as filmed: its frames whose `rife.ghost` is over GHOST_WARN
(`ghosts`, each `frame` and its reading) and the loop's own level, the median reading. A loop
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 8d2cf2d..168491e 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -1311,6 +1311,11 @@ def run_loop(
raise SystemExit(error) from exc
if report_base["jump_repair"]["replaced"]:
report_base["seam_measurement"] = "rendered-cells"
+ for r in report_base["jump_repair"].get("rounds", []):
+ if r["outcome"] == "accepted" and r["look"]:
+ print(f"video-loop: warning: frame {r['target']} was repaired with RIFE's frame between its neighbours, which may "
+ f"cross-fade two drawings inside its outline (crossfade {r['proposal']['crossfade']:.4f}); kept, a reading to "
+ "look at — see it in the loop, or cut it with --repair off (docs/loop-repair.md section 4)", file=sys.stderr)
if "rife" in report_base["jump_repair"]:
print(f"video-loop: warning: a jump frame was not repaired ({report_base['jump_repair']['score_max_before']:.2f}x "
f"the median step) — RIFE is not installed, so the loop is cut as filmed; run `{rife_mod.INSTALL_COMMAND}` "
@@ -1354,6 +1359,9 @@ def run_loop(
print(f"video-loop: warning: frame {g['frame']} of the cut (cycle/frame-{g['frame']:03d}.png) carries a part-covered band "
f"over {100 * g['ghost']:.2f} % of its body, at least {rife_mod.GHOST_THICK} px thick — a filmed ghost; delivered as cut "
"it shows, and video-cycle-align takes a clean frame beside it (docs/loop-repair.md)", file=sys.stderr)
+ if not report_base["ghost_screen"]["reads"]:
+ print(f"video-loop: warning: the ghost screen does not read this cut — {report_base['ghost_screen']['why']}; no frame "
+ "of it is named a ghost, here or in video-cycle-align, so look at cycle/ (docs/loop-repair.md)", file=sys.stderr)
cycle_dir.mkdir(parents=True, exist_ok=True)
for old in cycle_dir.glob("frame-*.png"):
old.unlink()
@@ -1557,7 +1565,7 @@ def run(**kwargs: object) -> int:
summary["cycle"]["coverage"] = payload["cycle"]["coverage"]
if "step_screen" in payload["cycle"]:
summary["cycle"]["step_screen"] = payload["cycle"]["step_screen"]
- if payload.get("ghost_screen", {}).get("ghosts"):
+ if payload.get("ghost_screen", {}).get("ghosts") or payload.get("ghost_screen", {}).get("reads") is False:
summary["ghost_screen"] = payload["ghost_screen"]
if payload.get("jump_repair", {}).get("replaced"):
summary["jump_repair"] = {k: payload["jump_repair"][k] for k in ("replaced", "score_max_before", "score_max_after")}
diff --git a/sprite_gen/video/repair.py b/sprite_gen/video/repair.py
index 4179e50..8c1225d 100644
--- a/sprite_gen/video/repair.py
+++ b/sprite_gen/video/repair.py
@@ -20,8 +20,8 @@ from typing import Any
from PIL import Image
from sprite_gen._deps import np
-from sprite_gen.video.rife import Interpolate, ghost, smear
-from sprite_gen.video.interpolation_quality import faults, ghost_screen
+from sprite_gen.video.rife import Interpolate, crossfade, ghost, smear
+from sprite_gen.video.interpolation_quality import faults, ghost_screen, looks
# A step this many times the loop's median step (whole body, or the hair behind it) is a jump.
JUMP_RATIO = 1.4
@@ -82,7 +82,8 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,
At most `max_frames` calls, and never next to a frame already made: two made frames side by side
are made from each other and melt the legs. A proposal with a shared interpolation-quality
fault — a ghost too, on its own coverage, where the loop's ghost screen reads it — keeps the
- original middle frame. Blocked and rejected targets do not end the search
+ original middle frame; a proposal that cross-fades two drawings inside its silhouette is still
+ taken, its round naming it (`look`). Blocked and rejected targets do not end the search
for independent targets. `interpolate` may be None while no jump is
found; it is asked for only when a frame is to be made (a ValueError says so otherwise).
Scores are re-read after each replacement, on the union box of the original loop."""
@@ -138,14 +139,14 @@ def repair_jumps(frames: list[Image.Image], interpolate: Interpolate | None, *,
attempted.add(j)
if reads is None:
reads = ghost_screen(frames)["reads"]
- measure = {**smear(made, a, b), "ghost": ghost(made) if reads else None}
+ measure = {**smear(made, a, b), "ghost": ghost(made) if reads else None, "crossfade": crossfade(made, a, b, 0.5)}
wrong = faults(measure)
if not made.getchannel("A").getbbox():
wrong.append("empty")
record["rounds"].append({"step": [k, (k + 1) % n], "target": j, "score": round(score, 4),
"whole": round(float(scores["whole"][k]), 4), "hair": round(float(scores["hair"][k]), 4),
"original": {**smear(out[j], a, b), "ghost": ghost(out[j]) if reads else None},
- "proposal": measure, "faults": wrong,
+ "proposal": measure, "faults": wrong, "look": looks(measure),
"outcome": "rejected" if wrong else "accepted", **({"replaced": j} if not wrong else {})})
if not wrong:
out[j] = made
diff --git a/sprite_gen/video/rife.py b/sprite_gen/video/rife.py
index 164ea70..4f8ce34 100644
--- a/sprite_gen/video/rife.py
+++ b/sprite_gen/video/rife.py
@@ -11,7 +11,8 @@ black a frame premultiplied over black put under it (2.24 and before: a black sm
crossing legs). Inside the coverage the colour is the frame's own, outline included.
`smear` measures what a made frame has that neither neighbour has, and the outline it lost where
the flow failed and melted a limb into the fill; `ghost` reads a band of part coverage on a frame
-alone, filmed or made (docs/loop-repair.md section 4).
+alone, filmed or made; `crossfade` reads two drawings cross-faded inside a whole silhouette, a
+reading to look at, not a fault (docs/loop-repair.md section 4).
The binary's own CPU path (`-g -1`) returns a wrong frame with rife-v4.6 on both macOS and
Linux (measured 2026-10-03: mean error 39 against 3.3 through Vulkan), so it is never passed;
@@ -60,6 +61,13 @@ OUTLINE_REACH = 2
# antialiased edge or a keyed strand of hair is a pixel or two wide and erodes away; the band a video
# model leaves between two drawings, or a flow carries from it, does not.
GHOST_THICK = 5
+# `crossfade`: an edge's local range is read over this many pixels, wider than RIFE's blur, so a
+# softened edge keeps its height and a cross-faded one does not; strong edges are counted in windows
+# this share of the body's height; a window that kept under CROSSFADE_KEEP of its source frames'
+# strong edges lost them.
+CROSSFADE_RANGE = 7
+CROSSFADE_WINDOW = 0.08
+CROSSFADE_KEEP = 0.6
CALL_TIMEOUT_SECONDS = 120
Interpolate = Callable[[Image.Image, Image.Image, float], Image.Image]
@@ -239,6 +247,65 @@ def ghost(frame: Image.Image) -> float:
return round(float(thick.sum()) / max(1, int((alpha >= 0.5).sum())), 5)
+def _local_range(x: np.ndarray) -> np.ndarray:
+ """Per pixel, the largest over the channels of max - min within CROSSFADE_RANGE pixels."""
+ out = np.zeros(x.shape[:2], dtype=np.float32)
+ for c in range(x.shape[2]):
+ channel = Image.fromarray(np.uint8(np.clip(x[..., c], 0, 1) * 255 + 0.5), "L")
+ hi = np.asarray(channel.filter(ImageFilter.MaxFilter(CROSSFADE_RANGE)), dtype=np.float32)
+ lo = np.asarray(channel.filter(ImageFilter.MinFilter(CROSSFADE_RANGE)), dtype=np.float32)
+ out = np.maximum(out, (hi - lo) / 255.0)
+ return out
+
+
+def crossfade(made: Image.Image, a: Image.Image, b: Image.Image, t: float) -> float:
+ """A cross-fade of two drawings inside the silhouette, the coverage whole: the near and far boots
+ of `a` and `b` both shown at part strength where a flow found nothing to follow. Read where two
+ things meet in one window of the frame where `a` and `b` differ: pixels of the made frame's solid
+ body at the plain blend of `a` and `b` at its own fraction `t` and well away from each (in patches
+ GHOST_THICK pixels thick, past an edge's soft rim), and the made frame keeping under CROSSFADE_KEEP
+ of the source frames' strong edges there — a blend shows each edge at part height, a flow that
+ moved the part shows it whole, only softer. The strong-edge pixels lost in such windows, as a
+ fraction of the made frame's solid pixels; 0 where it shows no blend. Relative to the source
+ frames' own edges, so a palette's lightness does not decide it (docs/loop-repair.md section 4)."""
+ m, fa, fb = (np.asarray(f.convert("RGBA"), dtype=np.float32) / 255.0 for f in (made, a, b))
+ pm, pa, pb = (np.dstack([x[..., :3] * x[..., 3:], x[..., 3:]]) for x in (m, fa, fb))
+
+ def dist(x: np.ndarray, y: np.ndarray) -> np.ndarray: # premultiplied RGBA, 0..1
+ return np.sqrt(((x - y) ** 2).sum(-1) / 4.0)
+
+ d = dist(pa, pb)
+ solid = m[..., 3] >= 0.5
+ blend = (solid & (d > 0.15) & (dist(pm, (1 - t) * pa + t * pb) < 0.35 * d)
+ & (dist(pm, pa) > 0.25 * d) & (dist(pm, pb) > 0.25 * d))
+ blend &= _mask(_mask(blend, GHOST_THICK, ImageFilter.MinFilter), GHOST_THICK, ImageFilter.MaxFilter)
+ if not blend.any():
+ return 0.0
+ rows = np.nonzero((np.maximum.reduce([fa[..., 3], fb[..., 3], m[..., 3]]) >= 0.5).any(axis=1))[0]
+ w = max(16, round(CROSSFADE_WINDOW * (rows[-1] - rows[0] + 1)))
+ changed = _mask(d > 0.08, CROSSFADE_RANGE, ImageFilter.MaxFilter)
+ ys, xs = np.nonzero(blend)
+ y0, y1, x0, x1 = max(0, ys.min() - w), ys.max() + w, max(0, xs.min() - w), xs.max() + w
+ rm, ra, rb = (np.zeros(d.shape, np.float32) for _ in range(3))
+ for into, x in ((rm, pm), (ra, pa), (rb, pb)):
+ into[y0:y1, x0:x1] = _local_range(x[y0:y1, x0:x1])
+ lost, step = 0.0, w // 2
+ for y in range((y0 // step) * step, y1, step):
+ for x in range((x0 // step) * step, x1, step):
+ win = (slice(y, y + w), slice(x, x + w))
+ near = changed[win]
+ if blend[win].sum() < 0.01 * w * w or near.sum() < 0.1 * w * w:
+ continue
+ strong = max(np.percentile(ra[win][near], 95), np.percentile(rb[win][near], 95))
+ if strong < 0.15: # no edge to keep here
+ continue
+ ka, kb, km = (int((r[win][near] > 0.5 * strong).sum()) for r in (ra, rb, rm))
+ kept = (ka + kb) / 2
+ if kept >= 0.02 * w * w and km < CROSSFADE_KEEP * kept:
+ lost += kept - km
+ return round(lost / max(1, int(solid.sum())), 5)
+
+
class Rife:
"""A located RIFE as an `Interpolate` callable. Counts the frames it made (`made`)."""