"""现场视频离线取证 / 阈值整定工具(**不参与运行时链路**)。 为什么单独放在 ``scripts/`` -------------------------- 运行时链路(``portcv/``)只做"在线判据";本工具做的是**事后取证**:把现场片段拆成 可复核的数字(帧号 / 时间 / 水平带位置 / 植被像素占比),供 ``docs/edge_evidence.md`` §9.2 的验收口径与 §12 的现场实测引用。只依赖 numpy + opencv-python,**不导入 portcv**, 因此不影响现有测试与交付形态。 它回答的三个问题 ---------------- 1. **箱底横梁在哪、随时间怎么动**(``--track``):逐帧检出"暗带"(箱体下侧梁、车底空隙) 与"亮带"(车帮上缘亮面、平车地板高光),看哪条在动(箱体)、哪条静止(车体)。 2. **箱底以下能不能"看到地面"**(``--veg``):分带统计植被(草地)像素占比与平均 BGR; 敞车侧墙挡死时该值恒为 0,平车/地面场景会出现成片绿色或道砟灰。 3. **关键帧长什么样**(``--key``):生成带标注的取证图(检出水平带用彩线画出、 植被像素染色、叠加百像素网格与帧号时间),可直接放进评审文档。 输出(写入 ``--out`` 目录) -------------------------- * ``_sheet.jpg`` 整段作业的 3 列拼版(快速通览,含帧号 / 时间) * ``_f00000_t00.0s_annot.jpg`` 关键帧标注图 * ``report.txt`` 全部打印结果(可复现的原始测量,随文档一起评审) 用法:: python scripts/field_clip_probe.py \\ --clip A="C:\\\\field\\\\with_wagon.mp4" --clip B="C:\\\\field\\\\flatcar.mp4" \\ --out docs/evidence/field_2026-10-08 --sampling 12 \\ --track A:300:1100:25 --key A:411 --key A:1100 --veg 约定 ---- * ``--clip NAME=PATH``:片段名(用于文件名前缀)与路径,可重复; * ``--track NAME:START:STOP:STEP``:逐帧测水平带(帧号区间与步长); * ``--key NAME:FRAME``:要生成标注图的帧; * 分析窗口默认 ``x=[400,750] y=[150,620]``(``--x0/--x1/--y0/--y1`` 可改); 取窗口时要避开镜头支架、反光镜等前景遮挡与铭牌文字。 """ from __future__ import annotations import argparse import os import cv2 import numpy as np #: 默认分析窗口(列区间避开铭牌/文字,行区间覆盖箱底与车体上部结构) WINDOW = {"x0": 400, "x1": 750, "y0": 150, "y1": 620} #: 标记色(BGR):亮带=绿、暗带=红、植被=品红、网格=灰 COLOR_BRIGHT = (60, 220, 60) COLOR_DARK = (60, 60, 240) COLOR_VEG = (255, 60, 255) COLOR_GRID = (90, 90, 90) def report_print(report, *args): """同时打印与记录。""" line = " ".join(str(a) for a in args) print(line) report.append(line) def grab(clip_path, idx): """取单帧(按帧号定位,失败返回 None)。""" cap = cv2.VideoCapture(clip_path) try: cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx)) ok, frame = cap.read() finally: cap.release() return frame if ok else None def meta(clip_path): """返回 ``(宽, 高, 帧率, 帧数, 时长秒)``。""" cap = cv2.VideoCapture(clip_path) try: fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) finally: cap.release() return width, height, fps, frames, frames / fps if fps else 0.0 def horizontal_bands(frame, window, min_h=3, max_h=70, topn=8): """检出水平"亮带 / 暗带"。 做法:对分析窗口取行平均的一阶纵向差分(Sobel-y),找显著的上跳沿(进入亮带)与 下跳沿(离开亮带),把相邻的一上一下配成一条带。返回 ``(bright, dark)``, 每项 ``(强度, 上边界 y, 下边界 y)``。 * 亮带 = 该行区间比上下都亮(车帮上缘亮面 / 平车地板高光 / 箱顶框反光); * 暗带 = 该行区间比上下都暗(**箱体下侧梁**、车底空隙、门缝阴影)。 """ x0, x1, y0, y1 = window["x0"], window["x1"], window["y0"], window["y1"] gray = cv2.cvtColor(frame[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY).astype(np.float32) gray = cv2.GaussianBlur(gray, (3, 3), 0) gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1) mag = np.abs(gy) limit = mag.mean() + 0.9 * mag.std() events = [] for i in range(2, len(gy) - 2): if mag[i] >= limit and mag[i] == mag[i - 2:i + 3].max(): events.append((i, float(gy[i]))) bright, dark = [], [] for (i, gi), (j, gj) in zip(events, events[1:]): if not min_h <= j - i <= max_h: continue strength = (mag[i] + mag[j]) / 2.0 if gi > 0 and gj < 0: bright.append((strength, y0 + i, y0 + j)) elif gi < 0 and gj > 0: dark.append((strength, y0 + i, y0 + j)) bright.sort(reverse=True) dark.sort(reverse=True) return bright[:topn], dark[:topn] def veg_profile(frame, step=60): """分带统计植被像素占比与平均 BGR(判断"箱底以下能否看到地面")。""" hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) veg = ((hsv[:, :, 0] > 35) & (hsv[:, :, 0] < 95) & (hsv[:, :, 1] > 60) & (hsv[:, :, 2] > 40)) rows = [] height = frame.shape[0] for y0 in range(0, height - step + 1, step): band = slice(y0, y0 + step) mean_bgr = frame[band, :, :].reshape(-1, 3).mean(axis=0) rows.append((y0, y0 + step, float(veg[band, :].mean()), float(mean_bgr[0]), float(mean_bgr[1]), float(mean_bgr[2]))) return rows, float(veg.mean()) def annotate(frame, window, clip_tag, idx, fps): """生成关键帧取证图:检出带 + 植被染色 + 百像素网格。""" img = frame.copy() height, width = img.shape[:2] bright, dark = horizontal_bands(frame, window) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) veg = ((hsv[:, :, 0] > 35) & (hsv[:, :, 0] < 95) & (hsv[:, :, 1] > 60) & (hsv[:, :, 2] > 40)) if veg.any(): img[veg] = (0.45 * img[veg] + 0.55 * np.array(COLOR_VEG, np.float32)).astype(np.uint8) for y in range(0, height, 100): cv2.line(img, (0, y), (width, y), COLOR_GRID, 1) cv2.putText(img, str(y), (4, min(y + 14, height - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 0), 1) for x in (window["x0"], window["x1"]): cv2.line(img, (x, 0), (x, height), (0, 200, 255), 1) for label_color, items, prefix in ((COLOR_BRIGHT, bright, "BRIGHT"), (COLOR_DARK, dark, "DARK")): for rank, (strength, ytop, ybot) in enumerate(items): cv2.line(img, (0, ytop), (width, ytop), label_color, 2) cv2.line(img, (0, ybot), (width, ybot), label_color, 2) text = "%s#%d y=%d..%d s=%.0f" % (prefix, rank + 1, ytop, ybot, strength) cv2.putText(img, text, (6, ytop - 4 if ytop > 16 else ybot + 16), cv2.FONT_HERSHEY_SIMPLEX, 0.45, label_color, 1) cv2.putText(img, "%s frame=%d t=%.1fs veg=%.2f%%" % (clip_tag, idx, idx / fps, veg.mean() * 100), (6, height - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2) return img def contact_sheet(clip_path, idxs, fps, clip_tag="", thumb_w=620): """3 列拼版,含片段名 / 帧号 / 时间。""" thumbs = [] for idx in idxs: frame = grab(clip_path, idx) if frame is None: continue cv2.putText(frame, "%s f%d t=%.1fs" % (clip_tag, idx, idx / fps), (12, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.1, (0, 0, 255), 3) h, w = frame.shape[:2] thumbs.append(cv2.resize(frame, (thumb_w, int(thumb_w * h / w)))) if not thumbs: return None cols = 3 rows = (len(thumbs) + cols - 1) // cols th, tw = thumbs[0].shape[:2] sheet = np.full((rows * th, cols * tw, 3), 25, np.uint8) for j, thumb in enumerate(thumbs): r, c = divmod(j, cols) sheet[r * th:(r + 1) * th, c * tw:(c + 1) * tw] = thumb return sheet def _parse_clip(text): """``NAME=PATH`` -> ``(name, path)``。""" name, sep, path = text.partition("=") if not sep or not name or not path: raise argparse.ArgumentTypeError("--clip 需要 NAME=PATH 形式: %r" % text) return name, path def _parse_track(text): """``NAME:START:STOP:STEP`` -> 元组。""" name, start, stop, step = text.split(":") return name, int(start), int(stop), int(step) def _parse_key(text): """``NAME:FRAME`` -> ``(name, frame)``。""" name, frame = text.split(":") return name, int(frame) def _fmt(items): """把 ``(强度, y0, y1)`` 列表压成一行。""" return " ".join("[s=%.0f y=%d..%d]" % (round(s), a, b) for s, a, b in items) def main(argv=None): parser = argparse.ArgumentParser(description="现场视频离线取证(判据验证 / 阈值整定)") parser.add_argument("--clip", action="append", required=True, metavar="NAME=PATH", help="片段名与路径(第一段=有车斗,第二段=无车斗),可重复") parser.add_argument("--out", default=os.path.join("docs", "evidence", "field"), help="输出目录(默认 docs/evidence/field)") parser.add_argument("--sampling", type=int, default=12, help="拼版抽帧数(默认 12)") parser.add_argument("--track", action="append", default=None, metavar="NAME:START:STOP:STEP", help="逐帧测水平带,可重复") parser.add_argument("--key", action="append", default=None, metavar="NAME:FRAME", help="生成标注图的帧,可重复") parser.add_argument("--veg", action="store_true", help="打印分带植被 / 灰度统计") parser.add_argument("--x0", type=int, default=WINDOW["x0"]) parser.add_argument("--x1", type=int, default=WINDOW["x1"]) parser.add_argument("--y0", type=int, default=WINDOW["y0"]) parser.add_argument("--y1", type=int, default=WINDOW["y1"]) args = parser.parse_args(argv) window = {"x0": args.x0, "x1": args.x1, "y0": args.y0, "y1": args.y1} clips = dict(_parse_clip(t) for t in args.clip) keys = [_parse_key(t) for t in (args.key or [])] os.makedirs(args.out, exist_ok=True) report = [] report_print(report, "# 现场视频取证报告(scripts/field_clip_probe.py 生成)") report_print(report, "# 分析窗口 x=[%d,%d] y=[%d,%d](列区间避开遮挡与铭牌文字)" % (window["x0"], window["x1"], window["y0"], window["y1"])) info = {} for name, path in clips.items(): if not os.path.exists(path): raise SystemExit("找不到片段: %s" % path) width, height, fps, frames, duration = meta(path) info[name] = (path, fps, frames) report_print(report, "") report_print(report, "## 片段 %s %s" % (name, os.path.basename(path))) report_print(report, " %dx%d fps=%.3f frames=%d dur=%.2fs" % (width, height, fps, frames, duration)) count = max(2, args.sampling) idxs = [int(frames * (0.03 + 0.94 * i / (count - 1))) for i in range(count)] sheet = contact_sheet(path, idxs, fps, name) if sheet is not None: out_path = os.path.join(args.out, "%s_sheet.jpg" % name) cv2.imwrite(out_path, sheet, [cv2.IMWRITE_JPEG_QUALITY, 85]) report_print(report, " 拼版 -> %s" % out_path) for spec in args.track or []: name, start, stop, step = _parse_track(spec) path, fps, _ = info[name] report_print(report, "") report_print(report, "## 逐帧水平带 %s f%d..f%d step=%d(DARK=暗带/箱体下侧梁, BRIGHT=亮带/车帮上缘)" % (spec, start, stop, step)) for idx in range(start, stop + 1, step): frame = grab(path, idx) if frame is None: continue bright, dark = horizontal_bands(frame, window) report_print(report, "f%-5d %6.1fs DARK %s" % (idx, idx / fps, _fmt(dark))) report_print(report, " BRIGHT %s" % _fmt(bright)) veg_targets = list(keys) if args.veg: for name, (path, fps, frames) in info.items(): if not any(k_name == name for k_name, _ in veg_targets): veg_targets.append((name, frames // 2)) veg_targets.append((name, frames - 1)) for name, idx in veg_targets: path, fps, _ = info.get(name, (None, 0, 0)) if path is None: report_print(report, " ! 未知片段 %s" % name) continue frame = grab(path, idx) if frame is None: report_print(report, " ! 取帧失败 %s f%d" % (name, idx)) continue out_path = os.path.join(args.out, "%s_f%05d_t%05.1fs_annot.jpg" % (name, idx, idx / fps)) cv2.imwrite(out_path, annotate(frame, window, name, idx, fps), [cv2.IMWRITE_JPEG_QUALITY, 88]) report_print(report, "") report_print(report, "## 关键帧 %s f%d t=%.1fs -> %s" % (name, idx, idx / fps, out_path)) if args.veg: rows, total = veg_profile(frame) report_print(report, " 全画面植被像素占比 = %.3f%%" % (total * 100.0)) for y0, y1, frac, blue, green, red in rows: report_print(report, " y=%3d-%3d veg=%5.1f%% BGR=(%5.1f,%5.1f,%5.1f)" % (y0, y1, frac * 100.0, blue, green, red)) report_path = os.path.join(args.out, "report.txt") with open(report_path, "w", encoding="utf-8") as handle: handle.write("\n".join(report) + "\n") print("报告 -> %s" % report_path) return 0 if __name__ == "__main__": raise SystemExit(main())