| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780 |
- """P0 v2 现场片段可分性测量(独立工具,**不 import portcv**)。
- 为什么单独一个脚本
- ------------------
- ``docs/route_v2.md`` 的 P0 要求先用现场 A/B 片段证明
- 「敞车(1)/ 平车(2)/ 其他(0)」在**箱底以下**的结构上可分,再动
- C++ / Python 生产代码。本脚本只做**离线取证**,输出可逐帧复算的数字:
- * 箱底线、车体上缘线(敞车墙顶 / 平车车面)与两者间隙;
- * 箱底以下固定 ROI 的**门板/立柱**结构(敞车)与**车轮/地面**线索(平车);
- * 箱高在画面中的可见程度、门板间距、落位时刻的代理量。
- 它不参与运行时链路,也不改变任何交付形态;只依赖 numpy + opencv-python,
- 与 ``scripts/field_clip_probe.py`` 的纪律一致。
- 用法::
- python scripts/p0_v2_measure.py \
- --clip A="C:\\field\\7a55d023....mp4" \
- --clip B="C:\\field\\75efb374....mp4" \
- --out docs/evidence/p0_v2 --samples 48 \
- --key A:411 --key A:1100 --key B:514 --key B:1790
- 输出::
- <out>/<TAG>_per_frame.jsonl 逐帧测量(可复算)
- <out>/<TAG>_f000411_annot.jpg 关键帧标注(ROI / 线 / 数字)
- <out>/summary.json 分位数、A/B 可分性、落位代理
- <out>/report.md 给评审看的 P0 报告
- """
- from __future__ import annotations
- import argparse
- import json
- import math
- import os
- import statistics
- from typing import Dict, Iterable, List, Optional, Sequence, Tuple
- import cv2
- import numpy as np
- #: 箱底以下结构 ROI(比例坐标 x0,y0,x1,y1)。A 片段对应 C70 下部门板,
- #: B 片段对应 X70 车面边梁 + 车轮 + 地面;固定 ROI 才能做 A/B 同口径比较。
- DEFAULT_BELOW = (0.00, 0.66, 1.00, 0.86)
- #: 地面/植被带(比例坐标):只作辅助,不单独判 2。
- DEFAULT_GROUND = (0.00, 0.48, 1.00, 0.68)
- #: 水平带搜索窗口(比例坐标):避开画面最左/最右的支架与反光镜。
- DEFAULT_WINDOW = (0.24, 0.10, 0.78, 0.90)
- COLOR_VERTICAL = (60, 220, 60)
- COLOR_DIAGONAL = (0, 220, 255)
- COLOR_HORIZONTAL = (255, 160, 60)
- COLOR_BOX = (40, 40, 240)
- COLOR_BED = (220, 220, 40)
- COLOR_ROI = (60, 220, 60)
- COLOR_GROUND = (255, 60, 255)
- def parse_ratio(text: str) -> Tuple[float, float, float, float]:
- parts = [float(v) for v in text.split(",")]
- if len(parts) != 4:
- raise argparse.ArgumentTypeError("需要 4 个逗号分隔的比例: x0,y0,x1,y1")
- x0, y0, x1, y1 = parts
- if not (0.0 <= x0 < x1 <= 1.0 and 0.0 <= y0 < y1 <= 1.0):
- raise argparse.ArgumentTypeError("比例必须满足 0<=x0<x1<=1、0<=y0<y1<=1")
- return (x0, y0, x1, y1)
- def roi_px(shape: Sequence[int], frac: Tuple[float, float, float, float]) -> Tuple[int, int, int, int]:
- height, width = int(shape[0]), int(shape[1])
- x0, y0, x1, y1 = frac
- return (int(round(x0 * width)), int(round(y0 * height)),
- int(round(x1 * width)), int(round(y1 * height)))
- def grab(path: str, index: int) -> Optional[np.ndarray]:
- cap = cv2.VideoCapture(path)
- try:
- cap.set(cv2.CAP_PROP_POS_FRAMES, int(index))
- ok, frame = cap.read()
- finally:
- cap.release()
- return frame if ok else None
- def meta(path: str) -> Dict[str, object]:
- cap = cv2.VideoCapture(path)
- try:
- fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0)
- frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
- finally:
- cap.release()
- return {"path": path, "width": width, "height": height, "fps": fps,
- "frames": frames, "duration_s": (frames / fps) if fps else 0.0}
- def horizontal_bands(gray: np.ndarray,
- roi: Tuple[int, int, int, int],
- min_h: int = 3,
- max_h: int = 90,
- topn: int = 10) -> Tuple[List[Dict[str, float]], List[Dict[str, float]]]:
- """在 ROI 内用行均值纵向 Sobel 找水平亮带/暗带。
- 返回 ``(bright, dark)``,每一项 ``{"strength", "y0", "y1"}``;
- ``y0/y1`` 是**原图坐标**。亮带 = 中间比上下亮(墙顶亮面 / 车面高光),
- 暗带 = 中间比上下暗(箱体下侧梁 / 门缝阴影 / 车底空隙)。
- """
- x0, y0, x1, y1 = roi
- crop = gray[y0:y1, x0:x1].astype(np.float32)
- if crop.size == 0:
- return [], []
- crop = cv2.GaussianBlur(crop, (3, 3), 0)
- gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
- mag = np.abs(gy)
- if mag.size == 0:
- return [], []
- limit = float(mag.mean() + 0.9 * mag.std())
- events: List[Tuple[int, float]] = []
- 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: List[Dict[str, float]] = []
- dark: List[Dict[str, float]] = []
- for j in range(len(events) - 1):
- i1, v1 = events[j]
- i2, v2 = events[j + 1]
- height = i2 - i1
- if height < min_h or height > max_h:
- continue
- strength = min(abs(v1), abs(v2))
- if strength <= 0.0:
- continue
- if v1 > 0.0 > v2:
- bright.append({"strength": strength, "y0": float(y0 + i1), "y1": float(y0 + i2)})
- elif v1 < 0.0 < v2:
- dark.append({"strength": strength, "y0": float(y0 + i1), "y1": float(y0 + i2)})
- bright.sort(key=lambda b: b["strength"], reverse=True)
- dark.sort(key=lambda b: b["strength"], reverse=True)
- return bright[:topn], dark[:topn]
- def pick_box_and_bed(bright: List[Dict[str, float]],
- dark: List[Dict[str, float]],
- frame_h: int) -> Tuple[Optional[Dict[str, float]], Optional[Dict[str, float]]]:
- """选箱底暗带与它下方最近的车体上缘亮带。
- * 箱底 = 画面上部(``y1 <= 0.68*h``)**最高**的强暗带(下侧梁是暗带);
- * 车体上缘 = 箱底下方 120 px 内**最近**的亮带(敞车墙顶 / 平车车面)。
- """
- upper = [b for b in dark if b["y1"] <= 0.68 * frame_h and b["y0"] >= 0.02 * frame_h]
- if not upper:
- return None, None
- strongest = max(b["strength"] for b in upper)
- strong = [b for b in upper if b["strength"] >= 0.45 * strongest]
- box = min(strong, key=lambda b: b["y0"])
- box_bottom = box["y1"]
- below = [b for b in bright if b["y0"] >= box_bottom + 1.0 and b["y0"] <= box_bottom + 120.0]
- bed = min(below, key=lambda b: b["y0"]) if below else None
- return box, bed
- def _cluster_positions(values: Iterable[float], gap_px: float = 9.0) -> List[float]:
- """把一维位置聚成簇(相邻差 <= gap_px 视为同一根立柱)。"""
- ordered = sorted(float(v) for v in values)
- if not ordered:
- return []
- clusters = [[ordered[0]]]
- for value in ordered[1:]:
- if value - clusters[-1][-1] <= gap_px:
- clusters[-1].append(value)
- else:
- clusters.append([value])
- return [float(statistics.median(c)) for c in clusters]
- def detect_structure(gray: np.ndarray,
- roi: Tuple[int, int, int, int]) -> Dict[str, object]:
- """箱底以下 ROI 的直线/矩形结构:门板立柱、斜撑(八)、矩形门(口)。
- 只做**证据计数**,不做分类;A/B 的阈值得由 P0 分布确定。
- """
- x0, y0, x1, y1 = roi
- crop = gray[y0:y1, x0:x1]
- if crop.size == 0:
- return {"vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0,
- "rect_contours": 0, "post_count": 0, "post_spacing_median": None,
- "post_spacing_cv": None, "edge_density": 0.0}
- crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop)
- edges = cv2.Canny(crop, 50, 150)
- roi_h = max(1, y1 - y0)
- roi_area = float(crop.shape[0] * crop.shape[1])
- lines = cv2.HoughLinesP(edges, 1, math.pi / 180.0, threshold=24,
- minLineLength=20, maxLineGap=8)
- vertical: List[Tuple[float, float, float]] = [] # (x_mid, y_top, y_bottom)
- diagonal = 0
- horizontal = 0
- if lines is not None:
- # OpenCV 4.x 返回 (N,1,4),OpenCV 5.x 可能返回 (N,4);两种都兼容。
- flat = lines.reshape(-1, 4)
- for raw in flat:
- xa, ya, xb, yb = (float(v) for v in raw)
- dx, dy = xb - xa, yb - ya
- length = math.hypot(dx, dy)
- if length < 20.0:
- continue
- if abs(dy) >= 2.0 * abs(dx):
- vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb)))
- elif abs(dx) >= 2.0 * abs(dy):
- horizontal += 1
- else:
- diagonal += 1
- posts = [v for v in vertical if (v[2] - v[1]) >= 0.30 * roi_h]
- post_x = _cluster_positions([v[0] for v in posts], gap_px=9.0)
- spacings = [post_x[i + 1] - post_x[i] for i in range(len(post_x) - 1)]
- spacing_median = float(statistics.median(spacings)) if spacings else None
- spacing_cv = None
- if len(spacings) >= 2 and spacing_median:
- spacing_cv = float(statistics.pstdev(spacings) / spacing_median)
- contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
- rect_contours = 0
- for contour in contours:
- area = cv2.contourArea(contour)
- if area < 180.0 or area > 0.20 * roi_area:
- continue
- peri = cv2.arcLength(contour, True)
- if peri <= 0.0:
- continue
- approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
- if not (4 <= len(approx) <= 6):
- continue
- _, _, bw, bh = cv2.boundingRect(approx)
- if bh <= 0:
- continue
- aspect = bw / float(bh)
- if 0.30 <= aspect <= 3.2:
- rect_contours += 1
- return {
- "vertical_lines": len(posts),
- "diagonal_lines": int(diagonal),
- "horizontal_lines": int(horizontal),
- "rect_contours": int(rect_contours),
- "post_count": len(post_x),
- "post_spacing_median": spacing_median,
- "post_spacing_cv": spacing_cv,
- "edge_density": float(edges.mean() / 255.0),
- }
- def detect_wheels(bgr: np.ndarray, roi: Tuple[int, int, int, int]) -> int:
- """箱底以下 ROI 的圆/轮候选数(HoughCircles;只作辅助证据)。"""
- x0, y0, x1, y1 = roi
- crop = bgr[y0:y1, x0:x1]
- if crop.size == 0:
- return 0
- gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
- gray = cv2.medianBlur(gray, 5)
- circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=36,
- param1=100, param2=26, minRadius=12, maxRadius=60)
- if circles is None:
- return 0
- return int(len(np.asarray(circles).reshape(-1, 3)))
- def green_ratio(bgr: np.ndarray, roi: Tuple[int, int, int, int]) -> float:
- """ROI 内植被像素占比(HSV 绿;只作辅助证据,地面也可能是灰/褐色)。"""
- x0, y0, x1, y1 = roi
- crop = bgr[y0:y1, x0:x1]
- if crop.size == 0:
- return 0.0
- hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
- mask = cv2.inRange(hsv, (35, 40, 40), (95, 255, 255))
- return float(mask.mean() / 255.0)
- def measure_frame(bgr: np.ndarray,
- frame_index: int,
- fps: float,
- below_frac: Tuple[float, float, float, float],
- ground_frac: Tuple[float, float, float, float],
- window_frac: Tuple[float, float, float, float]) -> Dict[str, object]:
- """单帧测量:箱底/车面线 + 箱底以下结构 + 辅助线索。"""
- height, width = bgr.shape[:2]
- gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
- window = roi_px(bgr.shape, window_frac)
- below = roi_px(bgr.shape, below_frac)
- ground = roi_px(bgr.shape, ground_frac)
- bright, dark = horizontal_bands(gray, window)
- box, bed = pick_box_and_bed(bright, dark, height)
- box_bottom = None if box is None else float(box["y1"])
- bed_top = None if bed is None else float(bed["y0"])
- gap = None
- if box_bottom is not None and bed_top is not None:
- gap = float(bed_top - box_bottom)
- structure = detect_structure(gray, below)
- wheels = detect_wheels(bgr, below)
- result: Dict[str, object] = {
- "frame": int(frame_index),
- "t_s": float(frame_index / fps) if fps else 0.0,
- "width": int(width),
- "height": int(height),
- "box_bottom_y": box_bottom,
- "bed_top_y": bed_top,
- "gap_px": gap,
- "gap_over_300px": (gap / 300.0) if gap is not None else None,
- "box_bottom_over_h": (box_bottom / float(height)) if box_bottom is not None else None,
- "wheel_candidates": int(wheels),
- "green_ratio_below": green_ratio(bgr, below),
- "green_ratio_ground": green_ratio(bgr, ground),
- "bright_bands": bright[:5],
- "dark_bands": dark[:5],
- }
- result.update(structure)
- return result
- NUMERIC_KEYS = (
- "box_bottom_y", "bed_top_y", "gap_px", "gap_over_300px", "box_bottom_over_h",
- "vertical_lines", "diagonal_lines", "horizontal_lines", "rect_contours",
- "post_count", "post_spacing_median", "post_spacing_cv", "wheel_candidates",
- "green_ratio_below", "green_ratio_ground", "edge_density",
- )
- def _stats(values: Sequence[float]) -> Optional[Dict[str, float]]:
- clean = [float(v) for v in values if v is not None and math.isfinite(float(v))]
- if not clean:
- return None
- return {"n": len(clean), "min": min(clean),
- "p50": float(statistics.median(clean)), "max": max(clean)}
- def summarize(rows: Sequence[Dict[str, object]]) -> Dict[str, object]:
- """逐特征分位数 + 箱底间隙的落位代理。"""
- summary: Dict[str, object] = {"frames": len(rows), "features": {}}
- for key in NUMERIC_KEYS:
- summary["features"][key] = _stats([r.get(key) for r in rows])
- gaps = [float(r["gap_px"]) for r in rows if r.get("gap_px") is not None]
- if gaps:
- close = [float(r["frame"]) for r in rows
- if r.get("gap_px") is not None and float(r["gap_px"]) <= 25.0]
- first_close = rows[min(range(len(rows)), key=lambda i: abs(float(rows[i]["frame"]) - close[0]))] if close else None
- summary["commit_proxy"] = {
- "rule": "gap_px <= 25(≈0.08 × 300 px 近端箱高;仅代理,不是 PLC 信号)",
- "close_frames": len(close),
- "first_close_frame": int(close[0]) if close else None,
- "first_close_t_s": float(first_close["t_s"]) if first_close else None,
- "last_gap_px": float(rows[-1].get("gap_px")) if rows[-1].get("gap_px") is not None else None,
- }
- else:
- summary["commit_proxy"] = {"rule": "gap_px <= 25", "close_frames": 0,
- "first_close_frame": None, "first_close_t_s": None,
- "last_gap_px": None}
- return summary
- def separability(a: Dict[str, object], b: Dict[str, object]) -> Dict[str, object]:
- """按特征比较 A/B 的 min..max 区间;不重叠才算 P0 可分。"""
- out: Dict[str, object] = {}
- for key in NUMERIC_KEYS:
- fa = (a.get("features") or {}).get(key) # type: ignore[union-attr]
- fb = (b.get("features") or {}).get(key) # type: ignore[union-attr]
- if not fa or not fb:
- out[key] = {"verdict": "n/a"}
- continue
- if fa["max"] < fb["min"]:
- margin = (fb["min"] - fa["max"]) / max(abs(fa["max"]), abs(fb["min"]), 1e-9)
- out[key] = {"verdict": "A<B", "margin": float(margin)}
- elif fb["max"] < fa["min"]:
- margin = (fa["min"] - fb["max"]) / max(abs(fa["min"]), abs(fb["max"]), 1e-9)
- out[key] = {"verdict": "B<A", "margin": float(margin)}
- else:
- out[key] = {"verdict": "overlap"}
- return out
- def write_jsonl(path: str, rows: Sequence[Dict[str, object]]) -> None:
- with open(path, "w", encoding="utf-8") as handle:
- for row in rows:
- handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
- def annotate_frame(bgr: np.ndarray,
- row: Dict[str, object],
- below: Tuple[int, int, int, int],
- ground: Tuple[int, int, int, int],
- window: Tuple[int, int, int, int],
- clip: str,
- out_path: str) -> None:
- """画 ROI / 箱底线 / 车面线 / 关键数字,人工复核用。"""
- canvas = bgr.copy()
- bx0, by0, bx1, by1 = below
- gx0, gy0, gx1, gy1 = ground
- wx0, wy0, wx1, wy1 = window
- cv2.rectangle(canvas, (wx0, wy0), (wx1, wy1), (160, 160, 160), 1)
- cv2.rectangle(canvas, (bx0, by0), (bx1, by1), COLOR_ROI, 2)
- cv2.rectangle(canvas, (gx0, gy0), (gx1, gy1), COLOR_GROUND, 1)
- for band in (row.get("bright_bands") or [])[:4]:
- yy = int(round(float(band["y0"])))
- cv2.line(canvas, (wx0, yy), (wx1, yy), COLOR_BED, 2)
- for band in (row.get("dark_bands") or [])[:4]:
- yy = int(round(float(band["y1"])))
- cv2.line(canvas, (wx0, yy), (wx1, yy), COLOR_BOX, 2)
- if row.get("box_bottom_y") is not None:
- yy = int(round(float(row["box_bottom_y"])))
- cv2.line(canvas, (bx0, yy), (bx1, yy), COLOR_BOX, 3)
- if row.get("bed_top_y") is not None:
- yy = int(round(float(row["bed_top_y"])))
- cv2.line(canvas, (bx0, yy), (bx1, yy), COLOR_BED, 3)
- text = ("%s f%s t=%.1fs gap=%s post=%s rect=%s diag=%s wheel=%s"
- % (clip, row.get("frame"), float(row.get("t_s") or 0.0),
- "n/a" if row.get("gap_px") is None else "%.0fpx" % float(row["gap_px"]),
- row.get("post_count"), row.get("rect_contours"),
- row.get("diagonal_lines"), row.get("wheel_candidates")))
- cv2.putText(canvas, text, (16, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.62,
- (20, 20, 20), 3, cv2.LINE_AA)
- cv2.putText(canvas, text, (16, 28), cv2.FONT_HERSHEY_SIMPLEX, 0.62,
- (240, 240, 240), 1, cv2.LINE_AA)
- cv2.imwrite(out_path, canvas, [cv2.IMWRITE_JPEG_QUALITY, 88])
- def _fmt_stats(stat: Optional[Dict[str, float]]) -> str:
- if not stat:
- return "n/a"
- return "n=%d %.1f / %.1f / %.1f" % (int(stat["n"]), stat["min"], stat["p50"], stat["max"])
- def _fmt_key_row(row: Dict[str, object]) -> str:
- def num(value, fmt="%.1f"):
- return "n/a" if value is None else fmt % float(value)
- return ("| %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |"
- % (row.get("frame"), num(row.get("t_s")), num(row.get("box_bottom_y"), "%.0f"),
- num(row.get("bed_top_y"), "%.0f"), num(row.get("gap_px"), "%.0f"),
- num(row.get("post_count"), "%.0f"), num(row.get("post_spacing_median"), "%.0f"),
- num(row.get("rect_contours"), "%.0f"), num(row.get("diagonal_lines"), "%.0f"),
- num(row.get("wheel_candidates"), "%.0f")))
- FEATURE_NOTES = {
- "box_bottom_y": "箱底 y(原图 px)",
- "bed_top_y": "车体上缘 y(墙顶/车面,原图 px)",
- "gap_px": "箱底→车体上缘间隙(px)",
- "gap_over_300px": "间隙 / 300 px(与既有近端箱高 p50 对齐的代理)",
- "box_bottom_over_h": "箱底 y / 画面高",
- "post_count": "门板立柱数(箱底以下 ROI)",
- "post_spacing_median": "立柱间距中位数(px)",
- "post_spacing_cv": "立柱间距离散度(越小越规则)",
- "rect_contours": "矩形门(口)候选数",
- "diagonal_lines": "斜撑(八)线数",
- "horizontal_lines": "水平线数",
- "vertical_lines": "竖直线数",
- "wheel_candidates": "车轮/圆候选数(HoughCircles)",
- "green_ratio_below": "箱底以下 ROI 植被占比",
- "green_ratio_ground": "地面带植被占比",
- "edge_density": "箱底以下 ROI 边缘密度",
- }
- def render_report(out_dir: str,
- summaries: Dict[str, Dict[str, object]],
- pair: Dict[str, object],
- key_rows: Dict[str, List[Dict[str, object]]],
- metas: Dict[str, Dict[str, object]]) -> str:
- """生成 report.md(内容全部来自本次测量,不写死结论)。"""
- names = list(summaries.keys())
- a_name = "A" if "A" in summaries else (names[0] if names else "A")
- b_name = "B" if "B" in summaries else (names[1] if len(names) > 1 else "B")
- lines: List[str] = []
- lines.append("# P0 v2:A/B 现场片段结构可分性测量")
- lines.append("")
- lines.append("> 生成:`scripts/p0_v2_measure.py`;本报告只证明**结构可分**,")
- lines.append("> 不是最终模型精度,也不替代现场验收。")
- lines.append("")
- lines.append("## 1. 数据与测量口径")
- lines.append("")
- lines.append("| 片段 | 文件 | 分辨率 | fps | 总帧 | 时长 | 采样帧数 |")
- lines.append("| --- | --- | --- | --- | --- | --- | --- |")
- for name in names:
- meta = metas.get(name, {})
- summary = summaries[name]
- lines.append("| %s | `%s` | %dx%d | %.1f | %d | %.1f s | %d |"
- % (name, os.path.basename(str(meta.get("path", ""))),
- int(meta.get("width", 0)), int(meta.get("height", 0)),
- float(meta.get("fps", 0.0)), int(meta.get("frames", 0)),
- float(meta.get("duration_s", 0.0)), int(summary.get("frames", 0))))
- lines.append("")
- lines.append("**固定 ROI(比例坐标,按 1280×720 换算)**:")
- lines.append("")
- lines.append("* 箱底以下结构 ROI:`x=[0.00,1.00], y=[0.66,0.86]` → `y=475..619`;")
- lines.append("* 地面/植被辅助带:`x=[0.00,1.00], y=[0.48,0.68]` → `y=346..490`;")
- lines.append("* 水平带搜索窗口:`x=[0.24,0.78], y=[0.10,0.90]`。")
- lines.append("")
- lines.append("**测量方法**:行均值纵向 Sobel 配对出水平亮/暗带;箱底取上部最高强暗带,")
- lines.append("车体上缘取箱底下方 120 px 内最近亮带;箱底以下 ROI 用 CLAHE+Canny+HoughLinesP")
- lines.append("统计立柱/斜撑/矩形门,用 HoughCircles 统计车轮候选,用 HSV 统计植被。")
- lines.append("")
- lines.append("## 2. 逐特征分布(min / p50 / max)")
- lines.append("")
- lines.append("| 特征 | 含义 | %s | %s |" % (a_name, b_name))
- lines.append("| --- | --- | --- | --- |")
- for key in NUMERIC_KEYS:
- fa = (summaries.get(a_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
- fb = (summaries.get(b_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
- lines.append("| `%s` | %s | %s | %s |"
- % (key, FEATURE_NOTES.get(key, ""), _fmt_stats(fa), _fmt_stats(fb)))
- lines.append("")
- lines.append("## 3. A/B 区间可分性")
- lines.append("")
- lines.append("> 只有 **min..max 完全不重叠** 才记为 `A<B` / `B<A`;`overlap` 表示该特征")
- lines.append("> 在这两段素材上不能单独定阈值,需要多帧/多结构组合。")
- lines.append("")
- lines.append("| 特征 | 区间关系 | 相对 margin |")
- lines.append("| --- | --- | --- |")
- for key, verdict in pair.items():
- lines.append("| `%s` | %s | %s |"
- % (key, verdict.get("verdict", "n/a"),
- "n/a" if verdict.get("margin") is None else "%.2f" % verdict["margin"]))
- lines.append("")
- key_summaries = {name: summarize(rows) for name, rows in key_rows.items() if rows}
- key_pair = (separability(key_summaries.get("A", {}), key_summaries.get("B", {}))
- if "A" in key_summaries and "B" in key_summaries else {})
- lines.append("## 3b. 关键帧(落位/commit 相位)可分性")
- lines.append("")
- lines.append("> 关键帧是人工选的**同相位**帧(A 411/978/1100;B 514/1790)。全帧统计会混入")
- lines.append("> 箱体移动、不同下放阶段与画面内其他结构,不能直接拿来定阈值;v2 必须在")
- lines.append("> commit/落位相位上做多帧累积。")
- lines.append("")
- lines.append("| 特征 | %s 关键帧 | %s 关键帧 | 区间关系 |" % (a_name, b_name))
- lines.append("| --- | --- | --- | --- |")
- for key in ("post_count", "post_spacing_median", "post_spacing_cv", "rect_contours",
- "diagonal_lines", "wheel_candidates", "green_ratio_ground", "gap_px"):
- fa = (key_summaries.get(a_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
- fb = (key_summaries.get(b_name, {}).get("features") or {}).get(key) # type: ignore[union-attr]
- verdict = (key_pair.get(key) or {}).get("verdict", "n/a")
- lines.append("| `%s` | %s | %s | %s |"
- % (key, _fmt_stats(fa), _fmt_stats(fb), verdict))
- lines.append("")
- lines.append("## 4. 关键帧测量")
- lines.append("")
- for name in names:
- rows = key_rows.get(name, [])
- if not rows:
- continue
- lines.append("### %s" % name)
- lines.append("")
- lines.append("| 帧 | t(s) | 箱底 y | 车面 y | 间隙 px | 立柱 | 间距 px | 矩形 | 斜撑 | 车轮 |")
- lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
- for row in rows:
- lines.append(_fmt_key_row(row))
- lines.append("")
- lines.append("> **注意**:自动箱底线可能被箱内文字/横梁吸附(尤其 A 411 / B 514);")
- lines.append("> 几何基准以 `p0_conclusion.md` §2 的人工读数与 `*_annot.jpg` 为准。")
- lines.append("")
- lines.append("## 5. 落位代理(commit proxy)")
- lines.append("")
- lines.append("| 片段 | 规则 | 命中帧数 | 首个命中帧 | 首帧时间 | 末帧间隙 |")
- lines.append("| --- | --- | --- | --- | --- | --- |")
- for name in names:
- cp = summaries[name].get("commit_proxy", {})
- lines.append("| %s | %s | %s | %s | %s | %s |"
- % (name, cp.get("rule", ""), cp.get("close_frames", 0),
- cp.get("first_close_frame", "n/a"),
- "n/a" if cp.get("first_close_t_s") is None else "%.2f s" % cp["first_close_t_s"],
- "n/a" if cp.get("last_gap_px") is None else "%.0f px" % cp["last_gap_px"]))
- lines.append("")
- lines.append("> `gap_px <= 25` 只是与既有近端箱高 p50≈300 px 对齐的**挑帧代理**,不是 commit 判据。")
- lines.append("> **A 的 15 个命中是反例**:f1100 gap≈25 px,按近端标尺≈0.25 m,实际仍差≈0.2 m、未落位。")
- lines.append("> P1 的 commit 必须用 `gap_m<=0.10 m` + 结构/稳定帧/运动门控,或 PLC 到位信号;`gap_ratio` 只能粗筛。")
- lines.append("")
- lines.append("## 6. P0 结论(人读,不替代复核)")
- lines.append("")
- post = pair.get("post_count", {})
- rect = pair.get("rect_contours", {})
- wheel = pair.get("wheel_candidates", {})
- green = pair.get("green_ratio_ground", {})
- key_post = key_pair.get("post_count", {})
- key_spacing = key_pair.get("post_spacing_median", {})
- key_rect = key_pair.get("rect_contours", {})
- key_green = key_pair.get("green_ratio_ground", {})
- lines.append("* 全帧自动统计:`post_count` = `%s`,`rect_contours` = `%s`,"
- "`wheel_candidates` = `%s`,`green_ratio_ground` = `%s`;"
- % (post.get("verdict", "n/a"), rect.get("verdict", "n/a"),
- wheel.get("verdict", "n/a"), green.get("verdict", "n/a")))
- lines.append("* **关键帧(同相位)**:`post_count` = `%s`,`post_spacing_median` = `%s`,"
- "`rect_contours` = `%s`,`green_ratio_ground` = `%s`;"
- % (key_post.get("verdict", "n/a"), key_spacing.get("verdict", "n/a"),
- key_rect.get("verdict", "n/a"), key_green.get("verdict", "n/a")))
- lines.append("* **P0 gate 的判读**:全帧 overlap 主要来自箱体移动/相位混入,不能据此否定")
- lines.append(" 结构可分;看**关键帧**:若 `post_count` 呈 `B<A`(敞车门板立柱显著多于平车),")
- lines.append(" 说明「箱底以下」结构证据成立。P0 的结论应是:**可分,但必须 phase-aware +")
- lines.append(" 多帧累积**;单帧固定 ROI 的全帧统计不足以定阈值。")
- lines.append("")
- lines.append("## 7. 局限与下一步")
- lines.append("")
- lines.append("* 本批只有 A/B 两段、同一机位、同一车型组合;**不能**据此估计跨车型/跨机位精度。")
- lines.append("* 箱体在近距画面中常被裁掉顶部 → **单帧箱高不是可靠标尺**;")
- lines.append(" 前端模式要用多帧累积 + 门板间距/轨距/轮径交叉校验,高吊模式再恢复 2.591 m 主标尺。")
- lines.append("* 自动 Hough 计数有噪声(尤其车轮),关键帧已在 `<out>/*_annot.jpg` 里留痕;")
- lines.append(" P1 应把本脚本的特征移植为 `evidence_v2` 的**可解释分量**,并加单测。")
- lines.append("* 需要补:高吊机位片段、C64K/C70/C80 门板定义、空车语义、PLC commit 信号。")
- lines.append("")
- report = "\n".join(lines) + "\n"
- path = os.path.join(out_dir, "report.md")
- with open(path, "w", encoding="utf-8") as handle:
- handle.write(report)
- return path
- def parse_named(items: Sequence[str], kind: str) -> Dict[str, str]:
- out: Dict[str, str] = {}
- for item in items:
- if "=" not in item:
- raise SystemExit("%s 需要 NAME=PATH:%s" % (kind, item))
- name, path = item.split("=", 1)
- name = name.strip()
- if not name or not path:
- raise SystemExit("%s 的 NAME/PATH 不能为空:%s" % (kind, item))
- if not os.path.isfile(path):
- raise SystemExit("%s 文件不存在:%s" % (kind, path))
- out[name] = path
- return out
- def parse_key(item: str) -> Tuple[str, int]:
- if ":" not in item:
- raise SystemExit("--key 需要 TAG:FRAME:%s" % item)
- name, frame = item.rsplit(":", 1)
- try:
- return name.strip(), int(frame)
- except ValueError:
- raise SystemExit("--key 的 FRAME 必须是整数:%s" % item)
- def scan_clip(path: str,
- indices: Sequence[int],
- fps: float,
- below: Tuple[float, float, float, float],
- ground: Tuple[float, float, float, float],
- window: Tuple[float, float, float, float]) -> Tuple[List[Dict[str, object]], Dict[int, np.ndarray]]:
- """顺序读一遍视频,只在目标帧做测量(比逐帧 seek 快且不受关键帧定位影响)。"""
- wanted = set(int(v) for v in indices)
- rows: List[Dict[str, object]] = []
- key_frames: Dict[int, np.ndarray] = {}
- cap = cv2.VideoCapture(path)
- try:
- index = 0
- while True:
- ok, frame = cap.read()
- if not ok:
- break
- if index in wanted:
- row = measure_frame(frame, index, fps, below, ground, window)
- rows.append(row)
- key_frames[index] = frame
- index += 1
- finally:
- cap.release()
- return rows, key_frames
- def main(argv: Optional[Sequence[str]] = None) -> int:
- parser = argparse.ArgumentParser(description="P0 v2 A/B 结构可分性测量(离线,不 import portcv)")
- parser.add_argument("--clip", action="append", required=True, metavar="TAG=PATH",
- help="片段名与路径,可重复(建议 A/B)")
- parser.add_argument("--out", default="docs/evidence/p0_v2", help="输出目录")
- parser.add_argument("--samples", type=int, default=40, help="每段均匀采样帧数(>=2)")
- parser.add_argument("--key", action="append", default=[], metavar="TAG:FRAME",
- help="关键帧,可重复")
- parser.add_argument("--below", type=parse_ratio, default=DEFAULT_BELOW,
- help="箱底以下 ROI 比例 x0,y0,x1,y1(默认 0,0.66,1,0.86)")
- parser.add_argument("--ground", type=parse_ratio, default=DEFAULT_GROUND,
- help="地面/植被带比例(默认 0,0.48,1,0.68)")
- parser.add_argument("--window", type=parse_ratio, default=DEFAULT_WINDOW,
- help="水平带搜索窗口比例(默认 0.24,0.10,0.78,0.90)")
- args = parser.parse_args(argv)
- clips = parse_named(args.clip, "--clip")
- keys: Dict[str, List[int]] = {}
- for item in args.key:
- name, frame = parse_key(item)
- keys.setdefault(name, []).append(frame)
- unknown = sorted(set(keys) - set(clips))
- if unknown:
- raise SystemExit("--key 引用了不存在的片段:%s" % ", ".join(unknown))
- os.makedirs(args.out, exist_ok=True)
- summaries: Dict[str, Dict[str, object]] = {}
- key_rows: Dict[str, List[Dict[str, object]]] = {}
- metas: Dict[str, Dict[str, object]] = {}
- for name, path in clips.items():
- info = meta(path)
- metas[name] = info
- fps = float(info["fps"]) or 30.0
- total = int(info["frames"])
- if total <= 0:
- raise SystemExit("片段读不到帧:%s" % path)
- count = max(2, int(args.samples))
- sampled = sorted({max(0, min(total - 1, int(round(v))))
- for v in np.linspace(total * 0.03, total * 0.97, count)})
- requested = sorted({max(0, min(total - 1, int(v))) for v in keys.get(name, [])})
- indices = sorted(set(sampled) | set(requested))
- rows, key_frames = scan_clip(path, indices, fps, args.below, args.ground, args.window)
- for row in rows:
- row["clip"] = name
- write_jsonl(os.path.join(args.out, "%s_per_frame.jsonl" % name), rows)
- key_rows[name] = [r for r in rows if int(r["frame"]) in requested]
- for index in requested:
- row = next((r for r in rows if int(r["frame"]) == index), None)
- frame = key_frames.get(index)
- if row is None or frame is None:
- continue
- below = roi_px(frame.shape, args.below)
- ground = roi_px(frame.shape, args.ground)
- window = roi_px(frame.shape, args.window)
- out_path = os.path.join(args.out, "%s_f%06d_annot.jpg" % (name, index))
- annotate_frame(frame, row, below, ground, window, name, out_path)
- row["annot_image"] = out_path
- summary = summarize(rows)
- summary["meta"] = info
- summaries[name] = summary
- print("[%s] frames=%d %s" % (name, len(rows), os.path.basename(path)))
- pair = separability(summaries.get("A", {}), summaries.get("B", {})) if "A" in summaries and "B" in summaries else {}
- output: Dict[str, object] = {
- "method": {
- "script": "scripts/p0_v2_measure.py",
- "below_roi": args.below,
- "ground_roi": args.ground,
- "window_roi": args.window,
- "box_bottom_rule": "画面上部最高强暗带的下沿",
- "bed_top_rule": "箱底下 120px 内最近亮带的上沿",
- "commit_proxy": "gap_px <= 25",
- },
- "clips": summaries,
- "separability": pair,
- }
- with open(os.path.join(args.out, "summary.json"), "w", encoding="utf-8") as handle:
- json.dump(output, handle, ensure_ascii=False, indent=2)
- handle.write("\n")
- report_path = render_report(args.out, summaries, pair, key_rows, metas)
- print("summary -> %s" % os.path.join(args.out, "summary.json"))
- print("report -> %s" % report_path)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|