Datasets:
File size: 27,982 Bytes
8ba5a96 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
burn_transition.py —— 双视频「燃烧圆形扩散」无缝转场
思路
----
给定两段视频 A、B,以及一对「动作对齐」的时刻 tA / tB(此刻两边镜头/玩家的运动
方向与速度一致),脚本会:
[A: tA-pre, tA-dur/2) 纯旧场景
[tA±dur/2] × [tB±dur/2] 燃烧扩散:圆内 = B,圆外 = A,边缘是火
[B: tB+dur/2, tB+post) 纯新场景
燃烧边缘由极坐标(角度 × 半径)里的多层湍流噪声驱动,角向频率高、径向频率低,
因此火口是不规则的、带放射状火舌的形状;再叠加白热芯 / 黄焰 / 橙焰 / 暗红辉光、
逐点热度调制、火线前方的焦化与热浪扭曲、以及向外飞散的火星粒子。
用法
----
# 已知对齐时刻
python burn_transition.py -a A.mp4 -b B.mp4 --ta 11.9 --tb 15.7 -o out.mp4
# 不知道该在哪拼 —— 自动搜索运动最匹配的时刻
python burn_transition.py -a A.mp4 -b B.mp4 --auto-align -o out.mp4
# 只看看两段视频各自的运动方向时间线(用来人工挑对齐点)
python burn_transition.py -a A.mp4 --probe
# 换个样式 / 配色 / 节奏
python burn_transition.py -a A.mp4 -b B.mp4 --ta 11.9 --tb 15.7 \
--style ring --color fire --dur 2.0 --keep-audio -o out.mp4
依赖
----
pip install numpy opencv-python # 另需系统里有 ffmpeg / ffprobe
固定 --seed 时输出逐帧完全可复现。
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass, field
from typing import Iterator, Optional, Sequence
import cv2
import numpy as np
# --------------------------------------------------------------------------- #
# 配色(BGR):核心白热 → 中焰 → 外焰 → 辉光
# --------------------------------------------------------------------------- #
PALETTES: dict[str, tuple[tuple[int, int, int], ...]] = {
"fire": ((205, 240, 255), ( 70, 205, 255), ( 15, 105, 250), ( 8, 28, 190)),
"blue": ((255, 244, 222), (255, 205, 75), (250, 130, 25), (190, 55, 10)),
"purple": ((255, 236, 246), (255, 130, 205), (232, 45, 150), (150, 12, 95)),
"green": ((226, 255, 232), (120, 255, 150), ( 45, 230, 85), ( 18, 150, 45)),
"ice": ((255, 250, 240), (255, 225, 160), (250, 180, 70), (200, 110, 25)),
}
@dataclass
class Config:
"""一次渲染的全部参数。"""
a: str
b: str
out: str
ta: float = 0.0 # A 中的对齐时刻(秒)
tb: float = 0.0 # B 中的对齐时刻(秒)
pre: float = 3.0 # 转场前保留的旧场景时长(秒)
post: float = 3.0 # 转场后保留的新场景时长(秒)
dur: float = 2.5 # 燃烧扩散时长(秒)
fps: Optional[float] = None # 输出帧率,默认取 A 的帧率
style: str = "burn" # burn | ring
color: str = "fire"
center: tuple[float, float] = (0.5, 0.5) # 圆心(画面宽高的比例)
amp: float = 165.0 # 火舌长度 / 边缘扰动幅度(px @720p)
embers: float = 1.0 # 火星密度倍率
ring_width: float = 6.0 # style=ring 时的圆环粗细
feather: float = 16.0 # style=ring 时的边缘羽化
seed: int = 7
crf: int = 17
keep_audio: bool = False
quiet: bool = False
# --------------------------------------------------------------------------- #
# 工具
# --------------------------------------------------------------------------- #
def _need(binary: str) -> str:
p = shutil.which(binary)
if not p:
sys.exit(f"[错误] 找不到 {binary},请先安装 ffmpeg。")
return p
def probe(path: str) -> dict:
"""用 ffprobe 读取视频基本信息。"""
_need("ffprobe")
out = subprocess.run(
["ffprobe", "-v", "error", "-print_format", "json",
"-show_streams", "-show_format", path],
capture_output=True, text=True, check=True).stdout
info = json.loads(out)
v = next((s for s in info["streams"] if s["codec_type"] == "video"), None)
if v is None:
sys.exit(f"[错误] {path} 里没有视频流。")
num, den = (v.get("r_frame_rate") or "30/1").split("/")
return dict(
width=int(v["width"]), height=int(v["height"]),
fps=float(num) / float(den or 1),
duration=float(info["format"].get("duration", 0) or 0),
has_audio=any(s["codec_type"] == "audio" for s in info["streams"]),
)
def smoothstep(t):
t = np.clip(t, 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
class Clip:
"""按输出帧率取帧的读取器,自动处理帧率差异与分辨率差异(居中裁剪填满)。"""
def __init__(self, path: str, out_size: tuple[int, int], out_fps: float):
if not os.path.isfile(path):
sys.exit(f"[错误] 找不到文件:{path}")
self.path = path
self.info = probe(path)
self.out_w, self.out_h = out_size
self.out_fps = out_fps
self.cap = cv2.VideoCapture(path)
self._pos = -1
@property
def n_frames(self) -> int:
return int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def _fit(self, frame: np.ndarray) -> np.ndarray:
h, w = frame.shape[:2]
if (w, h) == (self.out_w, self.out_h):
return frame
s = max(self.out_w / w, self.out_h / h) # cover
rw, rh = int(round(w * s)), int(round(h * s))
frame = cv2.resize(frame, (rw, rh), interpolation=cv2.INTER_AREA)
x0, y0 = (rw - self.out_w) // 2, (rh - self.out_h) // 2
return frame[y0:y0 + self.out_h, x0:x0 + self.out_w]
def read_at(self, t: float) -> Optional[np.ndarray]:
"""取时间 t(秒)处的一帧。"""
idx = int(round(t * self.info["fps"]))
idx = max(idx, 0)
if self._pos < 0 or idx < self._pos or idx > self._pos + 60:
self.cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
self._pos = idx - 1
while self._pos < idx: # 顺序跳帧,避免反复 seek
ok = self.cap.grab()
if not ok:
return None
self._pos += 1
ok, frame = self.cap.retrieve()
return self._fit(frame) if ok else None
def stream(self, t0: float, n: int) -> Iterator[np.ndarray]:
for i in range(n):
f = self.read_at(t0 + i / self.out_fps)
if f is None:
return
yield f
def release(self):
self.cap.release()
# --------------------------------------------------------------------------- #
# 运动分析:估计每帧的全局位移(= 镜头平移,玩家移动方向的反向)
# --------------------------------------------------------------------------- #
def motion_track(path: str, work_w: int = 320, work_h: int = 180) -> dict:
"""返回 {'fps', 'vx', 'vy'},vx/vy 是玩家移动方向(缩放到 work_w 宽度下的 px/帧)。"""
cap = cv2.VideoCapture(path)
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
han = cv2.createHanningWindow((work_w, work_h), cv2.CV_32F)
prev, vx, vy = None, [], []
while True:
ok, frame = cap.read()
if not ok:
break
g = cv2.cvtColor(cv2.resize(frame, (work_w, work_h)), cv2.COLOR_BGR2GRAY).astype(np.float32)
if prev is not None:
(dx, dy), _ = cv2.phaseCorrelate(prev, g, han)
vx.append(-dx); vy.append(-dy) # 取反:画面往左退 = 玩家往右走
prev = g
cap.release()
k = np.ones(9) / 9.0
return dict(fps=fps,
vx=np.convolve(np.array(vx, np.float32), k, mode="same"),
vy=np.convolve(np.array(vy, np.float32), k, mode="same"))
_ARROWS = ["→", "↗", "↑", "↖", "←", "↙", "↓", "↘"]
def print_timeline(path: str, still: float = 0.35) -> None:
"""打印每秒的平均运动方向,用来人工挑对齐点。"""
m = motion_track(path)
vx, vy, fps = m["vx"], m["vy"], m["fps"]
n, step = len(vx), int(round(m["fps"]))
print(f"== {os.path.basename(path)} {n / fps:.1f}s 平均速度 {np.hypot(vx, vy).mean():.2f}px/帧")
cells = []
for s in range(0, n, step):
mx, my = vx[s:s + step].mean(), vy[s:s + step].mean()
mag = float(np.hypot(mx, my))
if mag < still:
cells.append(" · ")
else:
ang = np.degrees(np.arctan2(my, mx))
cells.append(f"{_ARROWS[int(((ang + 22.5) % 360) // 45)]}{mag:.1f}")
for i in range(0, len(cells), 15):
print(f" {i:>3}s | " + " ".join(cells[i:i + 15]))
def auto_align(path_a: str, path_b: str, dur: float, pre: float, post: float,
min_speed: float = 0.45, max_jitter: float = 0.45, top: int = 5):
"""在 A、B 里搜索运动方向+速度最一致、且足够平稳的时间窗,返回候选 [(tA, tB, cost)]。"""
ma, mb = motion_track(path_a), motion_track(path_b)
def windows(m):
vx, vy, fps = m["vx"], m["vy"], m["fps"]
W = max(int(round(dur * fps)), 2)
idx = np.arange(0, max(len(vx) - W + 1, 0))
if len(idx) == 0:
return None
cx = np.concatenate([[0], np.cumsum(vx)]); cy = np.concatenate([[0], np.cumsum(vy)])
mx = (cx[idx + W] - cx[idx]) / W
my = (cy[idx + W] - cy[idx]) / W
cx2 = np.concatenate([[0], np.cumsum(vx ** 2)]); cy2 = np.concatenate([[0], np.cumsum(vy ** 2)])
sd = np.sqrt(np.maximum((cx2[idx + W] - cx2[idx]) / W - mx ** 2, 0) +
np.maximum((cy2[idx + W] - cy2[idx]) / W - my ** 2, 0))
ok = (idx >= pre * fps) & (idx + W + post * fps <= len(vx))
ok &= (np.hypot(mx, my) > min_speed) & (sd < max_jitter)
return idx, mx, my, sd, ok, fps
wa, wb = windows(ma), windows(mb)
if wa is None or wb is None or wa[4].sum() == 0 or wb[4].sum() == 0:
return []
ia, ax, ay, asd, aok, fa = wa
ib, bx, by, bsd, bok, fb = wb
A = np.stack([ax[aok], ay[aok]], 1); B = np.stack([bx[bok], by[bok]], 1)
diff = np.linalg.norm(A[:, None, :] - B[None, :, :], axis=2)
cost = (diff
+ 0.35 * (asd[aok][:, None] + bsd[bok][None, :])
- 0.30 * np.minimum(np.hypot(*A.T)[:, None], np.hypot(*B.T)[None, :]))
flat = np.argsort(cost, axis=None)[:top * 300]
out: list[tuple] = []
for k in flat:
i, j = np.unravel_index(k, cost.shape)
ta = (ia[aok][i] + dur * fa / 2) / fa # 窗口中点 = 对齐时刻
tb = (ib[bok][j] + dur * fb / 2) / fb
# 候选之间至少隔开 1s,否则只是同一处的相邻帧
if any(max(abs(ta - x), abs(tb - y)) < 1.0 for x, y, _, _ in out):
continue
out.append((float(ta), float(tb), float(cost[i, j]),
(float(A[i, 0]), float(A[i, 1]))))
if len(out) >= top:
break
return out
# --------------------------------------------------------------------------- #
# 火焰合成
# --------------------------------------------------------------------------- #
class PolarNoise:
"""(角度 × 半径) 空间里的动画分形噪声 —— 角向高频、径向低频 ⇒ 放射状火舌。"""
OCT = ((6, 4, 18, 1.00), (9, 7, 42, 0.50), (13, 12, 88, 0.26), (17, 22, 176, 0.13))
WT, HR = 512, 224
def __init__(self, dist: np.ndarray, theta: np.ndarray, rmax: float, rng):
self.grids = [rng.random((t, h, w)).astype(np.float32) for t, h, w, _ in self.OCT]
amps = np.array([o[3] for o in self.OCT], np.float32)
self.amps = amps / amps.sum()
self.map_x = (((theta / (2 * np.pi)) % 1.0) * self.WT).astype(np.float32)
self.map_y = (np.clip(dist / rmax, 0, 1) * (self.HR - 1)).astype(np.float32)
def __call__(self, u: float) -> np.ndarray:
acc = np.zeros((self.HR, self.WT), np.float32)
for g, a in zip(self.grids, self.amps):
T = g.shape[0]
f = u * (T - 1e-6)
i0 = int(f) % T
fr = f - int(f)
sl = g[i0] * (1 - fr) + g[(i0 + 1) % T] * fr
sl = np.concatenate([sl, sl[:, :1]], axis=1) # 角度方向环绕
up = cv2.resize(sl, (self.WT + 1, self.HR), interpolation=cv2.INTER_CUBIC)
acc += a * up[:, :self.WT]
return cv2.remap(acc, self.map_x, self.map_y, cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REPLICATE)
class Embers:
"""火星粒子:沿径向外飞 + 向上浮 + 阻尼 + 短拖影。"""
def __init__(self, w: int, h: int, cx: float, cy: float, rng):
self.w, self.h, self.cx, self.cy, self.rng = w, h, cx, cy, rng
z = np.zeros(0, np.float32)
self.p = dict(x=z.copy(), y=z.copy(), vx=z.copy(), vy=z.copy(),
life=z.copy(), age=z.copy(), heat=z.copy())
def spawn(self, n: int, r: float, front_speed: float):
if n <= 0:
return
rng = self.rng
th = rng.random(n).astype(np.float32) * 2 * np.pi
rr = r + rng.normal(0, 14, n).astype(np.float32)
sp = front_speed * rng.uniform(0.25, 0.85, n).astype(np.float32) \
+ rng.uniform(0.4, 2.6, n).astype(np.float32)
tg = rng.normal(0, 0.8, n).astype(np.float32)
new = dict(
x=self.cx + np.cos(th) * rr, y=self.cy + np.sin(th) * rr,
vx=np.cos(th) * sp - np.sin(th) * tg,
vy=np.sin(th) * sp + np.cos(th) * tg - rng.uniform(0.5, 2.0, n).astype(np.float32),
life=rng.uniform(20, 58, n).astype(np.float32),
age=np.zeros(n, np.float32),
heat=rng.uniform(0.45, 1.0, n).astype(np.float32))
for k, v in new.items():
self.p[k] = np.concatenate([self.p[k], v.astype(np.float32)])
def step(self):
p = self.p
p["vy"] += 0.055
p["vx"] *= 0.975; p["vy"] *= 0.975
p["x"] += p["vx"]; p["y"] += p["vy"]
p["age"] += 1
keep = ((p["age"] < p["life"]) & (p["x"] > -20) & (p["x"] < self.w + 20)
& (p["y"] > -20) & (p["y"] < self.h + 20))
for k in p:
p[k] = p[k][keep]
def draw(self) -> np.ndarray:
buf = np.zeros((self.h, self.w), np.float32)
p = self.p
if len(p["x"]):
t = p["age"] / np.maximum(p["life"], 1)
wgt = p["heat"] * (1 - t) ** 1.5 * self.rng.uniform(0.6, 1.0, len(t)).astype(np.float32)
for s in (0.0, -0.45, -0.9): # 沿速度方向的短拖影
ix = np.clip((p["x"] + p["vx"] * s).astype(np.int32), 0, self.w - 1)
iy = np.clip((p["y"] + p["vy"] * s).astype(np.int32), 0, self.h - 1)
np.add.at(buf, (iy, ix), wgt * (1.0 + s * 0.6))
return buf
def __len__(self):
return len(self.p["x"])
# --------------------------------------------------------------------------- #
# 主渲染
# --------------------------------------------------------------------------- #
def render(cfg: Config) -> str:
_need("ffmpeg")
ia = probe(cfg.a)
fps = cfg.fps or ia["fps"]
Wd, Ht = ia["width"], ia["height"]
clip_a = Clip(cfg.a, (Wd, Ht), fps)
clip_b = Clip(cfg.b, (Wd, Ht), fps)
n_pre, n_burn, n_post = (max(int(round(x * fps)), 0) for x in (cfg.pre, cfg.dur, cfg.post))
n_burn = max(n_burn, 1)
half = cfg.dur / 2.0
# 时间轴:燃烧窗口以对齐时刻为中心
a_t0 = cfg.ta - half - cfg.pre # A 起点
a_burn_t0 = cfg.ta - half
b_burn_t0 = cfg.tb - half
b_t0 = cfg.tb + half # B 转场后起点
if a_t0 < -1e-6:
sys.exit(f"[错误] A 里 tA={cfg.ta}s 前面不足 {cfg.pre}s 铺垫,请调小 --pre 或增大 --ta。")
if b_t0 + cfg.post > ia_b_dur(clip_b) + 1e-6:
sys.exit(f"[错误] B 里 tB={cfg.tb}s 之后不足 {half + cfg.post:.2f}s,请调小 --post/--dur。")
rng = np.random.default_rng(cfg.seed)
cx, cy = cfg.center[0] * Wd, cfg.center[1] * Ht
yy, xx = np.mgrid[0:Ht, 0:Wd].astype(np.float32)
dxg, dyg = xx - cx, yy - cy
dist = np.hypot(dxg, dyg)
rmax = float(dist.max())
noise = PolarNoise(dist, np.arctan2(dyg, dxg), rmax, rng) if cfg.style == "burn" else None
embers = Embers(Wd, Ht, cx, cy, rng)
C_HOT, C_MID, C_OUT, C_GLOW = (np.array(c, np.float32) for c in PALETTES[cfg.color])
ff = subprocess.Popen(
["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24",
"-s", f"{Wd}x{Ht}", "-r", f"{fps}", "-i", "-",
"-c:v", "libx264", "-crf", str(cfg.crf), "-preset", "medium",
"-pix_fmt", "yuv420p", "-movflags", "+faststart",
cfg.out if not cfg.keep_audio else cfg.out + ".silent.mp4"],
stdin=subprocess.PIPE)
w = ff.stdin.write
def log(msg):
if not cfg.quiet:
print(msg, flush=True)
# ---- 1) 旧场景铺垫 --------------------------------------------------- #
log(f"[1/3] 旧场景 {cfg.pre}s ({n_pre} 帧)")
for f in clip_a.stream(a_t0, n_pre):
w(f.tobytes())
# ---- 2) 燃烧扩散 ----------------------------------------------------- #
log(f"[2/3] {'燃烧扩散' if cfg.style == 'burn' else '圆环扩散'} {cfg.dur}s "
f"({n_burn} 帧) color={cfg.color} 对齐于 A {cfg.ta:.2f}s / B {cfg.tb:.2f}s")
prev_r = 0.0
for k in range(n_burn):
fa = clip_a.read_at(a_burn_t0 + k / fps)
fb = clip_b.read_at(b_burn_t0 + k / fps)
if fa is None or fb is None:
log("[警告] 素材帧不足,燃烧段提前结束。")
break
u = (k + 1) / n_burn
fa = fa.astype(np.float32); fb = fb.astype(np.float32)
if cfg.style == "ring":
out, r = _composite_ring(fa, fb, dist, rmax, u, cfg, C_GLOW)
else:
out, r = _composite_burn(fa, fb, dist, dxg, dyg, xx, yy, rmax, u, k,
cfg, noise, rng, C_HOT, C_MID, C_OUT, C_GLOW)
fade = 1.0 - smoothstep((r - rmax * 0.90) / (rmax * 0.22))
embers.spawn(int(160 * cfg.embers * fade * (0.4 + 0.6 * min(r / 200.0, 1.0))),
max(r, 6.0), max(r - prev_r, 0.0))
embers.step()
sp = cv2.GaussianBlur(embers.draw(), (0, 0), 0.7)
big = cv2.GaussianBlur(sp, (0, 0), 5.0) * 0.60
out += (C_HOT * (np.clip(sp, 0, 2.6) * 0.75)[..., None]
+ C_MID * (np.clip(sp, 0, 2.6) * 1.05)[..., None]
+ C_OUT * big[..., None])
prev_r = r
w(np.clip(out, 0, 255).astype(np.uint8).tobytes())
# ---- 3) 新场景 + 余烬 ------------------------------------------------ #
log(f"[3/3] 新场景 {cfg.post}s ({n_post} 帧)")
for f in clip_b.stream(b_t0, n_post):
out = f.astype(np.float32)
if cfg.style == "burn" and len(embers):
embers.step()
sp = cv2.GaussianBlur(embers.draw(), (0, 0), 1.2)
out += C_MID * (np.clip(sp, 0, 2.2) * 0.95)[..., None]
w(np.clip(out, 0, 255).astype(np.uint8).tobytes())
ff.stdin.close(); ff.wait()
clip_a.release(); clip_b.release()
if cfg.keep_audio:
_mux_audio(cfg, a_t0, cfg.pre + cfg.dur, b_burn_t0, cfg.dur + cfg.post)
log(f"[完成] {cfg.out}")
return cfg.out
def ia_b_dur(clip: Clip) -> float:
return clip.info["duration"] or (clip.n_frames / max(clip.info["fps"], 1e-6))
def _composite_ring(fa, fb, dist, rmax, u, cfg, color):
"""朴素版:单色圆环 + 羽化融合。"""
r = float(smoothstep(u) * (rmax + cfg.feather * 2))
m = np.clip((r - dist) / cfg.feather + 0.5, 0, 1)
m = (m * m * (3 - 2 * m))[..., None]
out = fa * (1 - m) + fb * m
d = np.abs(dist - r)
core = np.exp(-(d / cfg.ring_width) ** 2)
glow = np.exp(-(d / (cfg.ring_width * 4.3)) ** 2) * 0.45
fade = 1.0 - smoothstep((r - rmax * 0.86) / (rmax * 0.20))
a = (core * fade)[..., None]
out = out * (1 - a) + color * a + color * (glow * fade)[..., None] * 0.8
return out, r
def _composite_burn(fa, fb, dist, dxg, dyg, xx, yy, rmax, u, k, cfg, noise, rng,
C_HOT, C_MID, C_OUT, C_GLOW):
"""燃烧版:湍流火口 + 焦化 + 热浪 + 四层火焰。"""
amp = cfg.amp * (0.35 + 0.65 * smoothstep(u * 1.6)) # 火舌随火势变长
r = float(smoothstep(u) * (rmax + amp * 1.25) - amp * 0.35)
n = noise(u * 0.55 + k * 0.004)
n2 = noise(0.5 + u * 0.9 + k * 0.011) # 逐点热度调制
up = 22.0 * np.clip(-dyg / np.maximum(dist, 1.0), 0, 1) # 火往上窜
F = dist - r + amp * (np.clip(n, 0, 1) ** 1.35 - 0.42) - up # F<0 已烧穿(新场景)
hot = 0.35 + 1.45 * np.clip(n2, 0, 1) ** 1.5
flick = float(rng.uniform(0.93, 1.08))
# 火线前方的热浪扭曲
haze = np.exp(-((F - 32.0) / 46.0) ** 2) * (F > 0)
gy, gx = np.gradient(n)
fa = cv2.remap(fa, (xx + gx * 900.0 * haze).astype(np.float32),
(yy + gy * 900.0 * haze).astype(np.float32),
cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
# 即将烧到的地方先焦化
char = np.exp(-((F - 26.0) / 34.0) ** 2) * (F > 0)
fa = fa * (1 - 0.72 * char)[..., None] + np.array([6, 22, 55], np.float32) * (char * 0.55)[..., None]
m = smoothstep((-F) / 2.5 + 0.5)[..., None]
out = fa * (1 - m) + fb * m
inside = F < 0
out += C_OUT * (np.exp(-(np.clip(-F, 0, None) / 75.0) ** 2) * inside * 0.34 * flick)[..., None]
rim = np.exp(-((np.clip(-F, 0, None) - 9.0) / 15.0) ** 2) * inside # 内侧焦边
out *= (1 - 0.55 * rim)[..., None]
core = np.exp(-(F / 4.5) ** 2) * hot
mid = np.exp(-((F - 6.0) / 10.0) ** 2) * (0.55 + 0.65 * hot)
outr = np.exp(-((F - 16.0) / 21.0) ** 2)
glow = np.exp(-((F - 28.0) / 50.0) ** 2)
fade = 1.0 - smoothstep((r - rmax * 0.90) / (rmax * 0.22))
em = (C_HOT * (core * 1.05)[..., None] + C_MID * (mid * 0.80)[..., None]
+ C_OUT * (outr * 0.55)[..., None] + C_GLOW * (glow * 0.38)[..., None]) * (fade * flick)
a = np.clip(core * 1.25, 0, 1)[..., None] * fade
out = out * (1 - a) + em * a + em * 0.45 * (1 - a)
return out, r
def _mux_audio(cfg: Config, a_t0: float, a_len: float, b_t0: float, b_len: float):
"""A 的声音接 B 的声音,在燃烧段做交叉淡化。"""
silent = cfg.out + ".silent.mp4"
ha, hb = probe(cfg.a)["has_audio"], probe(cfg.b)["has_audio"]
if not (ha and hb):
os.replace(silent, cfg.out)
if not cfg.quiet:
print("[提示] 素材缺少音轨,输出为无声。")
return
cmd = ["ffmpeg", "-y", "-v", "error", "-i", silent,
"-ss", f"{a_t0:.3f}", "-t", f"{a_len:.3f}", "-i", cfg.a,
"-ss", f"{b_t0:.3f}", "-t", f"{b_len:.3f}", "-i", cfg.b,
"-filter_complex",
f"[1:a]aresample=48000[a1];[2:a]aresample=48000[a2];"
f"[a1][a2]acrossfade=d={cfg.dur:.3f}:c1=tri:c2=tri[a]",
"-map", "0:v", "-map", "[a]", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
"-shortest", cfg.out]
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
os.replace(silent, cfg.out)
if not cfg.quiet:
print("[提示] 混音失败,已输出无声版本:", r.stderr.strip().splitlines()[-1:] or "")
else:
os.remove(silent)
# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def main(argv: Optional[Sequence[str]] = None) -> int:
p = argparse.ArgumentParser(
description="双视频燃烧圆形扩散转场",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="示例:\n"
" python burn_transition.py -a A.mp4 -b B.mp4 --ta 11.9 --tb 15.7 -o out.mp4\n"
" python burn_transition.py -a A.mp4 -b B.mp4 --auto-align -o out.mp4\n"
" python burn_transition.py -a A.mp4 --probe\n")
p.add_argument("-a", required=True, help="旧场景视频")
p.add_argument("-b", help="新场景视频")
p.add_argument("-o", "--out", default="transition.mp4", help="输出文件(默认 transition.mp4)")
p.add_argument("--ta", type=float, help="A 中动作对齐时刻(秒)")
p.add_argument("--tb", type=float, help="B 中动作对齐时刻(秒)")
p.add_argument("--auto-align", action="store_true", help="自动搜索运动最匹配的对齐时刻")
p.add_argument("--probe", action="store_true", help="只打印运动方向时间线后退出")
p.add_argument("--pre", type=float, default=3.0, help="转场前旧场景时长,默认 3s")
p.add_argument("--post", type=float, default=3.0, help="转场后新场景时长,默认 3s")
p.add_argument("--dur", type=float, default=2.5, help="燃烧扩散时长,默认 2.5s")
p.add_argument("--style", choices=["burn", "ring"], default="burn", help="burn=火焰,ring=纯色圆环")
p.add_argument("--color", choices=sorted(PALETTES), default="fire", help="配色,默认 fire")
p.add_argument("--center", default="0.5,0.5", help="圆心位置,画面比例,如 0.5,0.45")
p.add_argument("--amp", type=float, default=165.0, help="火舌长度(px),默认 165")
p.add_argument("--embers", type=float, default=1.0, help="火星密度倍率,默认 1.0")
p.add_argument("--ring-width", type=float, default=6.0, help="style=ring 的圆环粗细")
p.add_argument("--feather", type=float, default=16.0, help="style=ring 的边缘羽化")
p.add_argument("--fps", type=float, help="输出帧率,默认取 A 的帧率")
p.add_argument("--crf", type=int, default=17, help="x264 质量,越小越好,默认 17")
p.add_argument("--keep-audio", action="store_true", help="保留原声并在转场处交叉淡化")
p.add_argument("--seed", type=int, default=7, help="随机种子,固定则完全可复现")
p.add_argument("--quiet", action="store_true")
args = p.parse_args(argv)
if args.probe:
print_timeline(args.a)
if args.b:
print()
print_timeline(args.b)
return 0
if not args.b:
p.error("需要 -b 指定新场景视频(或用 --probe 只做分析)")
ta, tb = args.ta, args.tb
if args.auto_align or ta is None or tb is None:
print("[对齐] 正在搜索运动最匹配的时刻……")
cands = auto_align(args.a, args.b, args.dur, args.pre, args.post)
if not cands:
sys.exit("[错误] 没找到运动足够一致的时间窗,请手动指定 --ta/--tb,"
"或放宽 --dur / 换素材。")
for i, (x, y, c, v) in enumerate(cands):
ang = np.degrees(np.arctan2(v[1], v[0]))
arrow = _ARROWS[int(((ang + 22.5) % 360) // 45)]
mark = " <= 采用" if i == 0 else ""
print(f" {i+1}. A {x:6.2f}s + B {y:6.2f}s 方向 {arrow} "
f"速度 {np.hypot(*v):.2f}px/帧 cost={c:.3f}{mark}")
ta, tb = cands[0][0], cands[0][1]
cxy = tuple(float(v) for v in args.center.split(","))
if len(cxy) != 2:
p.error("--center 需要形如 0.5,0.5")
cfg = Config(a=args.a, b=args.b, out=args.out, ta=ta, tb=tb,
pre=args.pre, post=args.post, dur=args.dur, fps=args.fps,
style=args.style, color=args.color, center=cxy, amp=args.amp,
embers=args.embers, ring_width=args.ring_width, feather=args.feather,
seed=args.seed, crf=args.crf, keep_audio=args.keep_audio, quiet=args.quiet)
render(cfg)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|