|
@@ -0,0 +1,266 @@
|
|
|
|
|
+# -*- coding: utf-8 -*-
|
|
|
|
|
+"""R9 红队二期:语义级逃逸候选的本地多空间距离验证。
|
|
|
|
|
+前提(用户实测裁决):快手判重=发布后异步、语义嵌入级、几何不变、幻影免疫。
|
|
|
|
|
+故本实验的度量目标不是"断 pHash",而是"断语义嵌入代理空间"。
|
|
|
|
|
+
|
|
|
|
|
+生成候选(源=77e9...mp4 前10s)→ 模拟快手转码(-r30 crf23)→ 在 .ks 面上测:
|
|
|
|
|
+ pham pHash 距离(低频 DCT 空间)
|
|
|
|
|
+ ssim 结构相似(像素空间,逆)
|
|
|
|
|
+ emd RGB 直方图 Wasserstein/3通道(色彩分布空间)
|
|
|
|
|
+ d_cnn 随机权重 CNN 多层 GAP 拼接嵌入余弦距离(深度特征代理空间)
|
|
|
|
|
+ flow 光流场差异(cos/nrmse,运动结构空间)
|
|
|
|
|
+ sift SIFT 匹配数(几何不变/手性敏感的局部特征对照)
|
|
|
|
|
+结果写 results_r9.json,样本存 samples/。
|
|
|
|
|
+用法: python -X utf8 R9_run.py
|
|
|
|
|
+"""
|
|
|
|
|
+import json, os, subprocess, sys
|
|
|
|
|
+import numpy as np
|
|
|
|
|
+
|
|
|
|
|
+sys.stdout.reconfigure(encoding="utf-8")
|
|
|
|
|
+W = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
+SMPL = os.path.join(W, "samples"); os.makedirs(SMPL, exist_ok=True)
|
|
|
|
|
+SRC = "D:/bbcHelp/77e9a462b481df8feba6b551925b8cc0.mp4"
|
|
|
|
|
+TS = [1.0, 3.0, 5.0, 7.0, 9.0] # 候选输出时间轴采样
|
|
|
|
|
+FLOW_PAIRS = [(1.0, 1.4), (5.0, 5.4), (7.0, 7.4)]
|
|
|
|
|
+SIFT_T = 2.0 # SIFT 用的输出时间轴时刻
|
|
|
|
|
+X264 = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p"]
|
|
|
|
|
+AAC = ["-c:a", "aac", "-b:a", "128k"]
|
|
|
|
|
+
|
|
|
|
|
+# ---------------- 候选定义 ----------------
|
|
|
|
|
+CANDS = [
|
|
|
|
|
+ dict(name="REF", desc="基线:同源重编码(零距离锚点)",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC, *X264, *AAC, o]),
|
|
|
|
|
+ dict(name="V1_mirror", desc="纯水平镜像",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC,
|
|
|
|
|
+ "-vf", "hflip", *X264, *AAC, o]),
|
|
|
|
|
+ dict(name="V2_mirror_geo", desc="镜像+几何深改(crop12%+旋转1°+渐晕+hue8)",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC,
|
|
|
|
|
+ "-vf", "hflip,crop=478:845:33:57,scale=544:960:flags=lanczos,"
|
|
|
|
|
+ "rotate=1.0*PI/180:ow=iw:oh=ih:bilinear=1,crop=520:918:12:21,"
|
|
|
|
|
+ "scale=544:960:flags=bicubic,vignette=PI/9,hue=h=8",
|
|
|
|
|
+ *X264, *AAC, o]),
|
|
|
|
|
+ dict(name="V3_pip", desc="画中画0.75(前景缩至75%,背景=自放大模糊)",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC,
|
|
|
|
|
+ "-filter_complex",
|
|
|
|
|
+ "[0:v]split=2[bg][fg];"
|
|
|
|
|
+ "[bg]scale=726:1280:flags=bicubic,crop=544:960,boxblur=20:2[bgb];"
|
|
|
|
|
+ "[fg]scale=408:720:flags=bicubic[fgs];"
|
|
|
|
|
+ "[bgb][fgs]overlay=(W-w)/2:(H-h)/2[v]",
|
|
|
|
|
+ "-map", "[v]", *X264, *AAC, o]),
|
|
|
|
|
+ dict(name="V4_temporal", desc="镜像+时序重排(掐头0.8s+删中段4.5~6.5s+拼接)",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-i", SRC,
|
|
|
|
|
+ "-filter_complex",
|
|
|
|
|
+ "[0:v]trim=0.8:4.5,setpts=PTS-STARTPTS[v1];[0:a]atrim=0.8:4.5,asetpts=PTS-STARTPTS[a1];"
|
|
|
|
|
+ "[0:v]trim=6.5:12.3,setpts=PTS-STARTPTS[v2];[0:a]atrim=6.5:12.3,asetpts=PTS-STARTPTS[a2];"
|
|
|
|
|
+ "[v1][a1][v2][a2]concat=n=2:v=1:a=1[vc][ac];[vc]hflip[v]",
|
|
|
|
|
+ "-map", "[v]", "-map", "[ac]", *X264, *AAC, o],
|
|
|
|
|
+ # 输出t ↔ 源t 的映射(无变速,分段平移)
|
|
|
|
|
+ tmap=lambda t: t + 0.8 if t < 3.7 else t + 2.8),
|
|
|
|
|
+ dict(name="V5_occlude", desc="遮挡贴纸(顶部半透明白条80px+右上色块140x90+底部黑条180px@0.85,覆盖~27%)",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC,
|
|
|
|
|
+ "-vf", "drawbox=x=0:y=0:w=544:h=80:color=white@0.5:t=fill,"
|
|
|
|
|
+ "drawbox=x=390:y=40:w=140:h=90:color=0x22AADD@0.92:t=fill,"
|
|
|
|
|
+ "drawbox=x=0:y=780:w=544:h=180:color=black@0.85:t=fill",
|
|
|
|
|
+ *X264, *AAC, o]),
|
|
|
|
|
+ dict(name="V6_night", desc="对照:昼夜风格化(亮度-0.22/饱和0.55/蓝色迁移)纯色彩攻击",
|
|
|
|
|
+ args=lambda o: ["ffmpeg", "-v", "error", "-y", "-t", "10", "-i", SRC,
|
|
|
|
|
+ "-vf", "eq=brightness=-0.22:contrast=0.85:saturation=0.55:gamma=0.9,"
|
|
|
|
|
+ "colorchannelmixer=rr=0.72:rb=0.16:br=0.22:bb=0.78",
|
|
|
|
|
+ *X264, *AAC, o]),
|
|
|
|
|
+]
|
|
|
|
|
+
|
|
|
|
|
+# ---------------- 指标 ----------------
|
|
|
|
|
+def _dct(n=32):
|
|
|
|
|
+ k = np.arange(n)[:, None]; x = np.arange(n)[None, :]
|
|
|
|
|
+ D = np.cos(np.pi * (2 * x + 1) * k / (2 * n))
|
|
|
|
|
+ D[0] *= 1 / np.sqrt(2); D *= np.sqrt(2 / n)
|
|
|
|
|
+ return D
|
|
|
|
|
+_D = _dct()
|
|
|
|
|
+
|
|
|
|
|
+def phash(gray):
|
|
|
|
|
+ small = gray.reshape(32, 30, 32, 17).mean(axis=(1, 3))
|
|
|
|
|
+ d = _D @ small @ _D.T
|
|
|
|
|
+ low = d[:8, :8].flatten(); med = np.median(low[1:])
|
|
|
|
|
+ return (low > med)
|
|
|
|
|
+
|
|
|
|
|
+def pham(h1, h2):
|
|
|
|
|
+ return float(np.count_nonzero(h1 != h2)) / 64.0
|
|
|
|
|
+
|
|
|
|
|
+_gk = np.exp(-0.5 * (np.arange(-5, 6) / 1.5) ** 2); _gk /= _gk.sum()
|
|
|
|
|
+def _blur(m):
|
|
|
|
|
+ t = np.apply_along_axis(lambda r: np.convolve(r, _gk, "valid"), 1, m)
|
|
|
|
|
+ return np.apply_along_axis(lambda c: np.convolve(c, _gk, "valid"), 0, t)
|
|
|
|
|
+
|
|
|
|
|
+def ssim(a, b):
|
|
|
|
|
+ a = a.astype(np.float64); b = b.astype(np.float64)
|
|
|
|
|
+ C1, C2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2
|
|
|
|
|
+ mu1, mu2 = _blur(a), _blur(b)
|
|
|
|
|
+ s11 = _blur(a * a) - mu1 * mu1; s22 = _blur(b * b) - mu2 * mu2; s12 = _blur(a * b) - mu1 * mu2
|
|
|
|
|
+ m = ((2 * mu1 * mu2 + C1) * (2 * s12 + C2)) / ((mu1 ** 2 + mu2 ** 2 + C1) * (s11 + s22 + C2))
|
|
|
|
|
+ return float(m.mean())
|
|
|
|
|
+
|
|
|
|
|
+def read_frame(video, t, fmt): # fmt: gray|rgb24
|
|
|
|
|
+ raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{t:.3f}", "-i", video,
|
|
|
|
|
+ "-frames:v", "1", "-vf", "scale=544:960", "-f", "rawvideo", "-pix_fmt", fmt, "-"],
|
|
|
|
|
+ capture_output=True).stdout
|
|
|
|
|
+ if fmt == "gray":
|
|
|
|
|
+ g = np.frombuffer(raw, np.uint8)
|
|
|
|
|
+ assert g.size >= 544 * 960, f"gray帧异常 {video}@{t}"
|
|
|
|
|
+ return g[:544 * 960].reshape(960, 544).astype(np.float32)
|
|
|
|
|
+ else:
|
|
|
|
|
+ g = np.frombuffer(raw, np.uint8)
|
|
|
|
|
+ assert g.size >= 544 * 960 * 3
|
|
|
|
|
+ return g[:544 * 960 * 3].reshape(960, 544, 3)
|
|
|
|
|
+
|
|
|
|
|
+def emd_rgb(a, b):
|
|
|
|
|
+ """两帧 RGB 直方图 Wasserstein-1 距离(64bin,逐通道均值)"""
|
|
|
|
|
+ from scipy.stats import wasserstein_distance
|
|
|
|
|
+ centers = (np.arange(64) + 0.5) * 255 / 64
|
|
|
|
|
+ tot = 0.0
|
|
|
|
|
+ for c in range(3):
|
|
|
|
|
+ ha, _ = np.histogram(a[:, :, c], bins=64, range=(0, 255), density=False)
|
|
|
|
|
+ hb, _ = np.histogram(b[:, :, c], bins=64, range=(0, 255), density=False)
|
|
|
|
|
+ ha = ha / ha.sum(); hb = hb / hb.sum()
|
|
|
|
|
+ tot += wasserstein_distance(centers, centers, ha, hb)
|
|
|
|
|
+ return tot / 3.0
|
|
|
|
|
+
|
|
|
|
|
+# ---- 随机权重 CNN 深度特征代理(固定种子,可复现) ----
|
|
|
|
|
+import torch, torch.nn as nn
|
|
|
|
|
+
|
|
|
|
|
+def make_proxy_net(seed=7):
|
|
|
|
|
+ torch.manual_seed(seed)
|
|
|
|
|
+ net = nn.Sequential(
|
|
|
|
|
+ nn.Conv2d(3, 16, 3, stride=2, padding=1), nn.ReLU(), # 112
|
|
|
|
|
+ nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU(), # 56
|
|
|
|
|
+ nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), # 28
|
|
|
|
|
+ nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), # 14
|
|
|
|
|
+ nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.ReLU(), # 7
|
|
|
|
|
+ )
|
|
|
|
|
+ with torch.no_grad():
|
|
|
|
|
+ for m in net.modules():
|
|
|
|
|
+ if isinstance(m, nn.Conv2d):
|
|
|
|
|
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
|
|
|
|
|
+ m.bias.zero_()
|
|
|
|
|
+ net.eval()
|
|
|
|
|
+ return net
|
|
|
|
|
+
|
|
|
|
|
+_NET = make_proxy_net()
|
|
|
|
|
+
|
|
|
|
|
+def cnn_feats(rgb):
|
|
|
|
|
+ """rgb uint8 544x960x3 → (GAP拼接向量, 2x2网格池化拼接向量),均归一化。
|
|
|
|
|
+ GAP 对空间置换(含镜像)近乎不变——模拟"纯内容统计"型嵌入;
|
|
|
|
|
+ 网格池化保留位置结构——模拟 CLIP/ViT 类位置敏感嵌入。"""
|
|
|
|
|
+ import cv2
|
|
|
|
|
+ x = cv2.resize(rgb, (224, 224)).astype(np.float32) / 255.0
|
|
|
|
|
+ x = (x - 0.5) / 0.5
|
|
|
|
|
+ t = torch.from_numpy(x.transpose(2, 0, 1))[None]
|
|
|
|
|
+ gaps, grids = [], []
|
|
|
|
|
+ h = t
|
|
|
|
|
+ with torch.no_grad():
|
|
|
|
|
+ for m in _NET:
|
|
|
|
|
+ h = m(h)
|
|
|
|
|
+ if isinstance(m, nn.ReLU):
|
|
|
|
|
+ v = h.mean(dim=(2, 3))[0]
|
|
|
|
|
+ gaps.append(v / (v.norm() + 1e-8))
|
|
|
|
|
+ C, Hh, Ww = h.shape[1], h.shape[2], h.shape[3]
|
|
|
|
|
+ g = torch.nn.functional.avg_pool2d(h, (Hh // 2, Ww // 2)).flatten()
|
|
|
|
|
+ grids.append(g / (g.norm() + 1e-8))
|
|
|
|
|
+ eg = torch.cat(gaps); er = torch.cat(grids)
|
|
|
|
|
+ return (eg / (eg.norm() + 1e-8)).numpy(), (er / (er.norm() + 1e-8)).numpy()
|
|
|
|
|
+
|
|
|
|
|
+def cos_dist(a, b):
|
|
|
|
|
+ return float(1.0 - np.dot(a, b))
|
|
|
|
|
+
|
|
|
|
|
+# ---- 光流场差异 ----
|
|
|
|
|
+def flow_pair(video, t0, t1):
|
|
|
|
|
+ import cv2
|
|
|
|
|
+ a = read_frame(video, t0, "gray"); b = read_frame(video, t1, "gray")
|
|
|
|
|
+ a = cv2.resize(a, (272, 480)).astype(np.uint8); b = cv2.resize(b, (272, 480)).astype(np.uint8)
|
|
|
|
|
+ return cv2.calcOpticalFlowFarneback(a, b, None, 0.5, 3, 15, 3, 5, 1.2, 0)
|
|
|
|
|
+
|
|
|
|
|
+def flow_metrics(fs, fc):
|
|
|
|
|
+ mag = np.linalg.norm(fs, axis=2)
|
|
|
|
|
+ mask = mag > 0.6
|
|
|
|
|
+ if mask.sum() < 100: return dict(flow_cos=0.0, flow_nrmse=1.0, mov_frac=float(mask.mean()))
|
|
|
|
|
+ s = fs[mask]; c = fc[mask]
|
|
|
|
|
+ dot = (s * c).sum(1); n = np.linalg.norm(s, axis=1) * np.linalg.norm(c, axis=1) + 1e-8
|
|
|
|
|
+ cosv = float((dot / n).mean())
|
|
|
|
|
+ nrmse = float(np.linalg.norm(s - c, axis=1).mean() / (mag[mask].mean() + 1e-8))
|
|
|
|
|
+ return dict(flow_cos=cosv, flow_nrmse=nrmse, mov_frac=float(mask.mean()))
|
|
|
|
|
+
|
|
|
|
|
+# ---- SIFT 匹配(几何不变/手性敏感对照) ----
|
|
|
|
|
+def sift_matches(ga, gb):
|
|
|
|
|
+ import cv2
|
|
|
|
|
+ sift = cv2.SIFT_create(nfeatures=2000)
|
|
|
|
|
+ ka, da = sift.detectAndCompute(ga.astype(np.uint8), None)
|
|
|
|
|
+ kb, db = sift.detectAndCompute(gb.astype(np.uint8), None)
|
|
|
|
|
+ if da is None or db is None: return 0, 0
|
|
|
|
|
+ bf = cv2.BFMatcher()
|
|
|
|
|
+ m = bf.knnMatch(da, db, k=2)
|
|
|
|
|
+ good = [x for x, y in m if x.distance < 0.75 * y.distance]
|
|
|
|
|
+ return len(good), min(len(ka), len(kb))
|
|
|
|
|
+
|
|
|
|
|
+# ---------------- 主流程 ----------------
|
|
|
|
|
+def run(cmd, tag):
|
|
|
|
|
+ r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
|
|
|
+ if r.returncode != 0:
|
|
|
|
|
+ print(f"[FAIL {tag}] {r.stderr[-1200:]}"); return False
|
|
|
|
|
+ return True
|
|
|
|
|
+
|
|
|
|
|
+def main():
|
|
|
|
|
+ _gray_cache, _rgb_cache, _flw_cache = {}, {}, {}
|
|
|
|
|
+ def gsrc(t):
|
|
|
|
|
+ if t not in _gray_cache:
|
|
|
|
|
+ _gray_cache[t] = read_frame(SRC, t, "gray")
|
|
|
|
|
+ _rgb_cache[t] = read_frame(SRC, t, "rgb24")
|
|
|
|
|
+ return _gray_cache[t], _rgb_cache[t]
|
|
|
|
|
+ def fsrc(t0, t1):
|
|
|
|
|
+ if (t0, t1) not in _flw_cache:
|
|
|
|
|
+ _flw_cache[(t0, t1)] = flow_pair(SRC, t0, t1)
|
|
|
|
|
+ return _flw_cache[(t0, t1)]
|
|
|
|
|
+ results = []
|
|
|
|
|
+ for cand in CANDS:
|
|
|
|
|
+ name = cand["name"]; tmap = cand.get("tmap", lambda t: t)
|
|
|
|
|
+ out = os.path.join(SMPL, name + ".mp4"); ks = os.path.join(SMPL, name + ".ks.mp4")
|
|
|
|
|
+ print(f"[gen] {name}: {cand['desc']}", flush=True)
|
|
|
|
|
+ if not (os.path.exists(out) and os.environ.get("SKIP_GEN") != "1"):
|
|
|
|
|
+ if not run(cand["args"](out), name): continue
|
|
|
|
|
+ if not run(["ffmpeg", "-v", "error", "-y", "-i", out, "-r", "30",
|
|
|
|
|
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
|
|
|
|
|
+ "-c:a", "aac", "-b:a", "128k", ks], name + ".ks"):
|
|
|
|
|
+ continue
|
|
|
|
|
+ row = dict(name=name, desc=cand["desc"])
|
|
|
|
|
+ phs, sss, emds, dgs, drs = [], [], [], [], []
|
|
|
|
|
+ for t in TS:
|
|
|
|
|
+ gc = read_frame(ks, t, "gray"); rc = read_frame(ks, t, "rgb24")
|
|
|
|
|
+ gs, rs = gsrc(tmap(t))
|
|
|
|
|
+ phs.append(pham(phash(gc), phash(gs)))
|
|
|
|
|
+ sss.append(ssim(gc, gs)); emds.append(emd_rgb(rc, rs))
|
|
|
|
|
+ eg_c, er_c = cnn_feats(rc); eg_s, er_s = cnn_feats(rs)
|
|
|
|
|
+ dgs.append(cos_dist(eg_c, eg_s)); drs.append(cos_dist(er_c, er_s))
|
|
|
|
|
+ row.update(ph=round(float(np.mean(phs)), 4), ph_all=[round(x, 3) for x in phs],
|
|
|
|
|
+ ssim=round(float(np.mean(sss)), 4), emd=round(float(np.mean(emds)), 2),
|
|
|
|
|
+ d_gap=round(float(np.mean(dgs)), 4), d_gap_all=[round(x, 3) for x in dgs],
|
|
|
|
|
+ d_grid=round(float(np.mean(drs)), 4), d_grid_all=[round(x, 3) for x in drs])
|
|
|
|
|
+ fcs, frs = [], []
|
|
|
|
|
+ for (t0, t1) in FLOW_PAIRS:
|
|
|
|
|
+ fc = flow_pair(ks, t0, t1)
|
|
|
|
|
+ m = flow_metrics(fsrc(tmap(t0), tmap(t1)), fc)
|
|
|
|
|
+ fcs.append(m["flow_cos"]); frs.append(m["flow_nrmse"])
|
|
|
|
|
+ row.update(flow_cos=round(float(np.mean(fcs)), 4), flow_nrmse=round(float(np.mean(frs)), 4))
|
|
|
|
|
+ # SIFT:源帧 vs 候选帧(内容对齐时刻)
|
|
|
|
|
+ gs_, _ = gsrc(tmap(SIFT_T))
|
|
|
|
|
+ gc_ = read_frame(ks, SIFT_T, "gray")
|
|
|
|
|
+ ngood, nkp = sift_matches(gs_, gc_)
|
|
|
|
|
+ row.update(sift_good=ngood, sift_kp=nkp,
|
|
|
|
|
+ sift_ratio=round(ngood / max(nkp, 1), 3))
|
|
|
|
|
+ results.append(row)
|
|
|
|
|
+ print(f" -> ph={row['ph']} ssim={row['ssim']} emd={row['emd']} d_gap={row['d_gap']} "
|
|
|
|
|
+ f"d_grid={row['d_grid']} flowcos={row['flow_cos']} flownrmse={row['flow_nrmse']} "
|
|
|
|
|
+ f"sift={ngood}/{nkp}", flush=True)
|
|
|
|
|
+ with open(os.path.join(W, "results_r9.json"), "w", encoding="utf-8") as f:
|
|
|
|
|
+ json.dump(results, f, ensure_ascii=False, indent=1)
|
|
|
|
|
+ print("DONE")
|
|
|
|
|
+
|
|
|
|
|
+if __name__ == "__main__":
|
|
|
|
|
+ main()
|