EYBX-processed / code /lum_scan.py
teawhite's picture
Add files using upload-large-folder tool
8ba5a96 verified
Raw History Blame Contribute Delete
5.58 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
lum_scan.py —— 全片逐帧亮度扫描(单次解码,流式)
为什么要全量而不是抽样:后面三件事都依赖逐帧亮度
1. 对齐:传送时「掉黑」那一帧是把日志 vt 钉到视频时间轴的信号
2. D2:帧均值 < 6 的低照度过滤
3. 传送窗口复核:确认固定余量 [leg_end-1.0, leg_start+1.5] 真的盖住了黑屏+加载页
度量必须与交付规格一致:`scale=64:36` + bicubic + gray,然后取整帧均值。
换成别的缩放尺寸/插值,暗场景的读数会系统性偏移,D2 的阈值 6 就不再是同一个 6。
产出 <out>/<session>/lum.npz:
mean float32[N] 逐帧 64x36 灰度均值 (0-255)
p95 float32[N] 逐帧 64x36 灰度 95 分位(配合 max 判「真·全黑」)
mx uint8[N] 逐帧最大值
diff float32[N] 与前一帧的平均绝对差(diff[0]=nan),粗粒度重复帧信号
fps, n_frames
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import time
import numpy as np
W, H = 64, 36
FRAME_BYTES = W * H
def probe(path: str) -> dict:
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")
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),
nb_frames=int(v.get("nb_frames") or 0),
duration=float(info["format"].get("duration", 0) or 0))
def scan(path: str, threads: int = 8, chunk_frames: int = 512, report_every: int = 60.0):
info = probe(path)
fps = info["fps"]
est = info["nb_frames"] or int(info["duration"] * fps)
cmd = ["ffmpeg", "-v", "error", "-threads", str(threads), "-i", path,
"-vf", f"scale={W}:{H}:flags=bicubic,format=gray",
"-f", "rawvideo", "-pix_fmt", "gray", "-"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=FRAME_BYTES * chunk_frames)
means, p95s, mxs, diffs = [], [], [], []
prev = None
t0 = time.time()
last_report = t0
n = 0
want = FRAME_BYTES * chunk_frames
buf = b""
while True:
block = p.stdout.read(want)
if not block:
break
buf += block
k = len(buf) // FRAME_BYTES
if k == 0:
continue
arr = np.frombuffer(buf[:k * FRAME_BYTES], np.uint8).reshape(k, H * W)
buf = buf[k * FRAME_BYTES:]
a = arr.astype(np.float32)
means.append(a.mean(1))
p95s.append(np.percentile(a, 95, axis=1).astype(np.float32))
mxs.append(arr.max(1))
d = np.empty(k, np.float32)
if prev is None:
d[0] = np.nan
if k > 1:
d[1:] = np.abs(np.diff(a, axis=0)).mean(1)
else:
d[0] = np.abs(a[0] - prev).mean()
if k > 1:
d[1:] = np.abs(np.diff(a, axis=0)).mean(1)
diffs.append(d)
prev = a[-1]
n += k
now = time.time()
if now - last_report >= report_every:
el = now - t0
pct = 100.0 * n / est if est else 0.0
eta = (est - n) / max(n / el, 1e-9) if est else 0.0
print(f" {n:,}/{est:,} 帧 ({pct:.1f}%) · {n/el:.0f} fps · 已用 {el/60:.1f} min"
f" · 剩 {eta/60:.1f} min", flush=True)
last_report = now
p.stdout.close()
rc = p.wait()
if rc != 0:
print(f" [警告] ffmpeg 退出码 {rc}(多半是文件尾损坏,前面的帧仍然有效)", file=sys.stderr)
return dict(
mean=np.concatenate(means) if means else np.zeros(0, np.float32),
p95=np.concatenate(p95s) if p95s else np.zeros(0, np.float32),
mx=np.concatenate(mxs) if mxs else np.zeros(0, np.uint8),
diff=np.concatenate(diffs) if diffs else np.zeros(0, np.float32),
), fps, rc
def main():
ap = argparse.ArgumentParser(description="全片逐帧亮度扫描")
ap.add_argument("--raw", default="/data/zhiyangdeng/EYBXROAM")
ap.add_argument("--out", default="/data/zhiyangdeng/data_eybx/logs")
ap.add_argument("--sessions", nargs="*", default=None)
ap.add_argument("--threads", type=int, default=8)
args = ap.parse_args()
sessions = args.sessions or sorted(
d for d in os.listdir(args.raw)
if os.path.isdir(os.path.join(args.raw, d)) and d[0].isdigit())
for sid in sessions:
vid = os.path.join(args.raw, sid, "video.mp4")
dst = os.path.join(args.out, sid)
os.makedirs(dst, exist_ok=True)
print(f"== {sid} {os.path.getsize(vid)/1e9:.1f} GB")
t0 = time.time()
d, fps, rc = scan(vid, threads=args.threads)
n = d["mean"].size
np.savez_compressed(os.path.join(dst, "lum.npz"), fps=np.float64(fps),
n_frames=np.int64(n), ffmpeg_rc=np.int32(rc), **d)
el = time.time() - t0
m = d["mean"]
print(f" {n:,} 帧 @ {fps:.4f} fps = {n/fps/3600:.2f} h · 用时 {el/60:.1f} min "
f"({n/el:.0f} fps)")
print(f" 亮度 中位 {np.median(m):.1f} · <6 占 {100*(m<6).mean():.2f}% · "
f"<10 占 {100*(m<10).mean():.2f}% · <20 占 {100*(m<20).mean():.2f}%")
print("DONE")
if __name__ == "__main__":
main()