video_eval.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """回放评估:用 portcv evidence-v2 前视链路对 mp4 逐帧识别(L3 回放 / TP-SAFE-001 工具)。
  2. 产物(全部落在 runs/video_eval/,runs/ 已在 .gitignore 中):
  3. * <tag>.jsonl 每帧一行(候选状态 / 生产输出 / 诊断输出 / commit 证据)
  4. * <tag>_summary.json 状态分布、稳定区间、弃权原因统计
  5. * <tag>_annot_*.jpg 每个输出状态变化点的叠加图
  6. * <tag>_sheet.jpg 等间隔抽帧拼图
  7. 用法:
  8. python scripts/video_eval.py --video "D:\\clips\\a.mp4" --video "D:\\clips\\b.mp4"
  9. 口径:`require_commit` 取配置值(`configs/edge-v2-front.json`,生产口径),
  10. 逐帧复算与 `VisionPipeline.step` 的等价性由 `scripts/verify_equiv.py` 校验。
  11. 本脚本原在 `build/_video_eval.py`(`build/` 进 `.gitignore`,交付拿不到),
  12. 因 `docs/test_plan_gbt45163_5.md` 的 L3/TP-SAFE-001 依赖它,已迁到 `scripts/`。
  13. """
  14. import argparse
  15. import json
  16. import os
  17. import sys
  18. import time
  19. import cv2
  20. import numpy as np
  21. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  22. sys.path.insert(0, REPO)
  23. from portcv.config import load_config # noqa: E402
  24. from portcv.logic import TemporalVoter # noqa: E402
  25. from portcv.schema import STATE_LABELS # noqa: E402
  26. from portcv.service.pipeline import VisionPipeline # noqa: E402
  27. CONFIG = os.path.join(REPO, "configs", "edge-v2-front.json")
  28. def _tag(index, path):
  29. stem = os.path.splitext(os.path.basename(path))[0]
  30. ascii_part = "".join(ch for ch in stem if ch.isascii() and ch.isalnum())
  31. return "v%d_%s" % (index + 1, ascii_part[-6:] or "clip")
  32. def _distribution(rows, key):
  33. counts = {}
  34. for row in rows:
  35. value = int(row[key])
  36. counts[value] = counts.get(value, 0) + 1
  37. total = max(1, len(rows))
  38. return {
  39. str(k): {
  40. "label": STATE_LABELS.get(k, "unknown"),
  41. "frames": v,
  42. "ratio": round(v / total, 4),
  43. }
  44. for k, v in sorted(counts.items())
  45. }
  46. def _segments(rows, key, conf_key):
  47. out = []
  48. cur = None
  49. for row in rows:
  50. value = int(row[key])
  51. if cur is None or cur["state"] != value:
  52. cur = {
  53. "state": value,
  54. "label": STATE_LABELS.get(value, "unknown"),
  55. "start_i": row["i"],
  56. "start_ts": row["ts"],
  57. "end_i": row["i"],
  58. "end_ts": row["ts"],
  59. "frames": 0,
  60. "conf_sum": 0.0,
  61. }
  62. out.append(cur)
  63. cur["frames"] += 1
  64. cur["end_i"] = row["i"]
  65. cur["end_ts"] = row["ts"]
  66. cur["conf_sum"] += float(row.get(conf_key, 0.0))
  67. for seg in out:
  68. seg["duration_s"] = round(seg["end_ts"] - seg["start_ts"], 3)
  69. seg["conf_mean"] = round(seg["conf_sum"] / max(1, seg["frames"]), 3)
  70. del seg["conf_sum"]
  71. return out
  72. def _overlay(image, lines, color=(0, 255, 255)):
  73. canvas = image.copy()
  74. cv2.rectangle(canvas, (0, 0), (canvas.shape[1], 16 + 16 * len(lines)), (0, 0, 0), -1)
  75. for n, text in enumerate(lines):
  76. cv2.putText(canvas, text, (6, 14 + 16 * n), cv2.FONT_HERSHEY_SIMPLEX,
  77. 0.42, color, 1, cv2.LINE_AA)
  78. return canvas
  79. def _sheet(frames, path, cols=4):
  80. if not frames:
  81. return
  82. thumbs = []
  83. for _, image in frames:
  84. h, w = image.shape[:2]
  85. tw = 236
  86. thumbs.append(cv2.resize(image, (tw, int(round(h * tw / w))),
  87. interpolation=cv2.INTER_AREA))
  88. th = max(t.shape[0] for t in thumbs)
  89. rows = (len(thumbs) + cols - 1) // cols
  90. sheet = np.zeros((rows * (th + 18), cols * 236, 3), dtype="uint8")
  91. for n, (idx, _) in enumerate(frames):
  92. r, c = divmod(n, cols)
  93. tile = _overlay(thumbs[n], ["frame %d" % idx], (255, 255, 255))
  94. y0 = r * (th + 18)
  95. sheet[y0:y0 + tile.shape[0], c * 236:c * 236 + tile.shape[1]] = tile
  96. cv2.imwrite(path, sheet, [int(cv2.IMWRITE_JPEG_QUALITY), 82])
  97. def run_clip(index, path, out_dir, step, limit, sheet_n, annot_n, cfg_path, start_i=0):
  98. cfg = load_config(cfg_path)
  99. cfg.set_path("plc.enabled", False)
  100. cfg.set_path("run.save_on_change", False)
  101. cfg.set_path("run.preview", False)
  102. pipeline = VisionPipeline(cfg)
  103. pipeline.load()
  104. require_commit = bool(cfg.get_path("evidence_v2.require_commit", True))
  105. voter_prod = TemporalVoter.from_config(cfg)
  106. voter_diag = TemporalVoter.from_config(cfg)
  107. cap = cv2.VideoCapture(path)
  108. if not cap.isOpened():
  109. raise RuntimeError("无法打开视频: %s" % path)
  110. fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0)
  111. frames_total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
  112. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  113. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  114. tag = _tag(index, path)
  115. if start_i:
  116. cap.set(cv2.CAP_PROP_POS_FRAMES, int(start_i))
  117. rows = []
  118. sheet_slots = set()
  119. if frames_total and sheet_n > 0:
  120. for n in range(sheet_n):
  121. sheet_slots.add(int((n + 0.5) * frames_total / sheet_n))
  122. sheet_frames = []
  123. processed = 0
  124. idx = int(start_i)
  125. started = time.perf_counter()
  126. while True:
  127. ok, image = cap.read()
  128. if not ok or image is None:
  129. break
  130. if limit and processed >= limit:
  131. break
  132. if idx % step:
  133. idx += 1
  134. continue
  135. ts = idx / fps
  136. t0 = time.perf_counter()
  137. boxes = pipeline.detector.timed_infer(image)
  138. result = pipeline.evidence_v2.analyze(
  139. image, ts=ts, frame_id=idx, plc_arrived=False,
  140. detections=boxes,
  141. )
  142. dec_prod = voter_prod.update(
  143. result.to_observation(ts=ts, frame_id=idx, require_commit=True))
  144. dec_diag = voter_diag.update(
  145. result.to_observation(ts=ts, frame_id=idx, require_commit=False))
  146. cost_ms = (time.perf_counter() - t0) * 1000.0
  147. rows.append({
  148. "i": idx,
  149. "ts": round(ts, 3),
  150. "cand": int(result.state),
  151. "cand_conf": round(float(result.confidence), 3),
  152. "prod": int(dec_prod.state),
  153. "prod_conf": round(float(dec_prod.confidence), 3),
  154. "prod_stable": bool(dec_prod.stable),
  155. "diag": int(dec_diag.state),
  156. "diag_conf": round(float(dec_diag.confidence), 3),
  157. "diag_stable": bool(dec_diag.stable),
  158. "committed": bool(result.committed),
  159. "commit_reason": result.commit_reason,
  160. "abstain_reason": result.abstain_reason,
  161. "view": result.view.value,
  162. "door_posts": int(result.door_posts),
  163. "gap_px": None if result.gap_px is None else round(float(result.gap_px), 1),
  164. "gap_m": None if result.gap_m is None else round(float(result.gap_m), 3),
  165. "scale_ok": bool(result.scale_ok),
  166. "motion_ok": bool(result.motion_ok),
  167. "hoist_high": bool(result.hoist_high),
  168. "stable_frames": int(result.stable_frames),
  169. "structure_frames": int(result.structure_frames),
  170. "ms": round(cost_ms, 2),
  171. })
  172. processed += 1
  173. if processed % 100 == 0:
  174. print("progress %s frames=%d ts=%.1f ms=%.1f" % (tag, processed, ts, cost_ms), flush=True)
  175. if idx in sheet_slots and len(sheet_frames) < sheet_n:
  176. sheet_frames.append((idx, image.copy()))
  177. idx += 1
  178. cap.release()
  179. elapsed = time.perf_counter() - started
  180. # 关键帧:生产输出状态每次变化各存一张(最多 annot_n 张)
  181. picks = []
  182. last_prod = None
  183. for row in rows:
  184. if last_prod is None or row["prod"] != last_prod:
  185. picks.append(row)
  186. last_prod = row["prod"]
  187. picks = picks[:annot_n]
  188. cap = cv2.VideoCapture(path)
  189. for n, row in enumerate(picks):
  190. cap.set(cv2.CAP_PROP_POS_FRAMES, row["i"])
  191. ok, image = cap.read()
  192. if not ok or image is None:
  193. continue
  194. lines = [
  195. "i=%d t=%.2fs cand=%d(%.2f) out=%d(%.2f)" % (
  196. row["i"], row["ts"], row["cand"], row["cand_conf"],
  197. row["prod"], row["prod_conf"]),
  198. "commit=%s %s" % (row["committed"], row["commit_reason"]),
  199. "posts=%d gap=%s motion_ok=%s hoist=%s" % (
  200. row["door_posts"], row["gap_px"], row["motion_ok"],
  201. row.get("hoist_high")),
  202. "abstain=%s" % (row["abstain_reason"] or "-"),
  203. ]
  204. annot = _overlay(image, [ln[:110] for ln in lines])
  205. cv2.imwrite(os.path.join(out_dir, "%s_annot_%02d_i%04d.jpg" % (tag, n, row["i"])),
  206. annot, [int(cv2.IMWRITE_JPEG_QUALITY), 85])
  207. cap.release()
  208. _sheet(sheet_frames, os.path.join(out_dir, "%s_sheet.jpg" % tag))
  209. ms_values = [r["ms"] for r in rows] or [0.0]
  210. summary = {
  211. "file": os.path.basename(path),
  212. "path": path,
  213. "tag": tag,
  214. "video": {
  215. "width": width,
  216. "height": height,
  217. "fps": round(fps, 3),
  218. "frames": frames_total,
  219. "duration_s": round(frames_total / fps, 2) if frames_total else None,
  220. },
  221. "config": os.path.relpath(cfg_path, REPO).replace("\\", "/"),
  222. "require_commit": require_commit,
  223. "view": str(cfg.get_path("evidence_v2.view", "front")),
  224. "analysed_frames": len(rows),
  225. "step": step,
  226. "elapsed_s": round(elapsed, 2),
  227. "ms_per_frame": {
  228. "mean": round(sum(ms_values) / len(ms_values), 2),
  229. "p95": round(sorted(ms_values)[int(0.95 * (len(ms_values) - 1))], 2),
  230. },
  231. "prod_dist": _distribution(rows, "prod"),
  232. "diag_dist": _distribution(rows, "diag"),
  233. "cand_dist": _distribution(rows, "cand"),
  234. "prod_committed_frames": sum(1 for r in rows if r["prod"] in (0, 1, 2)),
  235. "commit_ok_frames": sum(1 for r in rows if r["committed"]),
  236. "prod_segments": _segments(rows, "prod", "prod_conf"),
  237. "diag_segments": _segments(rows, "diag", "diag_conf"),
  238. "abstain_reasons": {},
  239. "commit_reasons": {},
  240. }
  241. for bucket, key in (("abstain_reasons", "abstain_reason"),
  242. ("commit_reasons", "commit_reason")):
  243. counts = {}
  244. for row in rows:
  245. text = str(row[key] or "-").split(" ")[0]
  246. counts[text] = counts.get(text, 0) + 1
  247. summary[bucket] = dict(sorted(counts.items(), key=lambda kv: -kv[1])[:12])
  248. with open(os.path.join(out_dir, "%s.jsonl" % tag), "w", encoding="utf-8") as fh:
  249. for row in rows:
  250. fh.write(json.dumps(row, ensure_ascii=False) + "\n")
  251. with open(os.path.join(out_dir, "%s_summary.json" % tag), "w", encoding="utf-8") as fh:
  252. json.dump(summary, fh, ensure_ascii=False, indent=2)
  253. return summary
  254. def main(argv=None):
  255. parser = argparse.ArgumentParser(description="对 mp4 跑 evidence-v2 识别(一次性分析)")
  256. parser.add_argument("--video", action="append", required=True)
  257. parser.add_argument("--config", default=CONFIG)
  258. parser.add_argument("--out", default=os.path.join(REPO, "runs", "video_eval"))
  259. parser.add_argument("--step", type=int, default=1)
  260. parser.add_argument("--start", type=int, default=0, help="起始帧号(调试分段跑)")
  261. parser.add_argument("--limit", type=int, default=0)
  262. parser.add_argument("--sheet", type=int, default=16)
  263. parser.add_argument("--annotate", type=int, default=6)
  264. args = parser.parse_args(argv)
  265. os.makedirs(args.out, exist_ok=True)
  266. for n, path in enumerate(args.video):
  267. summary = run_clip(n, path, args.out, args.step, args.limit,
  268. args.sheet, args.annotate, args.config, args.start)
  269. print(json.dumps({
  270. "tag": summary["tag"],
  271. "file": summary["file"],
  272. "frames": summary["analysed_frames"],
  273. "elapsed_s": summary["elapsed_s"],
  274. "ms_per_frame": summary["ms_per_frame"],
  275. "prod_dist": summary["prod_dist"],
  276. "diag_dist": summary["diag_dist"],
  277. "cand_dist": summary["cand_dist"],
  278. "commit_ok_frames": summary["commit_ok_frames"],
  279. "prod_segments": summary["prod_segments"],
  280. }, ensure_ascii=False))
  281. return 0
  282. if __name__ == "__main__":
  283. sys.exit(main())