Videoeditor / features /reframe.py
Transfer Bot
Moved to Hugging Face automatically
6fbf602
Raw History Blame Contribute Delete
13.1 kB
# ==========================================================================
# features/reframe.py — قاب‌بندی خودکار (مثلاً ویدیوی افقی در قاب عمودی)
# --------------------------------------------------------------------------
# ۱) سوژه پیدا می‌شود: چهره (YuNet)؛ اگر چهره کم بود، آدم (RVM)؛ و در نبود
# آدم، برجسته‌ترین بخش تصویر (saliency).
# ۲) مثل یک فیلم‌بردار: اگر سوژه با یک قاب ثابت جا می‌شود دوربین ثابت می‌ماند؛
# وگرنه نرم و بدون لرزش دنبالش می‌کند. در تغییر صحنه‌ها دوربین می‌پرد.
# ۳) نتیجه کلیدفریم‌های جابه‌جایی کلیپ است (قابل ویرایش در برنامه).
# ==========================================================================
import math
import numpy as np
from core.jobs import UserError
from features import tool
from features._common import media_rec, clamp_range, num, model_path, ort_session, FrameReader, fit_size
def _available():
try:
import cv2 # noqa: F401
return hasattr(cv2, "FaceDetectorYN")
except Exception:
return False
# --------------------------------------------------------------------------
# تبدیل مختصات: فریم منبع ↔ مختصات محلی کلیپ (بعد از چرخش، برش و قرینه)
# دقیقاً همان کاری که سایه‌زن پیش‌نمایش انجام می‌دهد.
# --------------------------------------------------------------------------
class Mapper:
def __init__(self, params):
self.rot = int(num(params.get("rot90"), 0, 0, 3)) % 4
c = params.get("crop") if isinstance(params.get("crop"), dict) else {}
self.cx = num(c.get("x"), 0, 0, 1)
self.cy = num(c.get("y"), 0, 0, 1)
self.cw = num(c.get("w"), 1, 0.02, 1)
self.ch = num(c.get("h"), 1, 0.02, 1)
self.fx = bool(params.get("fx"))
self.fy = bool(params.get("fy"))
def to_local(self, sx, sy):
r = self.rot
if r == 0:
dx, dy = sx, sy
elif r == 1:
dx, dy = 1 - sy, sx
elif r == 2:
dx, dy = 1 - sx, 1 - sy
else:
dx, dy = sy, 1 - sx
lx, ly = (dx - self.cx) / self.cw, (dy - self.cy) / self.ch
if self.fx:
lx = 1 - lx
if self.fy:
ly = 1 - ly
return lx, ly
def to_source(self, lx, ly):
if self.fx:
lx = 1 - lx
if self.fy:
ly = 1 - ly
dx, dy = self.cx + lx * self.cw, self.cy + ly * self.ch
r = self.rot
if r == 0:
return dx, dy
if r == 1:
return dy, 1 - dx
if r == 2:
return 1 - dx, 1 - dy
return 1 - dy, dx
def size_to_source(self, lw, lh):
dw, dh = lw * self.cw, lh * self.ch
return (dh, dw) if self.rot % 2 == 1 else (dw, dh)
def content_dims(self, w, h):
if self.rot % 2 == 1:
w, h = h, w
return w * self.cw, h * self.ch
# --------------------------------------------------------------------------
# پیدا کردن سوژه
# --------------------------------------------------------------------------
def _gauss_smooth(y, sigma):
if sigma <= 0 or len(y) < 3:
return np.asarray(y, dtype=np.float64)
r = int(math.ceil(sigma * 3))
k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)
k /= k.sum()
yp = np.pad(np.asarray(y, dtype=np.float64), (r, r), mode="edge")
return np.convolve(yp, k, mode="valid")
def _fill(vals):
"""پر کردن جاهای خالی (None) با درون‌یابی خطی؛ لبه‌ها با نزدیک‌ترین مقدار"""
idx = [i for i, v in enumerate(vals) if v is not None]
if not idx:
return None
x = np.arange(len(vals))
return np.interp(x, idx, [vals[i] for i in idx])
def _rdp(pts, eps):
"""ساده‌سازی مسیر (Ramer–Douglas–Peucker)"""
if len(pts) < 3:
return pts
a, b = np.array(pts[0]), np.array(pts[-1])
ab = b - a
nrm = math.hypot(*ab) or 1e-9
best, bi = -1.0, 0
for i in range(1, len(pts) - 1):
p = np.array(pts[i])
d = abs(ab[0] * (a[1] - p[1]) - ab[1] * (a[0] - p[0])) / nrm
if d > best:
best, bi = d, i
if best > eps:
return _rdp(pts[:bi + 1], eps)[:-1] + _rdp(pts[bi:], eps)
return [pts[0], pts[-1]]
def _camera(u, sfps, view, axis_target=0.5):
"""مسیر دوربین (مرکز پنجره‌ی دید، در مختصات محلی) برای یک صحنه
u: موقعیت سوژه در هر نمونه؛ view: عرض پنجره‌ی دید (کسری از کل)"""
u = np.asarray(u, dtype=np.float64)
lo, hi = np.percentile(u, 5), np.percentile(u, 95)
if hi - lo <= 0.62 * view:
# دوربین ثابت: همه‌ی حرکت سوژه در قاب جا می‌شود
c = (hi + lo) / 2.0
return np.full_like(u, c)
s = _gauss_smooth(u, sigma=max(1.0, 0.5 * sfps))
# ناحیه‌ی امن: تا وقتی سوژه نزدیک مرکز است دوربین تکان نمی‌خورد
dead = 0.14 * view
cam = np.empty_like(s)
c = s[0]
for i, x in enumerate(s):
if x > c + dead:
c = x - dead
elif x < c - dead:
c = x + dead
cam[i] = c
return _gauss_smooth(cam, sigma=max(1.0, 0.7 * sfps))
@tool("reframe", "قاب‌بندی خودکار", kind="ai", needs=_available, remote=True)
def reframe(job, params, owner):
import cv2
rec, src = media_rec(params.get("mid"), ("video",))
t0, t1 = clamp_range(rec, params.get("t0"), params.get("t1"), max_len=60 * 60)
span = max(0.05, t1 - t0)
dur = num(params.get("dur"), 0, 0, 1e6) or span / num(params.get("speed"), 1, 0.05, 16)
A = num(params.get("aspect"), 9 / 16.0, 0.1, 10)
mp = Mapper(params)
VW, VH = float(rec.get("w") or 1280), float(rec.get("h") or 720)
cw, ch = mp.content_dims(VW, VH)
ca = cw / ch
if abs(ca - A) / A < 0.03:
raise UserError("نسبت ابعاد این کلیپ با قاب یکی است و چیزی بیرون قاب نمی‌ماند.")
horiz = ca > A
view = A / ca if horiz else ca / A # عرض/ارتفاع پنجره‌ی دید در مختصات محلی
ratio = 1.0 / view # w/W یا h/H
sfps = 6.0 if span <= 180 else (3.0 if span <= 900 else 1.5)
aw, ah = fit_size(VW, VH, max_side=640)
job.update(0.03, "analyze", "پیدا کردن سوژه")
det = cv2.FaceDetectorYN.create(model_path("yunet", job), "", (aw, ah), 0.62, 0.3, 30)
det.setInputSize((aw, ah))
times, faces, cuts, smalls = [], [], [], []
prev_small = None
total = max(1, int(span * sfps))
rd = FrameReader(src["path"], (aw, ah), t0=t0, t1=t1, fps=f"{sfps:.4f}", hdr=bool(src.get("hdr")), cm=src.get("cm"))
try:
for i, fr in enumerate(rd):
job.check()
t = t0 + i / sfps
bgr = np.ascontiguousarray(fr[..., ::-1])
_, ff_ = det.detect(bgr)
lst = []
if ff_ is not None:
for f in ff_:
x, y, w, h, sc = float(f[0]), float(f[1]), float(f[2]), float(f[3]), float(f[14])
if w * h < 64:
continue
lst.append(((x + w / 2) / aw, (y + h / 2) / ah, w / aw, h / ah, sc))
sm = cv2.resize(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY), (64, 36), interpolation=cv2.INTER_AREA).astype(np.float32)
if prev_small is not None and float(np.mean(np.abs(sm - prev_small))) > 38:
cuts.append(len(times))
prev_small = sm
times.append(t)
faces.append(lst)
smalls.append(cv2.resize(fr, (192, max(2, int(192 * ah / aw))), interpolation=cv2.INTER_AREA))
if i % 4 == 0:
job.update(0.03 + 0.6 * min(1.0, i / float(total)), "analyze", "پیدا کردن سوژه")
finally:
rd.close()
n = len(times)
if n == 0:
raise UserError("فریمی از ویدیو خوانده نشد.")
# انتخاب سوژه‌ی اصلی با پیوستگی زمانی (از بین چند چهره، همانی که دنبالش بودیم)
seg_bounds = [0] + [c for c in cuts if 0 < c < n] + [n]
pos = [None] * n
kind = "face"
with_faces = sum(1 for f in faces if f)
for a, b in zip(seg_bounds[:-1], seg_bounds[1:]):
prev = None
for i in range(a, b):
best, bs = None, -1.0
for (x, y, w, h, sc) in faces[i]:
score = (w * h) ** 0.5 * sc
if prev is not None:
d2 = (x - prev[0]) ** 2 + (y - prev[1]) ** 2
score *= 1.0 + 2.5 * math.exp(-d2 / (2 * 0.12 ** 2))
if score > bs:
bs, best = score, (x, y, w, h)
if best is not None:
prev = best
# نقطه‌ی هدف: کمی پایین‌تر از مرکز چهره (چهره + شانه‌ها)
pos[i] = (best[0], best[1] + best[3] * 0.35)
# بدون چهره ⇒ آدم (RVM) ⇒ بخش برجسته
if with_faces < 0.35 * n:
job.update(0.66, "analyze", "پیدا کردن آدم‌ها")
kind = "person"
try:
sess = ort_session(model_path("rvm", job))
r = [np.zeros((1, 1, 1, 1), np.float32)] * 4
for i, sm in enumerate(smalls):
job.check()
if i in cuts:
r = [np.zeros((1, 1, 1, 1), np.float32)] * 4
x = (sm.astype(np.float32) / 255.0).transpose(2, 0, 1)[None]
outs = sess.run(None, {"src": x, "r1i": r[0], "r2i": r[1], "r3i": r[2], "r4i": r[3],
"downsample_ratio": np.array([1.0], np.float32)})
r = list(outs[2:6])
a = outs[1][0, 0]
m = a > 0.4
if pos[i] is None and m.mean() > 0.01:
ys, xs = np.nonzero(m)
wts = a[ys, xs]
top, bot = ys.min(), ys.max()
cx = float((xs * wts).sum() / wts.sum()) / a.shape[1]
cy = (top + 0.22 * (bot - top)) / float(a.shape[0])
pos[i] = (cx, cy)
except UserError:
pass
if sum(1 for p in pos if p is not None) < 0.3 * n:
kind = "salient"
sal = cv2.saliency.StaticSaliencySpectralResidual_create() if hasattr(cv2, "saliency") else None
gy, gx = np.mgrid[0:36, 0:64]
prior = np.exp(-(((gx / 63.0 - 0.5) ** 2) + ((gy / 35.0 - 0.5) ** 2)) / (2 * 0.3 ** 2))
for i, sm in enumerate(smalls):
if pos[i] is not None:
continue
g = cv2.resize(cv2.cvtColor(sm, cv2.COLOR_RGB2GRAY), (64, 36), interpolation=cv2.INTER_AREA)
mapv = None
if sal is not None:
ok, mapv = sal.computeSaliency(g)
if not ok:
mapv = None
if mapv is None:
continue
wmap = (mapv.astype(np.float64) ** 2) * prior
s = wmap.sum()
if s <= 1e-9:
continue
pos[i] = (float((wmap * gx).sum() / s) / 63.0, float((wmap * gy).sum() / s) / 35.0)
# مختصات محلی کلیپ
loc = [mp.to_local(p[0], p[1]) if p is not None else None for p in pos]
comp = [(l[0] if horiz else l[1]) if l is not None else None for l in loc]
if all(c is None for c in comp):
return {"kf": None}
target = 0.5 if horiz else 0.42
lo_v, hi_v = 1 - ratio / 2.0, ratio / 2.0
def tfv(c):
return float(min(hi_v, max(lo_v, target + (0.5 - c) * ratio)))
def tau(t):
return max(0.0, min(dur, (t - t0) / span * dur))
keys = []
for si, (a, b) in enumerate(zip(seg_bounds[:-1], seg_bounds[1:])):
seg = _fill(comp[a:b])
if seg is None:
seg = np.full(b - a, 0.5)
cam = _camera(seg, sfps, view)
vals = [tfv(c) for c in cam]
pts = [(tau(times[a + k]), vals[k]) for k in range(len(vals))]
if b < n:
pts.append((max(pts[-1][0], tau(times[b]) - 0.001), vals[-1]))
pts = _rdp(pts, 0.004)
for (t, v) in pts:
if keys and t <= keys[-1]["t"]:
t = keys[-1]["t"] + 0.001
keys.append({"t": round(t, 3), "v": round(v, 4), "e": "linear"})
if len(keys) == 1 or max(k["v"] for k in keys) - min(k["v"] for k in keys) < 1e-3:
keys = [{"t": 0.0, "v": keys[0]["v"], "e": "linear"}]
job.update(0.98, "done", "")
return {"kf": {"x" if horiz else "y": keys[:2000]}, "subject": kind}