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(breathe): a smooth breath's beat chosen from the frames to miss the hands — `sprite-gen breathe --avoid-region`

Soohong Kim69d8e6ccef8e
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index 5290791..83283fb 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -437,7 +437,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab
# The Breathe layer for frames that are not a curation run (a video loop's cells): the sidecar's values, its
# normalization and its bake, so the same values give the same bytes either way.
"breathe": (
- "Lay the Breathe layer over a folder of loop frames: pixel (default) or smooth (large illustrations, video frames).",
+ "Lay the Breathe layer over a folder of loop frames: pixel (default) or smooth (large illustrations, video frames); smooth can choose its beat to miss the hands (--avoid-region).",
breathe.add_arguments,
breathe.run,
),
diff --git a/sprite_gen/effects/breath_beat.py b/sprite_gen/effects/breath_beat.py
new file mode 100644
index 0000000..7d4df30
--- /dev/null
+++ b/sprite_gen/effects/breath_beat.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: Apache-2.0
+"""손을 비키는 숨 박자 — `sprite-gen breathe --avoid-region` (smooth).
+
+큰 일러 idle 에서 손이 가슴 앞을 오르내리면, 들숨 꼭대기가 손이 크게 오르는 칸에 떨어질 때 숨이 손을 따라 오르는
+것처럼 읽히거나 가슴이 손 밑으로 묻힌다. 숨 박자(숨 수 `breaths` 또는 들숨 꼭대기 칸 `breath_peaks`)를 칸의
+움직임에서 고른다 — 손으로 숨 수를 바꿔 보던 일을 엔진이 같은 잣대로 한다:
+
+- 손 상자(`--avoid-region`)와 그 위 몸 상자(`--avoid-anchor`, 생략하면 손 상자 바로 위 띠 `anchor_band`)를 첫 칸
+ 기준 마스크 NCC 로 따라간다(`auto_motion.track_box`, 정수 px). 손의 제 오름 = 손 − 몸, 몸 오름 = 몸 (위 양수).
+- 후보는 한 숨이 `PERIOD_S` 안인 숨 수 k 를 고르게 둔 것, 그리고 고른 k 의 꼭대기를 앞뒤 `NUDGE` 칸까지 민 것이다
+ (k 가 3 이하면 꼭대기마다 따로, 넘으면 다 같이). 곡선은 굽기와 같은 `breathe.smooth_wave` 다.
+- 점수 = 상관(숨, 몸 오름) − 상관(숨, 손 오름). 숨이 손과 같이 오르내리지 않고 영상의 몸과 같이 가면 높다.
+- 조건: 들숨 꼭대기마다 앞뒤 `NEAR` 칸에서 가슴 오름(가슴 오름 px × 숨) 이 손의 제 오름보다 낮지 않다 — 가슴이
+ 손 위에 있다. 가슴 오름 px 는 굽기가 쓰는 그 값(`breathe.smooth_lift`)이다.
+- 규칙(`pick`): 조건을 지키는 고르게 둔 후보 가운데 점수가 가장 높은 것. 꼭대기를 민 후보는 그보다 점수가
+ `MARGIN` 넘게 나을 때만 쓴다. 조건을 지키는 후보가 없으면 조용히 하나를 고르지 않고 멈춘다.
+
+`MARGIN` 과 `anchor_band` 의 띠는 몇 판에서 고른 값이다 — 판이 늘면 다시 잰다. 고른 박자와 후보 표는 breathe.json
+`beat` 에 남고, 그 파일을 받는 Sway 레이어(`video-sway --breathe`)는 같은 박자로 흔든다."""
+
+from __future__ import annotations
+
+import itertools
+import math
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.curate.curation import BREATHE_BREATHS_MAX
+from sprite_gen.effects import breathe
+from sprite_gen.video import auto_motion
+
+PERIOD_S = (1.5, 4.0) # 한 숨의 길이(초) — 숨 수 후보를 이 안에서 고른다
+NUDGE = 3 # 꼭대기를 앞뒤로 미는 칸 수
+NEAR = 2 # 꼭대기 앞뒤 이 칸 안에서 손의 제 오름을 본다
+PEAK_LEVEL = 0.9 # 숨 곡선의 이 값을 넘는 꼭대기 칸이 들숨 꼭대기다
+MARGIN = 0.1 # 꼭대기를 민 후보가 고르게 둔 것보다 이만큼 넘게 나아야 쓴다
+ANCHOR_BAND = (0.65, 0.02) # 몸 상자 기본값: 손 상자 위 (손 높이의 이 몫 ~ 그림 높이의 이 몫 위) 띠, 같은 열
+SEARCH = 0.05 # 따라가는 반경 — 그림의 긴 변의 몫, 적어도 8 px
+SEARCH_MIN = 8
+
+
+def anchor_band(avoid: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
+ """`--avoid-anchor` 생략 시 몸 상자 — 손 상자와 같은 열, 손 상자 위 손 높이의 `ANCHOR_BAND[0]` 몫부터 그림 높이의
+ `ANCHOR_BAND[1]` 몫 위까지 (그림 비율)."""
+ x0, y0, x1, y1 = avoid
+ return x0, max(0.0, y0 - ANCHOR_BAND[0] * (y1 - y0)), x1, y0 - ANCHOR_BAND[1]
+
+
+def _px(box: tuple[float, float, float, float], size: tuple[int, int]) -> tuple[int, int, int, int]:
+ w, h = size
+ return round(box[0] * w), round(box[1] * h), round(box[2] * w), round(box[3] * h)
+
+
+def _corr(a: np.ndarray, b: np.ndarray) -> float:
+ a, b = a - a.mean(), b - b.mean()
+ d = math.sqrt(float((a * a).sum() * (b * b).sum()))
+ return float((a * b).sum() / d) if d else 0.0
+
+
+def _row(beat: dict, n: int, hands: np.ndarray, body: np.ndarray, lift: float) -> dict[str, Any]:
+ """한 박자 후보의 점수와 조건 — 그 박자로 굽기가 쓸 위상에서."""
+ w = np.asarray([breathe.smooth_wave(p) for p in breathe.fit_breathe_pattern(n, {"mode": "smooth", **beat})])
+ peaks = [i for i in range(n) if w[i] > PEAK_LEVEL and w[i] >= w[i - 1] and w[i] >= w[(i + 1) % n]]
+ margin = min(lift * w[p] - max(hands[(p + j) % n] for j in range(-NEAR, NEAR + 1)) for p in peaks)
+ corr_hands, corr_body = _corr(w, hands), _corr(w, body)
+ return {**beat, "peaks": peaks, "score": corr_body - corr_hands, "corr_hands": corr_hands, "corr_body": corr_body,
+ "margin_px": float(margin), "keeps": bool(margin >= 0)}
+
+
+def candidates(n: int, frame_ms: float) -> list[int]:
+ """숨 수 후보 — 한 숨이 `PERIOD_S` 안인 k."""
+ return [k for k in range(1, BREATHE_BREATHS_MAX + 1) if PERIOD_S[0] <= n * frame_ms / 1000 / k <= PERIOD_S[1]]
+
+
+def nudged(n: int, k: int) -> list[list[int]]:
+ """숨 k 번을 고르게 둔 꼭대기를 앞뒤 `NUDGE` 칸까지 민 꼭대기 목록들 — 첫 칸은 쉼, 마지막 꼭대기 뒤에 날숨이 들어갈
+ 두 칸, 꼭대기 사이 두 칸 이상(curation 의 breath_peaks 검사와 _peaked_phases 의 끝 검사)."""
+ base = [round((i + breathe.INHALE) * n / k) for i in range(k)]
+ span = range(-NUDGE, NUDGE + 1)
+ moves = itertools.product(span, repeat=k) if k <= 3 else ((m,) * k for m in span)
+ out = []
+ for move in moves:
+ peaks = [p + m for p, m in zip(base, move)]
+ if any(move) and peaks[0] >= 1 and peaks[-1] <= n - 2 and all(b - a >= 2 for a, b in zip(peaks, peaks[1:])):
+ out.append(peaks)
+ return out
+
+
+def pick(evenly: list[dict[str, Any]], pushed: list[dict[str, Any]]) -> dict[str, Any]:
+ """규칙 — 조건을 지키는 고르게 둔 후보 가운데 점수 최고(같으면 숨이 적은 쪽), 꼭대기를 민 후보는 그보다 `MARGIN`
+ 넘게 나을 때만. 조건을 지키는 고르게 둔 후보가 없으면 멈춘다."""
+ kept = [row for row in evenly if row["keeps"]]
+ if not kept:
+ least = max(evenly, key=lambda row: row["margin_px"])
+ raise SystemExit(f"breathe: --avoid-region — 어느 숨 수로도 들숨 꼭대기에서 가슴이 손 위에 있지 않다 (가장 나은 "
+ f"breaths {least['breaths']} 도 가슴 오름이 손의 제 오름보다 {-least['margin_px']:.2f} px 낮다). "
+ f"손 상자를 확인하거나 depth 를 올리거나 --breaths 로 정해라. 조용히 고르지 않는다.")
+ best = max(kept, key=lambda row: (row["score"], -row["breaths"]))
+ top = max((row for row in pushed if row["keeps"]), key=lambda row: row["score"], default=None)
+ return top if top is not None and top["score"] > best["score"] + MARGIN else best
+
+
+def choose(images: list[Image.Image], lift: float, avoid: tuple[float, float, float, float],
+ anchor: tuple[float, float, float, float] | None, frame_ms: float) -> tuple[dict[str, Any], dict[str, Any]]:
+ """`images`(숨 넣기 전 칸들)에서 고른 숨 박자(`{"breaths": k}` 또는 `{"breath_peaks": [...]}`)와 breathe.json 에
+ 남길 `beat` 기록."""
+ n = len(images)
+ size = images[0].size
+ anchor = anchor_band(avoid) if anchor is None else anchor
+ boxes = {"hands": _px(avoid, size), "body": _px(anchor, size)}
+ radius = max(SEARCH_MIN, round(SEARCH * max(size)))
+ moves = {}
+ for name, box in boxes.items():
+ try:
+ moves[name] = auto_motion.track_box(images, box, radius)
+ except ValueError as exc:
+ flag = "--avoid-region" if name == "hands" else "--avoid-anchor"
+ raise SystemExit(f"breathe: {flag} 상자 {list(box)} px 를 칸마다 따라가지 못한다 — {exc}") from exc
+ body = -moves["body"][:, 1]
+ hands = -moves["hands"][:, 1] - body
+ ks = candidates(n, frame_ms)
+ if not ks:
+ raise SystemExit(f"breathe: --avoid-region — 루프가 {n * frame_ms / 1000:g} 초라 {PERIOD_S[0]:g}~{PERIOD_S[1]:g} 초 "
+ f"숨이 정수 번 들어가지 않는다. --breaths 로 정해라.")
+ evenly = [_row({"breaths": k}, n, hands, body, lift) for k in ks]
+ best = pick(evenly, [])
+ pushed = [_row({"breath_peaks": peaks}, n, hands, body, lift) for peaks in nudged(n, best["breaths"])]
+ chosen = pick(evenly, pushed)
+ beat = {"breaths": chosen["breaths"]} if "breaths" in chosen else {"breath_peaks": chosen["breath_peaks"]}
+ top = max(pushed, key=lambda row: (row["keeps"], row["score"]), default=None)
+ record = {
+ "avoid_region": list(avoid), "avoid_anchor": list(anchor), "boxes_px": {k: list(v) for k, v in boxes.items()},
+ "search_px": radius, "frame_ms": frame_ms, "lift_px": round(lift, 4),
+ "hands_rise_px": hands.tolist(), "body_rise_px": body.tolist(),
+ "rule": {"period_s": list(PERIOD_S), "nudge": NUDGE, "near": NEAR, "margin": MARGIN},
+ "candidates": [_rounded(row) for row in evenly], "nudged_best": None if top is None else _rounded(top),
+ "chosen": beat,
+ }
+ return beat, record
+
+
+def _rounded(row: dict[str, Any]) -> dict[str, Any]:
+ return {k: round(v, 4) if isinstance(v, float) else v for k, v in row.items()}
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index 6465b05..cfb73c1 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -76,7 +76,7 @@ from sprite_gen.effects.anatomy import Anatomy, analyze
from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X,
BREATHE_SMOOTH_SHAPE, normalize_transform, state_breathe)
from sprite_gen.frames.extract import BORDER_MIN_FRACTION, FRAME_SIDES, own_border, solid_alpha_bbox
-from sprite_gen.frames.folder import open_frames, publish
+from sprite_gen.frames.folder import cycle_frame_ms, open_frames, publish
# 강체 경계에서 변형 강도가 0 이 되기까지의 테이퍼 반폭 (콘텐츠 높이 비율).
# 이 테이퍼가 이음매를 없앤다 — 경계에서 강도가 계단이 아니라 경사로 떨어진다.
@@ -1005,6 +1005,17 @@ def _cells(text: str) -> list[int]:
raise argparse.ArgumentTypeError(f"cell numbers separated by commas, not {text!r}")
+def _box(text: str) -> tuple[float, float, float, float]:
+ try:
+ x0, y0, x1, y1 = (float(part) for part in text.split(","))
+ except ValueError:
+ raise argparse.ArgumentTypeError(f"x0,y0,x1,y1 as shares of the picture (0..1), not {text!r}")
+ if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
+ raise argparse.ArgumentTypeError(f"x0,y0,x1,y1 as shares of the picture, 0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1, "
+ f"not {text!r}")
+ return x0, y0, x1, y1
+
+
def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("frames", help="folder of the loop's frames (*.png, played in name order)")
parser.add_argument("out", help="new folder for the breathing frames (same names) and breathe.json")
@@ -1047,6 +1058,25 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
shape.add_argument("--breath-peaks", type=_cells, default=None, metavar="CELL,CELL,...",
help="smooth: the cells where each in-breath peaks (the breath count is how many); the first "
"cell stays at rest and the loop closes at rest")
+ beat = parser.add_argument_group("the beat chosen to miss the hands (smooth; off by default)")
+ beat.add_argument("--avoid-region", type=_box, default=None, metavar="X0,Y0,X1,Y1",
+ help="the hands in front of the chest, as shares of the picture: the breath count (or each in-breath "
+ "peak) is chosen from the frames so the in-breath peaks miss the hands' own rise and the chest stays "
+ "above them; the choice and every candidate go into breathe.json `beat`. Not with --breaths or "
+ "--breath-peaks")
+ beat.add_argument("--avoid-anchor", type=_box, default=None, metavar="X0,Y0,X1,Y1",
+ help="the body the hands' own move is read against, as shares of the picture (default: the band just "
+ "above the hands, in their columns)")
+ beat.add_argument("--fps", type=float, default=None,
+ help="the frames' rate, for the length of a breath (a video-loop cycle/ folder has its own in the "
+ "loop's strip meta)")
+
+
+def _cli_breathe(raw: dict) -> dict:
+ try:
+ return state_breathe({"states": {"frames": {"breathe": raw}}}, "frames")
+ except SystemExit as exc:
+ raise SystemExit(f"breathe: 사이드카와 같은 검사에서 거부됐다 — {exc}")
def run(*, frames: str, out: str, mode: str | None = None, depth: float | None = None,
@@ -1055,9 +1085,12 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
chest_ry: float | None = None, shoulder: float | None = None, shoulder_lag: float | None = None,
chest_tilt: float | None = None, chest_bias: float | None = None, chest_dir: float | None = None,
chest_x: float | None = None, chest_bias_y: float | None = None, chest_flat: float | None = None,
- breath_peaks: list[int] | None = None) -> int:
+ breath_peaks: list[int] | None = None, avoid_region: tuple[float, float, float, float] | None = None,
+ avoid_anchor: tuple[float, float, float, float] | None = None, fps: float | None = None) -> int:
"""프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,
- 같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다."""
+ 같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다.
+
+ `avoid_region` 이면 숨 박자를 칸에서 고른다(`breath_beat`) — 고른 박자도 사이드카와 같은 검사를 다시 지난다."""
src_dir, out_dir = Path(frames), Path(out)
raw = {k: v for k, v in (("mode", mode), ("depth", depth), ("depth_x", depth_x), ("breaths", breaths),
("lag", lag), ("rigid_row", rigid_row), ("chest_y", chest_y), ("chest_rx", chest_rx),
@@ -1066,18 +1099,30 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
("chest_x", chest_x), ("chest_bias_y", chest_bias_y), ("chest_flat", chest_flat),
("breath_peaks", breath_peaks))
if v is not None}
- try:
- cfg = state_breathe({"states": {"frames": {"breathe": raw}}}, "frames")
- except SystemExit as exc:
- raise SystemExit(f"breathe: 사이드카와 같은 검사에서 거부됐다 — {exc}")
+ if avoid_region is None and (avoid_anchor is not None or fps is not None):
+ raise SystemExit("breathe: --avoid-anchor 와 --fps 는 --avoid-region 의 것이다 — 손 상자 없이는 읽지 않는다")
+ if avoid_region is not None and (breaths is not None or breath_peaks is not None):
+ raise SystemExit("breathe: --avoid-region 은 숨 박자를 칸에서 고른다 — --breaths·--breath-peaks 와 같이 주지 마라")
+ cfg = _cli_breathe(raw)
+ if avoid_region is not None and breathe_mode(cfg) != "smooth":
+ raise SystemExit("breathe: --avoid-region 은 smooth 의 것이다 (--mode smooth) — pixel 숨은 진행파라 첫 칸이 쉼이 아니다")
folder = open_frames(src_dir, out_dir, "breathe") # 무엇을 만들거나 지우기 전에 — 실경로와 폴더 동일성으로 본다
images = folder.images
anat = resolve_anatomy(images[0], cfg) # 보고와 굽기가 같은 한 벌 — 큰 칸은 재는 데 0.5 초다
+ beat = None
+ if avoid_region is not None:
+ from sprite_gen.effects import breath_beat # 박자 고르기가 이 모듈을 읽는다 — 돌아 들어오지 않게 여기서
+ frame_ms = cycle_frame_ms(src_dir, len(images), fps, "breathe")
+ if frame_ms is None:
+ raise SystemExit("breathe: --avoid-region 은 한 숨의 길이를 초로 본다 — --fps 를 주라 (video-loop 의 cycle/ "
+ "폴더면 루프의 strip meta 에서 읽는다)")
+ chosen, beat = breath_beat.choose(images, smooth_lift(anat, cfg), avoid_region, avoid_anchor, frame_ms)
+ cfg = _cli_breathe(raw | chosen)
resolved = anatomy_report(images, cfg, anat)
baked, phases = bake_breathe_sequence(images, cfg, anat)
# 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다(frames.folder.publish).
publish(folder, baked, "breathe.json", {"frames": len(images), "source": str(src_dir), "config": cfg,
- "phases": phases, "resolved": resolved})
+ "phases": phases, "resolved": resolved} | ({} if beat is None else {"beat": beat}))
print(f"breathe: {len(images)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "
f"breaths {cfg['breaths']} -> {out_dir}")
return 0
diff --git a/sprite_gen/video/auto_motion.py b/sprite_gen/video/auto_motion.py
index 977ea3f..083184e 100644
--- a/sprite_gen/video/auto_motion.py
+++ b/sprite_gen/video/auto_motion.py
@@ -137,6 +137,28 @@ def _match_costs(reference, moving, center, radius):
return 1 - product / np.maximum(1e-10, denominator), xs, ys
+def track_box(frames: list[Image.Image], box: tuple[int, int, int, int], radius: int) -> np.ndarray:
+ """Per frame, how far the content of `box` (x0, y0, x1, y1 in frames[0]) lies from where it is in frames[0], across
+ and down, in whole px: the masked NCC `discover` tracks with, at full size, searched within `radius` px each way.
+
+ Each frame is cut to the box grown by the radius before it is read, so a large frame costs what its box does.
+ ValueError where the box holds too little body to match, or where a match reaches the edge of the search."""
+ x0, y0, x1, y1 = box
+ width, height = frames[0].size
+ cut = (max(0, x0 - radius), max(0, y0 - radius), min(width, x1 + radius), min(height, y1 + radius))
+ inner = (x0 - cut[0], y0 - cut[1], x1 - cut[0], y1 - cut[1])
+ if inner[2] <= inner[0] or inner[3] <= inner[1] or x0 < 0 or y0 < 0 or x1 > width or y1 > height:
+ raise ValueError(f"box {box} is not inside the {width}x{height} frame")
+ reference = _reference(motion_anchor._features(frames[0].crop(cut)), inner)
+ if reference is None:
+ raise ValueError(f"box {box} holds too little body to match")
+ moves = []
+ for frame in frames:
+ shift, _ = _match(reference, motion_anchor._features(frame.crop(cut)), (0, 0), radius)
+ moves.append((-float(shift[0]), -float(shift[1])))
+ return np.asarray(moves)
+
+
def discover(frames: list[Image.Image], *, reference_index: int) -> tuple[list, dict]:
if len(frames) < 6 or any(im.mode != 'RGBA' or im.size != frames[0].size for im in frames):
raise ValueError("automatic motion anchor needs at least six equally sized RGBA frames")