field_clip_probe.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. """现场视频离线取证 / 阈值整定工具(**不参与运行时链路**)。
  2. 为什么单独放在 ``scripts/``
  3. --------------------------
  4. 运行时链路(``portcv/``)只做"在线判据";本工具做的是**事后取证**:把现场片段拆成
  5. 可复核的数字(帧号 / 时间 / 水平带位置 / 植被像素占比),供 ``docs/edge_evidence.md``
  6. §9.2 的验收口径与 §12 的现场实测引用。只依赖 numpy + opencv-python,**不导入 portcv**,
  7. 因此不影响现有测试与交付形态。
  8. 它回答的三个问题
  9. ----------------
  10. 1. **箱底横梁在哪、随时间怎么动**(``--track``):逐帧检出"暗带"(箱体下侧梁、车底空隙)
  11. 与"亮带"(车帮上缘亮面、平车地板高光),看哪条在动(箱体)、哪条静止(车体)。
  12. 2. **箱底以下能不能"看到地面"**(``--veg``):分带统计植被(草地)像素占比与平均 BGR;
  13. 敞车侧墙挡死时该值恒为 0,平车/地面场景会出现成片绿色或道砟灰。
  14. 3. **关键帧长什么样**(``--key``):生成带标注的取证图(检出水平带用彩线画出、
  15. 植被像素染色、叠加百像素网格与帧号时间),可直接放进评审文档。
  16. 输出(写入 ``--out`` 目录)
  17. --------------------------
  18. * ``<TAG>_sheet.jpg`` 整段作业的 3 列拼版(快速通览,含帧号 / 时间)
  19. * ``<TAG>_f00000_t00.0s_annot.jpg`` 关键帧标注图
  20. * ``report.txt`` 全部打印结果(可复现的原始测量,随文档一起评审)
  21. 用法::
  22. python scripts/field_clip_probe.py \\
  23. --clip A="C:\\\\field\\\\with_wagon.mp4" --clip B="C:\\\\field\\\\flatcar.mp4" \\
  24. --out docs/evidence/field_2026-10-08 --sampling 12 \\
  25. --track A:300:1100:25 --key A:411 --key A:1100 --veg
  26. 约定
  27. ----
  28. * ``--clip NAME=PATH``:片段名(用于文件名前缀)与路径,可重复;
  29. * ``--track NAME:START:STOP:STEP``:逐帧测水平带(帧号区间与步长);
  30. * ``--key NAME:FRAME``:要生成标注图的帧;
  31. * 分析窗口默认 ``x=[400,750] y=[150,620]``(``--x0/--x1/--y0/--y1`` 可改);
  32. 取窗口时要避开镜头支架、反光镜等前景遮挡与铭牌文字。
  33. """
  34. from __future__ import annotations
  35. import argparse
  36. import os
  37. import cv2
  38. import numpy as np
  39. #: 默认分析窗口(列区间避开铭牌/文字,行区间覆盖箱底与车体上部结构)
  40. WINDOW = {"x0": 400, "x1": 750, "y0": 150, "y1": 620}
  41. #: 标记色(BGR):亮带=绿、暗带=红、植被=品红、网格=灰
  42. COLOR_BRIGHT = (60, 220, 60)
  43. COLOR_DARK = (60, 60, 240)
  44. COLOR_VEG = (255, 60, 255)
  45. COLOR_GRID = (90, 90, 90)
  46. def report_print(report, *args):
  47. """同时打印与记录。"""
  48. line = " ".join(str(a) for a in args)
  49. print(line)
  50. report.append(line)
  51. def grab(clip_path, idx):
  52. """取单帧(按帧号定位,失败返回 None)。"""
  53. cap = cv2.VideoCapture(clip_path)
  54. try:
  55. cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
  56. ok, frame = cap.read()
  57. finally:
  58. cap.release()
  59. return frame if ok else None
  60. def meta(clip_path):
  61. """返回 ``(宽, 高, 帧率, 帧数, 时长秒)``。"""
  62. cap = cv2.VideoCapture(clip_path)
  63. try:
  64. fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
  65. frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
  66. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  67. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  68. finally:
  69. cap.release()
  70. return width, height, fps, frames, frames / fps if fps else 0.0
  71. def horizontal_bands(frame, window, min_h=3, max_h=70, topn=8):
  72. """检出水平"亮带 / 暗带"。
  73. 做法:对分析窗口取行平均的一阶纵向差分(Sobel-y),找显著的上跳沿(进入亮带)与
  74. 下跳沿(离开亮带),把相邻的一上一下配成一条带。返回 ``(bright, dark)``,
  75. 每项 ``(强度, 上边界 y, 下边界 y)``。
  76. * 亮带 = 该行区间比上下都亮(车帮上缘亮面 / 平车地板高光 / 箱顶框反光);
  77. * 暗带 = 该行区间比上下都暗(**箱体下侧梁**、车底空隙、门缝阴影)。
  78. """
  79. x0, x1, y0, y1 = window["x0"], window["x1"], window["y0"], window["y1"]
  80. gray = cv2.cvtColor(frame[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY).astype(np.float32)
  81. gray = cv2.GaussianBlur(gray, (3, 3), 0)
  82. gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  83. mag = np.abs(gy)
  84. limit = mag.mean() + 0.9 * mag.std()
  85. events = []
  86. for i in range(2, len(gy) - 2):
  87. if mag[i] >= limit and mag[i] == mag[i - 2:i + 3].max():
  88. events.append((i, float(gy[i])))
  89. bright, dark = [], []
  90. for (i, gi), (j, gj) in zip(events, events[1:]):
  91. if not min_h <= j - i <= max_h:
  92. continue
  93. strength = (mag[i] + mag[j]) / 2.0
  94. if gi > 0 and gj < 0:
  95. bright.append((strength, y0 + i, y0 + j))
  96. elif gi < 0 and gj > 0:
  97. dark.append((strength, y0 + i, y0 + j))
  98. bright.sort(reverse=True)
  99. dark.sort(reverse=True)
  100. return bright[:topn], dark[:topn]
  101. def veg_profile(frame, step=60):
  102. """分带统计植被像素占比与平均 BGR(判断"箱底以下能否看到地面")。"""
  103. hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  104. veg = ((hsv[:, :, 0] > 35) & (hsv[:, :, 0] < 95)
  105. & (hsv[:, :, 1] > 60) & (hsv[:, :, 2] > 40))
  106. rows = []
  107. height = frame.shape[0]
  108. for y0 in range(0, height - step + 1, step):
  109. band = slice(y0, y0 + step)
  110. mean_bgr = frame[band, :, :].reshape(-1, 3).mean(axis=0)
  111. rows.append((y0, y0 + step, float(veg[band, :].mean()),
  112. float(mean_bgr[0]), float(mean_bgr[1]), float(mean_bgr[2])))
  113. return rows, float(veg.mean())
  114. def annotate(frame, window, clip_tag, idx, fps):
  115. """生成关键帧取证图:检出带 + 植被染色 + 百像素网格。"""
  116. img = frame.copy()
  117. height, width = img.shape[:2]
  118. bright, dark = horizontal_bands(frame, window)
  119. hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  120. veg = ((hsv[:, :, 0] > 35) & (hsv[:, :, 0] < 95)
  121. & (hsv[:, :, 1] > 60) & (hsv[:, :, 2] > 40))
  122. if veg.any():
  123. img[veg] = (0.45 * img[veg] + 0.55 * np.array(COLOR_VEG, np.float32)).astype(np.uint8)
  124. for y in range(0, height, 100):
  125. cv2.line(img, (0, y), (width, y), COLOR_GRID, 1)
  126. cv2.putText(img, str(y), (4, min(y + 14, height - 4)),
  127. cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 0), 1)
  128. for x in (window["x0"], window["x1"]):
  129. cv2.line(img, (x, 0), (x, height), (0, 200, 255), 1)
  130. for label_color, items, prefix in ((COLOR_BRIGHT, bright, "BRIGHT"), (COLOR_DARK, dark, "DARK")):
  131. for rank, (strength, ytop, ybot) in enumerate(items):
  132. cv2.line(img, (0, ytop), (width, ytop), label_color, 2)
  133. cv2.line(img, (0, ybot), (width, ybot), label_color, 2)
  134. text = "%s#%d y=%d..%d s=%.0f" % (prefix, rank + 1, ytop, ybot, strength)
  135. cv2.putText(img, text, (6, ytop - 4 if ytop > 16 else ybot + 16),
  136. cv2.FONT_HERSHEY_SIMPLEX, 0.45, label_color, 1)
  137. cv2.putText(img, "%s frame=%d t=%.1fs veg=%.2f%%" % (clip_tag, idx, idx / fps, veg.mean() * 100),
  138. (6, height - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2)
  139. return img
  140. def contact_sheet(clip_path, idxs, fps, clip_tag="", thumb_w=620):
  141. """3 列拼版,含片段名 / 帧号 / 时间。"""
  142. thumbs = []
  143. for idx in idxs:
  144. frame = grab(clip_path, idx)
  145. if frame is None:
  146. continue
  147. cv2.putText(frame, "%s f%d t=%.1fs" % (clip_tag, idx, idx / fps), (12, 40),
  148. cv2.FONT_HERSHEY_SIMPLEX, 1.1, (0, 0, 255), 3)
  149. h, w = frame.shape[:2]
  150. thumbs.append(cv2.resize(frame, (thumb_w, int(thumb_w * h / w))))
  151. if not thumbs:
  152. return None
  153. cols = 3
  154. rows = (len(thumbs) + cols - 1) // cols
  155. th, tw = thumbs[0].shape[:2]
  156. sheet = np.full((rows * th, cols * tw, 3), 25, np.uint8)
  157. for j, thumb in enumerate(thumbs):
  158. r, c = divmod(j, cols)
  159. sheet[r * th:(r + 1) * th, c * tw:(c + 1) * tw] = thumb
  160. return sheet
  161. def _parse_clip(text):
  162. """``NAME=PATH`` -> ``(name, path)``。"""
  163. name, sep, path = text.partition("=")
  164. if not sep or not name or not path:
  165. raise argparse.ArgumentTypeError("--clip 需要 NAME=PATH 形式: %r" % text)
  166. return name, path
  167. def _parse_track(text):
  168. """``NAME:START:STOP:STEP`` -> 元组。"""
  169. name, start, stop, step = text.split(":")
  170. return name, int(start), int(stop), int(step)
  171. def _parse_key(text):
  172. """``NAME:FRAME`` -> ``(name, frame)``。"""
  173. name, frame = text.split(":")
  174. return name, int(frame)
  175. def _fmt(items):
  176. """把 ``(强度, y0, y1)`` 列表压成一行。"""
  177. return " ".join("[s=%.0f y=%d..%d]" % (round(s), a, b) for s, a, b in items)
  178. def main(argv=None):
  179. parser = argparse.ArgumentParser(description="现场视频离线取证(判据验证 / 阈值整定)")
  180. parser.add_argument("--clip", action="append", required=True, metavar="NAME=PATH",
  181. help="片段名与路径(第一段=有车斗,第二段=无车斗),可重复")
  182. parser.add_argument("--out", default=os.path.join("docs", "evidence", "field"),
  183. help="输出目录(默认 docs/evidence/field)")
  184. parser.add_argument("--sampling", type=int, default=12, help="拼版抽帧数(默认 12)")
  185. parser.add_argument("--track", action="append", default=None, metavar="NAME:START:STOP:STEP",
  186. help="逐帧测水平带,可重复")
  187. parser.add_argument("--key", action="append", default=None, metavar="NAME:FRAME",
  188. help="生成标注图的帧,可重复")
  189. parser.add_argument("--veg", action="store_true", help="打印分带植被 / 灰度统计")
  190. parser.add_argument("--x0", type=int, default=WINDOW["x0"])
  191. parser.add_argument("--x1", type=int, default=WINDOW["x1"])
  192. parser.add_argument("--y0", type=int, default=WINDOW["y0"])
  193. parser.add_argument("--y1", type=int, default=WINDOW["y1"])
  194. args = parser.parse_args(argv)
  195. window = {"x0": args.x0, "x1": args.x1, "y0": args.y0, "y1": args.y1}
  196. clips = dict(_parse_clip(t) for t in args.clip)
  197. keys = [_parse_key(t) for t in (args.key or [])]
  198. os.makedirs(args.out, exist_ok=True)
  199. report = []
  200. report_print(report, "# 现场视频取证报告(scripts/field_clip_probe.py 生成)")
  201. report_print(report, "# 分析窗口 x=[%d,%d] y=[%d,%d](列区间避开遮挡与铭牌文字)"
  202. % (window["x0"], window["x1"], window["y0"], window["y1"]))
  203. info = {}
  204. for name, path in clips.items():
  205. if not os.path.exists(path):
  206. raise SystemExit("找不到片段: %s" % path)
  207. width, height, fps, frames, duration = meta(path)
  208. info[name] = (path, fps, frames)
  209. report_print(report, "")
  210. report_print(report, "## 片段 %s %s" % (name, os.path.basename(path)))
  211. report_print(report, " %dx%d fps=%.3f frames=%d dur=%.2fs"
  212. % (width, height, fps, frames, duration))
  213. count = max(2, args.sampling)
  214. idxs = [int(frames * (0.03 + 0.94 * i / (count - 1))) for i in range(count)]
  215. sheet = contact_sheet(path, idxs, fps, name)
  216. if sheet is not None:
  217. out_path = os.path.join(args.out, "%s_sheet.jpg" % name)
  218. cv2.imwrite(out_path, sheet, [cv2.IMWRITE_JPEG_QUALITY, 85])
  219. report_print(report, " 拼版 -> %s" % out_path)
  220. for spec in args.track or []:
  221. name, start, stop, step = _parse_track(spec)
  222. path, fps, _ = info[name]
  223. report_print(report, "")
  224. report_print(report, "## 逐帧水平带 %s f%d..f%d step=%d(DARK=暗带/箱体下侧梁, BRIGHT=亮带/车帮上缘)"
  225. % (spec, start, stop, step))
  226. for idx in range(start, stop + 1, step):
  227. frame = grab(path, idx)
  228. if frame is None:
  229. continue
  230. bright, dark = horizontal_bands(frame, window)
  231. report_print(report, "f%-5d %6.1fs DARK %s" % (idx, idx / fps, _fmt(dark)))
  232. report_print(report, " BRIGHT %s" % _fmt(bright))
  233. veg_targets = list(keys)
  234. if args.veg:
  235. for name, (path, fps, frames) in info.items():
  236. if not any(k_name == name for k_name, _ in veg_targets):
  237. veg_targets.append((name, frames // 2))
  238. veg_targets.append((name, frames - 1))
  239. for name, idx in veg_targets:
  240. path, fps, _ = info.get(name, (None, 0, 0))
  241. if path is None:
  242. report_print(report, " ! 未知片段 %s" % name)
  243. continue
  244. frame = grab(path, idx)
  245. if frame is None:
  246. report_print(report, " ! 取帧失败 %s f%d" % (name, idx))
  247. continue
  248. out_path = os.path.join(args.out, "%s_f%05d_t%05.1fs_annot.jpg" % (name, idx, idx / fps))
  249. cv2.imwrite(out_path, annotate(frame, window, name, idx, fps),
  250. [cv2.IMWRITE_JPEG_QUALITY, 88])
  251. report_print(report, "")
  252. report_print(report, "## 关键帧 %s f%d t=%.1fs -> %s" % (name, idx, idx / fps, out_path))
  253. if args.veg:
  254. rows, total = veg_profile(frame)
  255. report_print(report, " 全画面植被像素占比 = %.3f%%" % (total * 100.0))
  256. for y0, y1, frac, blue, green, red in rows:
  257. report_print(report, " y=%3d-%3d veg=%5.1f%% BGR=(%5.1f,%5.1f,%5.1f)"
  258. % (y0, y1, frac * 100.0, blue, green, red))
  259. report_path = os.path.join(args.out, "report.txt")
  260. with open(report_path, "w", encoding="utf-8") as handle:
  261. handle.write("\n".join(report) + "\n")
  262. print("报告 -> %s" % report_path)
  263. return 0
  264. if __name__ == "__main__":
  265. raise SystemExit(main())