p0_v2_measure.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. """P0 v2 现场片段可分性测量(独立工具,**不 import portcv**)。
  2. 为什么单独一个脚本
  3. ------------------
  4. ``docs/route_v2.md`` 的 P0 要求先用现场 A/B 片段证明
  5. 「敞车(1)/ 平车(2)/ 其他(0)」在**箱底以下**的结构上可分,再动
  6. C++ / Python 生产代码。本脚本只做**离线取证**,输出可逐帧复算的数字:
  7. * 箱底线、车体上缘线(敞车墙顶 / 平车车面)与两者间隙;
  8. * 箱底以下固定 ROI 的**门板/立柱**结构(敞车)与**车轮/地面**线索(平车);
  9. * 箱高在画面中的可见程度、门板间距、落位时刻的代理量。
  10. 它不参与运行时链路,也不改变任何交付形态;只依赖 numpy + opencv-python,
  11. 与 ``scripts/field_clip_probe.py`` 的纪律一致。
  12. 用法::
  13. python scripts/p0_v2_measure.py \
  14. --clip A="C:\\field\\7a55d023....mp4" \
  15. --clip B="C:\\field\\75efb374....mp4" \
  16. --out docs/evidence/p0_v2 --samples 48 \
  17. --key A:411 --key A:1100 --key B:514 --key B:1790
  18. 输出::
  19. <out>/<TAG>_per_frame.jsonl 逐帧测量(可复算)
  20. <out>/<TAG>_f000411_annot.jpg 关键帧标注(ROI / 线 / 数字)
  21. <out>/summary.json 分位数、A/B 可分性、落位代理
  22. <out>/report.md 给评审看的 P0 报告
  23. """
  24. from __future__ import annotations
  25. import argparse
  26. import json
  27. import math
  28. import os
  29. import statistics
  30. from typing import Dict, Iterable, List, Optional, Sequence, Tuple
  31. import cv2
  32. import numpy as np
  33. #: 箱底以下结构 ROI(比例坐标 x0,y0,x1,y1)。A 片段对应 C70 下部门板,
  34. #: B 片段对应 X70 车面边梁 + 车轮 + 地面;固定 ROI 才能做 A/B 同口径比较。
  35. DEFAULT_BELOW = (0.00, 0.66, 1.00, 0.86)
  36. #: 地面/植被带(比例坐标):只作辅助,不单独判 2。
  37. DEFAULT_GROUND = (0.00, 0.48, 1.00, 0.68)
  38. #: 水平带搜索窗口(比例坐标):避开画面最左/最右的支架与反光镜。
  39. DEFAULT_WINDOW = (0.24, 0.10, 0.78, 0.90)
  40. COLOR_VERTICAL = (60, 220, 60)
  41. COLOR_DIAGONAL = (0, 220, 255)
  42. COLOR_HORIZONTAL = (255, 160, 60)
  43. COLOR_BOX = (40, 40, 240)
  44. COLOR_BED = (220, 220, 40)
  45. COLOR_ROI = (60, 220, 60)
  46. COLOR_GROUND = (255, 60, 255)
  47. def parse_ratio(text: str) -> Tuple[float, float, float, float]:
  48. parts = [float(v) for v in text.split(",")]
  49. if len(parts) != 4:
  50. raise argparse.ArgumentTypeError("需要 4 个逗号分隔的比例: x0,y0,x1,y1")
  51. x0, y0, x1, y1 = parts
  52. if not (0.0 <= x0 < x1 <= 1.0 and 0.0 <= y0 < y1 <= 1.0):
  53. raise argparse.ArgumentTypeError("比例必须满足 0<=x0<x1<=1、0<=y0<y1<=1")
  54. return (x0, y0, x1, y1)
  55. def roi_px(shape: Sequence[int], frac: Tuple[float, float, float, float]) -> Tuple[int, int, int, int]:
  56. height, width = int(shape[0]), int(shape[1])
  57. x0, y0, x1, y1 = frac
  58. return (int(round(x0 * width)), int(round(y0 * height)),
  59. int(round(x1 * width)), int(round(y1 * height)))
  60. def grab(path: str, index: int) -> Optional[np.ndarray]:
  61. cap = cv2.VideoCapture(path)
  62. try:
  63. cap.set(cv2.CAP_PROP_POS_FRAMES, int(index))
  64. ok, frame = cap.read()
  65. finally:
  66. cap.release()
  67. return frame if ok else None
  68. def meta(path: str) -> Dict[str, object]:
  69. cap = cv2.VideoCapture(path)
  70. try:
  71. fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0)
  72. frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
  73. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
  74. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
  75. finally:
  76. cap.release()
  77. return {"path": path, "width": width, "height": height, "fps": fps,
  78. "frames": frames, "duration_s": (frames / fps) if fps else 0.0}
  79. def horizontal_bands(gray: np.ndarray,
  80. roi: Tuple[int, int, int, int],
  81. min_h: int = 3,
  82. max_h: int = 90,
  83. topn: int = 10) -> Tuple[List[Dict[str, float]], List[Dict[str, float]]]:
  84. """在 ROI 内用行均值纵向 Sobel 找水平亮带/暗带。
  85. 返回 ``(bright, dark)``,每一项 ``{"strength", "y0", "y1"}``;
  86. ``y0/y1`` 是**原图坐标**。亮带 = 中间比上下亮(墙顶亮面 / 车面高光),
  87. 暗带 = 中间比上下暗(箱体下侧梁 / 门缝阴影 / 车底空隙)。
  88. """
  89. x0, y0, x1, y1 = roi
  90. crop = gray[y0:y1, x0:x1].astype(np.float32)
  91. if crop.size == 0:
  92. return [], []
  93. crop = cv2.GaussianBlur(crop, (3, 3), 0)
  94. gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  95. mag = np.abs(gy)
  96. if mag.size == 0:
  97. return [], []
  98. limit = float(mag.mean() + 0.9 * mag.std())
  99. events: List[Tuple[int, float]] = []
  100. for i in range(2, len(gy) - 2):
  101. if mag[i] >= limit and mag[i] == mag[i - 2:i + 3].max():
  102. events.append((i, float(gy[i])))
  103. bright: List[Dict[str, float]] = []
  104. dark: List[Dict[str, float]] = []
  105. for j in range(len(events) - 1):
  106. i1, v1 = events[j]
  107. i2, v2 = events[j + 1]
  108. height = i2 - i1
  109. if height < min_h or height > max_h:
  110. continue
  111. strength = min(abs(v1), abs(v2))
  112. if strength <= 0.0:
  113. continue
  114. if v1 > 0.0 > v2:
  115. bright.append({"strength": strength, "y0": float(y0 + i1), "y1": float(y0 + i2)})
  116. elif v1 < 0.0 < v2:
  117. dark.append({"strength": strength, "y0": float(y0 + i1), "y1": float(y0 + i2)})
  118. bright.sort(key=lambda b: b["strength"], reverse=True)
  119. dark.sort(key=lambda b: b["strength"], reverse=True)
  120. return bright[:topn], dark[:topn]
  121. def pick_box_and_bed(bright: List[Dict[str, float]],
  122. dark: List[Dict[str, float]],
  123. frame_h: int) -> Tuple[Optional[Dict[str, float]], Optional[Dict[str, float]]]:
  124. """选箱底暗带与它下方最近的车体上缘亮带。
  125. * 箱底 = 画面上部(``y1 <= 0.68*h``)**最高**的强暗带(下侧梁是暗带);
  126. * 车体上缘 = 箱底下方 120 px 内**最近**的亮带(敞车墙顶 / 平车车面)。
  127. """
  128. upper = [b for b in dark if b["y1"] <= 0.68 * frame_h and b["y0"] >= 0.02 * frame_h]
  129. if not upper:
  130. return None, None
  131. strongest = max(b["strength"] for b in upper)
  132. strong = [b for b in upper if b["strength"] >= 0.45 * strongest]
  133. box = min(strong, key=lambda b: b["y0"])
  134. box_bottom = box["y1"]
  135. below = [b for b in bright if b["y0"] >= box_bottom + 1.0 and b["y0"] <= box_bottom + 120.0]
  136. bed = min(below, key=lambda b: b["y0"]) if below else None
  137. return box, bed
  138. def _cluster_positions(values: Iterable[float], gap_px: float = 9.0) -> List[float]:
  139. """把一维位置聚成簇(相邻差 <= gap_px 视为同一根立柱)。"""
  140. ordered = sorted(float(v) for v in values)
  141. if not ordered:
  142. return []
  143. clusters = [[ordered[0]]]
  144. for value in ordered[1:]:
  145. if value - clusters[-1][-1] <= gap_px:
  146. clusters[-1].append(value)
  147. else:
  148. clusters.append([value])
  149. return [float(statistics.median(c)) for c in clusters]
  150. def detect_structure(gray: np.ndarray,
  151. roi: Tuple[int, int, int, int]) -> Dict[str, object]:
  152. """箱底以下 ROI 的直线/矩形结构:门板立柱、斜撑(八)、矩形门(口)。
  153. 只做**证据计数**,不做分类;A/B 的阈值得由 P0 分布确定。
  154. """
  155. x0, y0, x1, y1 = roi
  156. crop = gray[y0:y1, x0:x1]
  157. if crop.size == 0:
  158. return {"vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0,
  159. "rect_contours": 0, "post_count": 0, "post_spacing_median": None,
  160. "post_spacing_cv": None, "edge_density": 0.0}
  161. crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop)
  162. edges = cv2.Canny(crop, 50, 150)
  163. roi_h = max(1, y1 - y0)
  164. roi_area = float(crop.shape[0] * crop.shape[1])
  165. lines = cv2.HoughLinesP(edges, 1, math.pi / 180.0, threshold=24,
  166. minLineLength=20, maxLineGap=8)
  167. vertical: List[Tuple[float, float, float]] = [] # (x_mid, y_top, y_bottom)
  168. diagonal = 0
  169. horizontal = 0
  170. if lines is not None:
  171. # OpenCV 4.x 返回 (N,1,4),OpenCV 5.x 可能返回 (N,4);两种都兼容。
  172. flat = lines.reshape(-1, 4)
  173. for raw in flat:
  174. xa, ya, xb, yb = (float(v) for v in raw)
  175. dx, dy = xb - xa, yb - ya
  176. length = math.hypot(dx, dy)
  177. if length < 20.0:
  178. continue
  179. if abs(dy) >= 2.0 * abs(dx):
  180. vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb)))
  181. elif abs(dx) >= 2.0 * abs(dy):
  182. horizontal += 1
  183. else:
  184. diagonal += 1
  185. posts = [v for v in vertical if (v[2] - v[1]) >= 0.30 * roi_h]
  186. post_x = _cluster_positions([v[0] for v in posts], gap_px=9.0)
  187. spacings = [post_x[i + 1] - post_x[i] for i in range(len(post_x) - 1)]
  188. spacing_median = float(statistics.median(spacings)) if spacings else None
  189. spacing_cv = None
  190. if len(spacings) >= 2 and spacing_median:
  191. spacing_cv = float(statistics.pstdev(spacings) / spacing_median)
  192. contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  193. rect_contours = 0
  194. for contour in contours:
  195. area = cv2.contourArea(contour)
  196. if area < 180.0 or area > 0.20 * roi_area:
  197. continue
  198. peri = cv2.arcLength(contour, True)
  199. if peri <= 0.0:
  200. continue
  201. approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
  202. if not (4 <= len(approx) <= 6):
  203. continue
  204. _, _, bw, bh = cv2.boundingRect(approx)
  205. if bh <= 0:
  206. continue
  207. aspect = bw / float(bh)
  208. if 0.30 <= aspect <= 3.2:
  209. rect_contours += 1
  210. return {
  211. "vertical_lines": len(posts),
  212. "diagonal_lines": int(diagonal),
  213. "horizontal_lines": int(horizontal),
  214. "rect_contours": int(rect_contours),
  215. "post_count": len(post_x),
  216. "post_spacing_median": spacing_median,
  217. "post_spacing_cv": spacing_cv,
  218. "edge_density": float(edges.mean() / 255.0),
  219. }
  220. def detect_wheels(bgr: np.ndarray, roi: Tuple[int, int, int, int]) -> int:
  221. """箱底以下 ROI 的圆/轮候选数(HoughCircles;只作辅助证据)。"""
  222. x0, y0, x1, y1 = roi
  223. crop = bgr[y0:y1, x0:x1]
  224. if crop.size == 0:
  225. return 0
  226. gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
  227. gray = cv2.medianBlur(gray, 5)
  228. circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=36,
  229. param1=100, param2=26, minRadius=12, maxRadius=60)
  230. if circles is None:
  231. return 0
  232. return int(len(np.asarray(circles).reshape(-1, 3)))
  233. def green_ratio(bgr: np.ndarray, roi: Tuple[int, int, int, int]) -> float:
  234. """ROI 内植被像素占比(HSV 绿;只作辅助证据,地面也可能是灰/褐色)。"""
  235. x0, y0, x1, y1 = roi
  236. crop = bgr[y0:y1, x0:x1]
  237. if crop.size == 0:
  238. return 0.0
  239. hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
  240. mask = cv2.inRange(hsv, (35, 40, 40), (95, 255, 255))
  241. return float(mask.mean() / 255.0)
  242. def measure_frame(bgr: np.ndarray,
  243. frame_index: int,
  244. fps: float,
  245. below_frac: Tuple[float, float, float, float],
  246. ground_frac: Tuple[float, float, float, float],
  247. window_frac: Tuple[float, float, float, float]) -> Dict[str, object]:
  248. """单帧测量:箱底/车面线 + 箱底以下结构 + 辅助线索。"""
  249. height, width = bgr.shape[:2]
  250. gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
  251. window = roi_px(bgr.shape, window_frac)
  252. below = roi_px(bgr.shape, below_frac)
  253. ground = roi_px(bgr.shape, ground_frac)
  254. bright, dark = horizontal_bands(gray, window)
  255. box, bed = pick_box_and_bed(bright, dark, height)
  256. box_bottom = None if box is None else float(box["y1"])
  257. bed_top = None if bed is None else float(bed["y0"])
  258. gap = None
  259. if box_bottom is not None and bed_top is not None:
  260. gap = float(bed_top - box_bottom)
  261. structure = detect_structure(gray, below)
  262. wheels = detect_wheels(bgr, below)
  263. result: Dict[str, object] = {
  264. "frame": int(frame_index),
  265. "t_s": float(frame_index / fps) if fps else 0.0,
  266. "width": int(width),
  267. "height": int(height),
  268. "box_bottom_y": box_bottom,
  269. "bed_top_y": bed_top,
  270. "gap_px": gap,
  271. "gap_over_300px": (gap / 300.0) if gap is not None else None,
  272. "box_bottom_over_h": (box_bottom / float(height)) if box_bottom is not None else None,
  273. "wheel_candidates": int(wheels),
  274. "green_ratio_below": green_ratio(bgr, below),
  275. "green_ratio_ground": green_ratio(bgr, ground),
  276. "bright_bands": bright[:5],
  277. "dark_bands": dark[:5],
  278. }
  279. result.update(structure)
  280. return result
  281. NUMERIC_KEYS = (
  282. "box_bottom_y", "bed_top_y", "gap_px", "gap_over_300px", "box_bottom_over_h",
  283. "vertical_lines", "diagonal_lines", "horizontal_lines", "rect_contours",
  284. "post_count", "post_spacing_median", "post_spacing_cv", "wheel_candidates",
  285. "green_ratio_below", "green_ratio_ground", "edge_density",
  286. )
  287. def _stats(values: Sequence[float]) -> Optional[Dict[str, float]]:
  288. clean = [float(v) for v in values if v is not None and math.isfinite(float(v))]
  289. if not clean:
  290. return None
  291. return {"n": len(clean), "min": min(clean),
  292. "p50": float(statistics.median(clean)), "max": max(clean)}
  293. def summarize(rows: Sequence[Dict[str, object]]) -> Dict[str, object]:
  294. """逐特征分位数 + 箱底间隙的落位代理。"""
  295. summary: Dict[str, object] = {"frames": len(rows), "features": {}}
  296. for key in NUMERIC_KEYS:
  297. summary["features"][key] = _stats([r.get(key) for r in rows])
  298. gaps = [float(r["gap_px"]) for r in rows if r.get("gap_px") is not None]
  299. if gaps:
  300. close = [float(r["frame"]) for r in rows
  301. if r.get("gap_px") is not None and float(r["gap_px"]) <= 25.0]
  302. first_close = rows[min(range(len(rows)), key=lambda i: abs(float(rows[i]["frame"]) - close[0]))] if close else None
  303. summary["commit_proxy"] = {
  304. "rule": "gap_px <= 25(≈0.08 × 300 px 近端箱高;仅代理,不是 PLC 信号)",
  305. "close_frames": len(close),
  306. "first_close_frame": int(close[0]) if close else None,
  307. "first_close_t_s": float(first_close["t_s"]) if first_close else None,
  308. "last_gap_px": float(rows[-1].get("gap_px")) if rows[-1].get("gap_px") is not None else None,
  309. }
  310. else:
  311. summary["commit_proxy"] = {"rule": "gap_px <= 25", "close_frames": 0,
  312. "first_close_frame": None, "first_close_t_s": None,
  313. "last_gap_px": None}
  314. return summary
  315. def separability(a: Dict[str, object], b: Dict[str, object]) -> Dict[str, object]:
  316. """按特征比较 A/B 的 min..max 区间;不重叠才算 P0 可分。"""
  317. out: Dict[str, object] = {}
  318. for key in NUMERIC_KEYS:
  319. fa = (a.get("features") or {}).get(key) # type: ignore[union-attr]
  320. fb = (b.get("features") or {}).get(key) # type: ignore[union-attr]
  321. if not fa or not fb:
  322. out[key] = {"verdict": "n/a"}
  323. continue
  324. if fa["max"] < fb["min"]:
  325. margin = (fb["min"] - fa["max"]) / max(abs(fa["max"]), abs(fb["min"]), 1e-9)
  326. out[key] = {"verdict": "A<B", "margin": float(margin)}
  327. elif fb["max"] < fa["min"]:
  328. margin = (fa["min"] - fb["max"]) / max(abs(fa["min"]), abs(fb["max"]), 1e-9)
  329. out[key] = {"verdict": "B<A", "margin": float(margin)}
  330. else:
  331. out[key] = {"verdict": "overlap"}
  332. return out
  333. def write_jsonl(path: str, rows: Sequence[Dict[str, object]]) -> None:
  334. with open(path, "w", encoding="utf-8") as handle:
  335. for row in rows:
  336. handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
  337. def annotate_frame(bgr: np.ndarray,
  338. row: Dict[str, object],
  339. below: Tuple[int, int, int, int],
  340. ground: Tuple[int, int, int, int],
  341. window: Tuple[int, int, int, int],
  342. clip: str,
  343. out_path: str) -> None:
  344. """画 ROI / 箱底线 / 车面线 / 关键数字,人工复核用。"""
  345. canvas = bgr.copy()
  346. bx0, by0, bx1, by1 = below
  347. gx0, gy0, gx1, gy1 = ground
  348. wx0, wy0, wx1, wy1 = window
  349. cv2.rectangle(canvas, (wx0, wy0), (wx1, wy1), (160, 160, 160), 1)
  350. cv2.rectangle(canvas, (bx0, by0), (bx1, by1), COLOR_ROI, 2)
  351. cv2.rectangle(canvas, (gx0, gy0), (gx1, gy1), COLOR_GROUND, 1)
  352. for band in (row.get("bright_bands") or [])[:4]:
  353. yy = int(round(float(band["y0"])))
  354. cv2.line(canvas, (wx0, yy), (wx1, yy), COLOR_BED, 2)
  355. for band in (row.get("dark_bands") or [])[:4]:
  356. yy = int(round(float(band["y1"])))
  357. cv2.line(canvas, (wx0, yy), (wx1, yy), COLOR_BOX, 2)
  358. if row.get("box_bottom_y") is not None:
  359. yy = int(round(float(row["box_bottom_y"])))
  360. cv2.line(canvas, (bx0, yy), (bx1, yy), COLOR_BOX, 3)
  361. if row.get("bed_top_y") is not None:
  362. yy = int(round(float(row["bed_top_y"])))
  363. cv2.line(canvas, (bx0, yy), (bx1, yy), COLOR_BED, 3)
  364. text = ("%s f%s t=%.1fs gap=%s post=%s rect=%s diag=%s wheel=%s"
  365. % (clip, row.get("frame"), float(row.get("t_s") or 0.0),
  366. "n/a" if row.get("gap_px") is None else "%.0fpx" % float(row["gap_px"]),
  367. row.get("post_count"), row.get("rect_contours"),
  368. row.get("diagonal_lines"), row.get("wheel_candidates")))
  369. cv2.putText(canvas, text, (16, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.62,
  370. (20, 20, 20), 3, cv2.LINE_AA)
  371. cv2.putText(canvas, text, (16, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.62,
  372. (240, 240, 240), 1, cv2.LINE_AA)
  373. cv2.imwrite(out_path, canvas, [cv2.IMWRITE_JPEG_QUALITY, 88])
  374. def _fmt_stats(stat: Optional[Dict[str, float]]) -> str:
  375. if not stat:
  376. return "n/a"
  377. return "n=%d %.1f / %.1f / %.1f" % (int(stat["n"]), stat["min"], stat["p50"], stat["max"])
  378. def _fmt_key_row(row: Dict[str, object]) -> str:
  379. def num(value, fmt="%.1f"):
  380. return "n/a" if value is None else fmt % float(value)
  381. return ("| %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |"
  382. % (row.get("frame"), num(row.get("t_s")), num(row.get("box_bottom_y"), "%.0f"),
  383. num(row.get("bed_top_y"), "%.0f"), num(row.get("gap_px"), "%.0f"),
  384. num(row.get("post_count"), "%.0f"), num(row.get("post_spacing_median"), "%.0f"),
  385. num(row.get("rect_contours"), "%.0f"), num(row.get("diagonal_lines"), "%.0f"),
  386. num(row.get("wheel_candidates"), "%.0f")))
  387. FEATURE_NOTES = {
  388. "box_bottom_y": "箱底 y(原图 px)",
  389. "bed_top_y": "车体上缘 y(墙顶/车面,原图 px)",
  390. "gap_px": "箱底→车体上缘间隙(px)",
  391. "gap_over_300px": "间隙 / 300 px(与既有近端箱高 p50 对齐的代理)",
  392. "box_bottom_over_h": "箱底 y / 画面高",
  393. "post_count": "门板立柱数(箱底以下 ROI)",
  394. "post_spacing_median": "立柱间距中位数(px)",
  395. "post_spacing_cv": "立柱间距离散度(越小越规则)",
  396. "rect_contours": "矩形门(口)候选数",
  397. "diagonal_lines": "斜撑(八)线数",
  398. "horizontal_lines": "水平线数",
  399. "vertical_lines": "竖直线数",
  400. "wheel_candidates": "车轮/圆候选数(HoughCircles)",
  401. "green_ratio_below": "箱底以下 ROI 植被占比",
  402. "green_ratio_ground": "地面带植被占比",
  403. "edge_density": "箱底以下 ROI 边缘密度",
  404. }
  405. def render_report(out_dir: str,
  406. summaries: Dict[str, Dict[str, object]],
  407. pair: Dict[str, object],
  408. key_rows: Dict[str, List[Dict[str, object]]],
  409. metas: Dict[str, Dict[str, object]]) -> str:
  410. """生成 report.md(内容全部来自本次测量,不写死结论)。"""
  411. names = list(summaries.keys())
  412. a_name = "A" if "A" in summaries else (names[0] if names else "A")
  413. b_name = "B" if "B" in summaries else (names[1] if len(names) > 1 else "B")
  414. lines: List[str] = []
  415. lines.append("# P0 v2:A/B 现场片段结构可分性测量")
  416. lines.append("")
  417. lines.append("> 生成:`scripts/p0_v2_measure.py`;本报告只证明**结构可分**,")
  418. lines.append("> 不是最终模型精度,也不替代现场验收。")
  419. lines.append("")
  420. lines.append("## 1. 数据与测量口径")
  421. lines.append("")
  422. lines.append("| 片段 | 文件 | 分辨率 | fps | 总帧 | 时长 | 采样帧数 |")
  423. lines.append("| --- | --- | --- | --- | --- | --- | --- |")
  424. for name in names:
  425. meta = metas.get(name, {})
  426. summary = summaries[name]
  427. lines.append("| %s | `%s` | %dx%d | %.1f | %d | %.1f s | %d |"
  428. % (name, os.path.basename(str(meta.get("path", ""))),
  429. int(meta.get("width", 0)), int(meta.get("height", 0)),
  430. float(meta.get("fps", 0.0)), int(meta.get("frames", 0)),
  431. float(meta.get("duration_s", 0.0)), int(summary.get("frames", 0))))
  432. lines.append("")
  433. lines.append("**固定 ROI(比例坐标,按 1280×720 换算)**:")
  434. lines.append("")
  435. lines.append("* 箱底以下结构 ROI:`x=[0.00,1.00], y=[0.66,0.86]` → `y=475..619`;")
  436. lines.append("* 地面/植被辅助带:`x=[0.00,1.00], y=[0.48,0.68]` → `y=346..490`;")
  437. lines.append("* 水平带搜索窗口:`x=[0.24,0.78], y=[0.10,0.90]`。")
  438. lines.append("")
  439. lines.append("**测量方法**:行均值纵向 Sobel 配对出水平亮/暗带;箱底取上部最高强暗带,")
  440. lines.append("车体上缘取箱底下方 120 px 内最近亮带;箱底以下 ROI 用 CLAHE+Canny+HoughLinesP")
  441. lines.append("统计立柱/斜撑/矩形门,用 HoughCircles 统计车轮候选,用 HSV 统计植被。")
  442. lines.append("")
  443. lines.append("## 2. 逐特征分布(min / p50 / max)")
  444. lines.append("")
  445. lines.append("| 特征 | 含义 | %s | %s |" % (a_name, b_name))
  446. lines.append("| --- | --- | --- | --- |")
  447. for key in NUMERIC_KEYS:
  448. fa = (summaries.get(a_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
  449. fb = (summaries.get(b_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
  450. lines.append("| `%s` | %s | %s | %s |"
  451. % (key, FEATURE_NOTES.get(key, ""), _fmt_stats(fa), _fmt_stats(fb)))
  452. lines.append("")
  453. lines.append("## 3. A/B 区间可分性")
  454. lines.append("")
  455. lines.append("> 只有 **min..max 完全不重叠** 才记为 `A<B` / `B<A`;`overlap` 表示该特征")
  456. lines.append("> 在这两段素材上不能单独定阈值,需要多帧/多结构组合。")
  457. lines.append("")
  458. lines.append("| 特征 | 区间关系 | 相对 margin |")
  459. lines.append("| --- | --- | --- |")
  460. for key, verdict in pair.items():
  461. lines.append("| `%s` | %s | %s |"
  462. % (key, verdict.get("verdict", "n/a"),
  463. "n/a" if verdict.get("margin") is None else "%.2f" % verdict["margin"]))
  464. lines.append("")
  465. key_summaries = {name: summarize(rows) for name, rows in key_rows.items() if rows}
  466. key_pair = (separability(key_summaries.get("A", {}), key_summaries.get("B", {}))
  467. if "A" in key_summaries and "B" in key_summaries else {})
  468. lines.append("## 3b. 关键帧(落位/commit 相位)可分性")
  469. lines.append("")
  470. lines.append("> 关键帧是人工选的**同相位**帧(A 411/978/1100;B 514/1790)。全帧统计会混入")
  471. lines.append("> 箱体移动、不同下放阶段与画面内其他结构,不能直接拿来定阈值;v2 必须在")
  472. lines.append("> commit/落位相位上做多帧累积。")
  473. lines.append("")
  474. lines.append("| 特征 | %s 关键帧 | %s 关键帧 | 区间关系 |" % (a_name, b_name))
  475. lines.append("| --- | --- | --- | --- |")
  476. for key in ("post_count", "post_spacing_median", "post_spacing_cv", "rect_contours",
  477. "diagonal_lines", "wheel_candidates", "green_ratio_ground", "gap_px"):
  478. fa = (key_summaries.get(a_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
  479. fb = (key_summaries.get(b_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
  480. verdict = (key_pair.get(key) or {}).get("verdict", "n/a")
  481. lines.append("| `%s` | %s | %s | %s |"
  482. % (key, _fmt_stats(fa), _fmt_stats(fb), verdict))
  483. lines.append("")
  484. lines.append("## 4. 关键帧测量")
  485. lines.append("")
  486. for name in names:
  487. rows = key_rows.get(name, [])
  488. if not rows:
  489. continue
  490. lines.append("### %s" % name)
  491. lines.append("")
  492. lines.append("| 帧 | t(s) | 箱底 y | 车面 y | 间隙 px | 立柱 | 间距 px | 矩形 | 斜撑 | 车轮 |")
  493. lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
  494. for row in rows:
  495. lines.append(_fmt_key_row(row))
  496. lines.append("")
  497. lines.append("> **注意**:自动箱底线可能被箱内文字/横梁吸附(尤其 A 411 / B 514);")
  498. lines.append("> 几何基准以 `p0_conclusion.md` §2 的人工读数与 `*_annot.jpg` 为准。")
  499. lines.append("")
  500. lines.append("## 5. 落位代理(commit proxy)")
  501. lines.append("")
  502. lines.append("| 片段 | 规则 | 命中帧数 | 首个命中帧 | 首帧时间 | 末帧间隙 |")
  503. lines.append("| --- | --- | --- | --- | --- | --- |")
  504. for name in names:
  505. cp = summaries[name].get("commit_proxy", {})
  506. lines.append("| %s | %s | %s | %s | %s | %s |"
  507. % (name, cp.get("rule", ""), cp.get("close_frames", 0),
  508. cp.get("first_close_frame", "n/a"),
  509. "n/a" if cp.get("first_close_t_s") is None else "%.2f s" % cp["first_close_t_s"],
  510. "n/a" if cp.get("last_gap_px") is None else "%.0f px" % cp["last_gap_px"]))
  511. lines.append("")
  512. lines.append("> `gap_px <= 25` 只是与既有近端箱高 p50≈300 px 对齐的**挑帧代理**,不是 commit 判据。")
  513. lines.append("> **A 的 15 个命中是反例**:f1100 gap≈25 px,按近端标尺≈0.25 m,实际仍差≈0.2 m、未落位。")
  514. lines.append("> P1 的 commit 必须用 `gap_m<=0.10 m` + 结构/稳定帧/运动门控,或 PLC 到位信号;`gap_ratio` 只能粗筛。")
  515. lines.append("")
  516. lines.append("## 6. P0 结论(人读,不替代复核)")
  517. lines.append("")
  518. post = pair.get("post_count", {})
  519. rect = pair.get("rect_contours", {})
  520. wheel = pair.get("wheel_candidates", {})
  521. green = pair.get("green_ratio_ground", {})
  522. key_post = key_pair.get("post_count", {})
  523. key_spacing = key_pair.get("post_spacing_median", {})
  524. key_rect = key_pair.get("rect_contours", {})
  525. key_green = key_pair.get("green_ratio_ground", {})
  526. lines.append("* 全帧自动统计:`post_count` = `%s`,`rect_contours` = `%s`,"
  527. "`wheel_candidates` = `%s`,`green_ratio_ground` = `%s`;"
  528. % (post.get("verdict", "n/a"), rect.get("verdict", "n/a"),
  529. wheel.get("verdict", "n/a"), green.get("verdict", "n/a")))
  530. lines.append("* **关键帧(同相位)**:`post_count` = `%s`,`post_spacing_median` = `%s`,"
  531. "`rect_contours` = `%s`,`green_ratio_ground` = `%s`;"
  532. % (key_post.get("verdict", "n/a"), key_spacing.get("verdict", "n/a"),
  533. key_rect.get("verdict", "n/a"), key_green.get("verdict", "n/a")))
  534. lines.append("* **P0 gate 的判读**:全帧 overlap 主要来自箱体移动/相位混入,不能据此否定")
  535. lines.append(" 结构可分;看**关键帧**:若 `post_count` 呈 `B<A`(敞车门板立柱显著多于平车),")
  536. lines.append(" 说明「箱底以下」结构证据成立。P0 的结论应是:**可分,但必须 phase-aware +")
  537. lines.append(" 多帧累积**;单帧固定 ROI 的全帧统计不足以定阈值。")
  538. lines.append("")
  539. lines.append("## 7. 局限与下一步")
  540. lines.append("")
  541. lines.append("* 本批只有 A/B 两段、同一机位、同一车型组合;**不能**据此估计跨车型/跨机位精度。")
  542. lines.append("* 箱体在近距画面中常被裁掉顶部 → **单帧箱高不是可靠标尺**;")
  543. lines.append(" 前端模式要用多帧累积 + 门板间距/轨距/轮径交叉校验,高吊模式再恢复 2.591 m 主标尺。")
  544. lines.append("* 自动 Hough 计数有噪声(尤其车轮),关键帧已在 `<out>/*_annot.jpg` 里留痕;")
  545. lines.append(" P1 应把本脚本的特征移植为 `evidence_v2` 的**可解释分量**,并加单测。")
  546. lines.append("* 需要补:高吊机位片段、C64K/C70/C80 门板定义、空车语义、PLC commit 信号。")
  547. lines.append("")
  548. report = "\n".join(lines) + "\n"
  549. path = os.path.join(out_dir, "report.md")
  550. with open(path, "w", encoding="utf-8") as handle:
  551. handle.write(report)
  552. return path
  553. def parse_named(items: Sequence[str], kind: str) -> Dict[str, str]:
  554. out: Dict[str, str] = {}
  555. for item in items:
  556. if "=" not in item:
  557. raise SystemExit("%s 需要 NAME=PATH:%s" % (kind, item))
  558. name, path = item.split("=", 1)
  559. name = name.strip()
  560. if not name or not path:
  561. raise SystemExit("%s 的 NAME/PATH 不能为空:%s" % (kind, item))
  562. if not os.path.isfile(path):
  563. raise SystemExit("%s 文件不存在:%s" % (kind, path))
  564. out[name] = path
  565. return out
  566. def parse_key(item: str) -> Tuple[str, int]:
  567. if ":" not in item:
  568. raise SystemExit("--key 需要 TAG:FRAME:%s" % item)
  569. name, frame = item.rsplit(":", 1)
  570. try:
  571. return name.strip(), int(frame)
  572. except ValueError:
  573. raise SystemExit("--key 的 FRAME 必须是整数:%s" % item)
  574. def scan_clip(path: str,
  575. indices: Sequence[int],
  576. fps: float,
  577. below: Tuple[float, float, float, float],
  578. ground: Tuple[float, float, float, float],
  579. window: Tuple[float, float, float, float]) -> Tuple[List[Dict[str, object]], Dict[int, np.ndarray]]:
  580. """顺序读一遍视频,只在目标帧做测量(比逐帧 seek 快且不受关键帧定位影响)。"""
  581. wanted = set(int(v) for v in indices)
  582. rows: List[Dict[str, object]] = []
  583. key_frames: Dict[int, np.ndarray] = {}
  584. cap = cv2.VideoCapture(path)
  585. try:
  586. index = 0
  587. while True:
  588. ok, frame = cap.read()
  589. if not ok:
  590. break
  591. if index in wanted:
  592. row = measure_frame(frame, index, fps, below, ground, window)
  593. rows.append(row)
  594. key_frames[index] = frame
  595. index += 1
  596. finally:
  597. cap.release()
  598. return rows, key_frames
  599. def main(argv: Optional[Sequence[str]] = None) -> int:
  600. parser = argparse.ArgumentParser(description="P0 v2 A/B 结构可分性测量(离线,不 import portcv)")
  601. parser.add_argument("--clip", action="append", required=True, metavar="TAG=PATH",
  602. help="片段名与路径,可重复(建议 A/B)")
  603. parser.add_argument("--out", default="docs/evidence/p0_v2", help="输出目录")
  604. parser.add_argument("--samples", type=int, default=40, help="每段均匀采样帧数(>=2)")
  605. parser.add_argument("--key", action="append", default=[], metavar="TAG:FRAME",
  606. help="关键帧,可重复")
  607. parser.add_argument("--below", type=parse_ratio, default=DEFAULT_BELOW,
  608. help="箱底以下 ROI 比例 x0,y0,x1,y1(默认 0,0.66,1,0.86)")
  609. parser.add_argument("--ground", type=parse_ratio, default=DEFAULT_GROUND,
  610. help="地面/植被带比例(默认 0,0.48,1,0.68)")
  611. parser.add_argument("--window", type=parse_ratio, default=DEFAULT_WINDOW,
  612. help="水平带搜索窗口比例(默认 0.24,0.10,0.78,0.90)")
  613. args = parser.parse_args(argv)
  614. clips = parse_named(args.clip, "--clip")
  615. keys: Dict[str, List[int]] = {}
  616. for item in args.key:
  617. name, frame = parse_key(item)
  618. keys.setdefault(name, []).append(frame)
  619. unknown = sorted(set(keys) - set(clips))
  620. if unknown:
  621. raise SystemExit("--key 引用了不存在的片段:%s" % ", ".join(unknown))
  622. os.makedirs(args.out, exist_ok=True)
  623. summaries: Dict[str, Dict[str, object]] = {}
  624. key_rows: Dict[str, List[Dict[str, object]]] = {}
  625. metas: Dict[str, Dict[str, object]] = {}
  626. for name, path in clips.items():
  627. info = meta(path)
  628. metas[name] = info
  629. fps = float(info["fps"]) or 30.0
  630. total = int(info["frames"])
  631. if total <= 0:
  632. raise SystemExit("片段读不到帧:%s" % path)
  633. count = max(2, int(args.samples))
  634. sampled = sorted({max(0, min(total - 1, int(round(v))))
  635. for v in np.linspace(total * 0.03, total * 0.97, count)})
  636. requested = sorted({max(0, min(total - 1, int(v))) for v in keys.get(name, [])})
  637. indices = sorted(set(sampled) | set(requested))
  638. rows, key_frames = scan_clip(path, indices, fps, args.below, args.ground, args.window)
  639. for row in rows:
  640. row["clip"] = name
  641. write_jsonl(os.path.join(args.out, "%s_per_frame.jsonl" % name), rows)
  642. key_rows[name] = [r for r in rows if int(r["frame"]) in requested]
  643. for index in requested:
  644. row = next((r for r in rows if int(r["frame"]) == index), None)
  645. frame = key_frames.get(index)
  646. if row is None or frame is None:
  647. continue
  648. below = roi_px(frame.shape, args.below)
  649. ground = roi_px(frame.shape, args.ground)
  650. window = roi_px(frame.shape, args.window)
  651. out_path = os.path.join(args.out, "%s_f%06d_annot.jpg" % (name, index))
  652. annotate_frame(frame, row, below, ground, window, name, out_path)
  653. row["annot_image"] = out_path
  654. summary = summarize(rows)
  655. summary["meta"] = info
  656. summaries[name] = summary
  657. print("[%s] frames=%d %s" % (name, len(rows), os.path.basename(path)))
  658. pair = separability(summaries.get("A", {}), summaries.get("B", {})) if "A" in summaries and "B" in summaries else {}
  659. output: Dict[str, object] = {
  660. "method": {
  661. "script": "scripts/p0_v2_measure.py",
  662. "below_roi": args.below,
  663. "ground_roi": args.ground,
  664. "window_roi": args.window,
  665. "box_bottom_rule": "画面上部最高强暗带的下沿",
  666. "bed_top_rule": "箱底下 120px 内最近亮带的上沿",
  667. "commit_proxy": "gap_px <= 25",
  668. },
  669. "clips": summaries,
  670. "separability": pair,
  671. }
  672. with open(os.path.join(args.out, "summary.json"), "w", encoding="utf-8") as handle:
  673. json.dump(output, handle, ensure_ascii=False, indent=2)
  674. handle.write("\n")
  675. report_path = render_report(args.out, summaries, pair, key_rows, metas)
  676. print("summary -> %s" % os.path.join(args.out, "summary.json"))
  677. print("report -> %s" % report_path)
  678. return 0
  679. if __name__ == "__main__":
  680. raise SystemExit(main())