"""P1b:前视 v2 结构证据(箱底以下的门板 / 边梁 / 地面)。 设计依据 -------- ``docs/route_v2.md`` §2–§4 与 P0 实测(``docs/evidence/p0_v2``): * **1(敞车)**:箱底以下是一整面不透明侧墙,门板立柱 ``8–14`` 根、 立柱间距有规律,斜撑/矩形门可作加分;**贴合形态**(箱底与墙顶/箱顶贴住) 必须有"八"字斜撑,防"上层箱坐在下层箱上"被判 1; * **2(平车)**:箱底以下只有薄车面边梁,下方透空,能看到地面/植被; 门板立柱 ``0–4`` 根;**边梁必须是薄边,且下方有车底空隙/阴影暗带**, 否则地面/堆料/下层箱顶会被误判 2; * **0(其他)**:只有连续地面,既无门板阵列也无可信车面边梁。 与 v1 的区别 ------------- v1 用固定高位带(箱底以上 0.55–0.85 箱高)找围挡,方向是错的;本模块 **只在箱底以下**取证,ROI 的 y 起点跟随每帧箱底下沿,不再使用 ``y=475..619`` 的固定带。单帧输出只是“候选”,是否允许提交给 PLC 由 :mod:`portcv.logic.commit` 的 T2 门决定。 工程约束 -------- * 运行期依赖 ``numpy`` + ``opencv-python``(取流层本来就需要 OpenCV); * 所有几何量用**原图像素**输出,内部按 ``work_width`` 缩放; * 单帧确定性:不使用随机数,Hough 参数固定; * 看不清一律内部 255,绝不硬判 2。 """ from __future__ import annotations import math import statistics from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence, Tuple import numpy as np try: # pragma: no cover - 无 OpenCV 时给出明确错误,而不是静默降级 import cv2 except ImportError: # pragma: no cover cv2 = None # type: ignore from ..config import Config from ..schema import Box, CommitPhase, Observation, SceneState, ViewMode from .commit import CommitState, CommitTracker __all__ = [ "Band", "EvidenceV2", "EvidenceV2Params", "EvidenceV2Result", "detect_hoist_high", "detect_spreader_contact", "detect_structure_v2", "find_texture_top", "ground_like_ratio", "horizontal_bands", "pick_box_and_bed", ] Point = Tuple[float, float] @dataclass(frozen=True) class Band: """水平亮带/暗带(原图像素坐标)。""" y0: float y1: float strength: float @property def height(self) -> float: return max(0.0, self.y1 - self.y0) @dataclass(frozen=True) class EvidenceV2Params: """``evidence_v2.*`` 配置(与 ``configs/edge-v2-front.json`` 同名同义)。""" enabled: bool = False view: ViewMode = ViewMode.FRONT work_width: int = 960 window: Tuple[float, float, float, float] = (0.24, 0.02, 0.78, 0.95) band_min_h: int = 3 band_max_h_ratio: float = 0.15 bed_search_ratio: float = 0.40 box_bottom_max_ratio: float = 0.78 below_start_ratio: float = 0.07 below_height_ratio: float = 0.55 below_min_height_px: int = 24 min_door_posts: int = 5 max_door_posts: int = 16 max_bed_gap_px: float = 40.0 flat_max_door_posts: int = 4 max_post_spacing_cv: float = 6.0 min_post_len_ratio: float = 0.30 # P0-Q3:门板立柱间距下限(**原图像素**)。容器侧壁瓦楞周期通常 10~20 px, # C70 门板立柱 63~185 px(docs/edge_evidence.md §4.1)→ 低于该值不构成门板阵列。 # 没有这条时,"上层箱坐在下层箱上"会把下层箱的瓦楞当成车斗门板 → 误判 1。 min_post_spacing_px: float = 24.0 # P0-Q3:门板阵列的 x 跨度下限(占工作宽度)。真实 C70 横跨车体(A 25%~66%), # 平车车轮/制动梁只在窄区给伪立柱(B ~20%)→ 取 0.23(B 挡、A f1100 保留)。 min_post_span_ratio: float = 0.23 # P0-Q4:天空/电线 ROI 约束(与 C++ 同名同义)。 texture_top_enable: bool = True texture_grad_th: float = 50.0 texture_block_px: int = 16 texture_block_hit_ratio: float = 0.03 texture_coverage_min: float = 0.50 texture_run_rows: int = 3 texture_smooth_rows: int = 7 texture_top_margin_ratio: float = 0.02 # P0-Q4:空车/无箱兜底(纹理车体 ROI 再数一次门板立柱) body_fallback_enable: bool = True body_bottom_ratio: float = 0.75 body_min_opacity: float = 0.75 body_min_roi_px: int = 90 # P0-Q3:`1`(敞车)还必须有"八"字斜撑/三角撑证据(docs/edge_evidence.md §4.1)。 # 容器侧壁只有瓦楞、没有斜撑 → 防"上层箱坐在下层箱上"被判成敞车。 # 0 = 关闭该门(只用于对照实验,现场不要关)。 min_diagonal_braces: int = 1 min_wall_opacity: float = 0.35 max_flat_gap_px: float = 40.0 wall_edge_density_ref: float = 0.14 wall_edge_density_span: float = 0.04 ground_block_px: int = 32 ground_density_lo: float = 0.02 ground_density_hi: float = 0.35 min_flat_ground_ratio: float = 0.40 min_zero_ground_ratio: float = 0.65 deck_min_len_ratio: float = 0.30 # P0-Q3:`2`(平车)必须是"薄车面边梁 + 车面下方暗带"。 # 箱底紧贴的亮带若比 contact_max_h_ratio × 估箱高更厚,它不是车面边梁, # 而是地面 / 下层箱顶 / 月台 / 货台等大平面 → 不当作车面、不判 2。 contact_max_h_ratio: float = 0.12 # 车面亮带下方必须在 under_deck_search_h_ratio × 画幅内找到一条更暗的 # under_deck_min_h_ratio × 画幅高的带(车底空隙/阴影);找不到 → 不判 2。 under_deck_dark_delta: float = 12.0 under_deck_min_h_ratio: float = 0.01 under_deck_search_h_ratio: float = 0.10 box_height_m: float = 2.591 px_per_m: float = 0.0 min_scale_px: float = 60.0 motion_diff_max: float = 12.0 motion_grad_ratio_min: float = 0.72 require_commit: bool = True allow_state2: bool = True structure_hits_min: float = 0.60 # P0-0:吊具/钢缆/臂架高悬安全门(默认开)。只在箱体上方区域找 # “长横线 + 上方暗带 + 下方更亮”的组合;宁可弃权,不可把悬空箱 # 当成已落位。 reject_hoist_high: bool = True hoist_dark_max: int = 75 hoist_band_frac: float = 0.035 hoist_line_ratio: float = 0.20 hoist_dark_ratio: float = 0.55 hoist_bright_delta: float = 12.0 def __post_init__(self) -> None: if self.work_width < 160: raise ValueError("work_width 至少 160") if self.band_min_h < 1: raise ValueError("band_min_h 至少 1") if not 0.0 < self.band_max_h_ratio <= 1.0: raise ValueError("band_max_h_ratio 必须在 (0,1]") if self.bed_search_ratio <= 0.0: raise ValueError("bed_search_ratio 必须为正") if self.below_height_ratio <= 0.0: raise ValueError("below_height_ratio 必须为正") if self.min_door_posts < 1: raise ValueError("min_door_posts 至少 1") if not 0.0 < self.contact_max_h_ratio <= 0.5: raise ValueError("contact_max_h_ratio 必须在 (0,0.5]") if self.under_deck_dark_delta < 0.0: raise ValueError("under_deck_dark_delta 不能为负") if not 0.0 < self.under_deck_min_h_ratio <= 0.1: raise ValueError("under_deck_min_h_ratio 必须在 (0,0.1]") if not 0.0 < self.under_deck_search_h_ratio <= 0.5: raise ValueError("under_deck_search_h_ratio 必须在 (0,0.5]") if self.min_post_spacing_px < 0.0: raise ValueError("min_post_spacing_px 不能为负") if not 0.0 <= self.min_post_span_ratio <= 1.0: raise ValueError("min_post_span_ratio 必须在 [0,1]") if self.texture_grad_th <= 0.0: raise ValueError("texture_grad_th 必须 > 0") if self.texture_block_px < 4: raise ValueError("texture_block_px 至少 4") if not 0.0 <= self.texture_block_hit_ratio <= 1.0: raise ValueError("texture_block_hit_ratio 必须在 [0,1]") if not 0.0 <= self.texture_coverage_min <= 1.0: raise ValueError("texture_coverage_min 必须在 [0,1]") if self.texture_run_rows < 1 or self.texture_smooth_rows < 1: raise ValueError("texture_run_rows / texture_smooth_rows 至少 1") if not 0.0 <= self.texture_top_margin_ratio <= 0.5: raise ValueError("texture_top_margin_ratio 必须在 [0,0.5]") if not 0.0 < self.body_bottom_ratio <= 1.0: raise ValueError("body_bottom_ratio 必须在 (0,1]") if not 0.0 <= self.body_min_opacity <= 1.0: raise ValueError("body_min_opacity 必须在 [0,1]") if self.body_min_roi_px < 8: raise ValueError("body_min_roi_px 至少 8") if self.min_diagonal_braces < 0: raise ValueError("min_diagonal_braces 不能为负") if self.box_height_m <= 0.0: raise ValueError("box_height_m 必须为正") @classmethod def from_config(cls, cfg: Config) -> "EvidenceV2Params": raw = cfg.section("evidence_v2") window = raw.get("window") or [0.24, 0.02, 0.78, 0.95] if len(window) != 4: raise ValueError("evidence_v2.window 需要 4 个数字") return cls( enabled=bool(raw.get("enabled", False)), view=ViewMode.parse(raw.get("view", "front")), work_width=int(raw.get("work_width", 960)), window=tuple(float(v) for v in window), # type: ignore[arg-type] band_min_h=int(raw.get("band_min_h", 3)), band_max_h_ratio=float(raw.get("band_max_h_ratio", 0.15)), bed_search_ratio=float(raw.get("bed_search_ratio", 0.40)), box_bottom_max_ratio=float(raw.get("box_bottom_max_ratio", 0.78)), below_start_ratio=float(raw.get("below_start_ratio", 0.07)), below_height_ratio=float(raw.get("below_height_ratio", 0.55)), below_min_height_px=int(raw.get("below_min_height_px", 24)), min_door_posts=int(raw.get("min_door_posts", 5)), max_door_posts=int(raw.get("max_door_posts", 16)), max_bed_gap_px=float(raw.get("max_bed_gap_px", 40.0)), flat_max_door_posts=int(raw.get("flat_max_door_posts", 4)), max_post_spacing_cv=float(raw.get("max_post_spacing_cv", 6.0)), min_post_len_ratio=float(raw.get("min_post_len_ratio", 0.30)), min_post_spacing_px=float(raw.get("min_post_spacing_px", 24.0)), min_post_span_ratio=float(raw.get("min_post_span_ratio", 0.23)), texture_top_enable=bool(raw.get("texture_top_enable", True)), texture_grad_th=float(raw.get("texture_grad_th", 50.0)), texture_block_px=int(raw.get("texture_block_px", 16)), texture_block_hit_ratio=float(raw.get("texture_block_hit_ratio", 0.03)), texture_coverage_min=float(raw.get("texture_coverage_min", 0.50)), texture_run_rows=int(raw.get("texture_run_rows", 3)), texture_smooth_rows=int(raw.get("texture_smooth_rows", 7)), texture_top_margin_ratio=float(raw.get("texture_top_margin_ratio", 0.02)), body_fallback_enable=bool(raw.get("body_fallback_enable", True)), body_bottom_ratio=float(raw.get("body_bottom_ratio", 0.75)), body_min_opacity=float(raw.get("body_min_opacity", 0.75)), body_min_roi_px=int(raw.get("body_min_roi_px", 90)), min_diagonal_braces=int(raw.get("min_diagonal_braces", 1)), min_wall_opacity=float(raw.get("min_wall_opacity", 0.35)), max_flat_gap_px=float(raw.get("max_flat_gap_px", 40.0)), wall_edge_density_ref=float(raw.get("wall_edge_density_ref", 0.14)), wall_edge_density_span=float(raw.get("wall_edge_density_span", 0.04)), ground_block_px=int(raw.get("ground_block_px", 32)), ground_density_lo=float(raw.get("ground_density_lo", 0.02)), ground_density_hi=float(raw.get("ground_density_hi", 0.35)), min_flat_ground_ratio=float(raw.get("min_flat_ground_ratio", 0.40)), min_zero_ground_ratio=float(raw.get("min_zero_ground_ratio", 0.65)), deck_min_len_ratio=float(raw.get("deck_min_len_ratio", 0.30)), contact_max_h_ratio=float(raw.get("contact_max_h_ratio", 0.12)), under_deck_dark_delta=float(raw.get("under_deck_dark_delta", 12.0)), under_deck_min_h_ratio=float(raw.get("under_deck_min_h_ratio", 0.01)), under_deck_search_h_ratio=float(raw.get("under_deck_search_h_ratio", 0.10)), box_height_m=float(raw.get("box_height_m", 2.591)), px_per_m=float(raw.get("px_per_m", 0.0)), min_scale_px=float(raw.get("min_scale_px", 60.0)), motion_diff_max=float(raw.get("motion_diff_max", 12.0)), motion_grad_ratio_min=float(raw.get("motion_grad_ratio_min", 0.72)), require_commit=bool(raw.get("require_commit", True)), allow_state2=bool(raw.get("allow_state2", True)), structure_hits_min=float(raw.get("structure_hits_min", 0.60)), reject_hoist_high=bool(raw.get("reject_hoist_high", True)), hoist_dark_max=int(raw.get("hoist_dark_max", 75)), hoist_band_frac=float(raw.get("hoist_band_frac", 0.035)), hoist_line_ratio=float(raw.get("hoist_line_ratio", 0.20)), hoist_dark_ratio=float(raw.get("hoist_dark_ratio", 0.55)), hoist_bright_delta=float(raw.get("hoist_bright_delta", 12.0)), ) @dataclass class EvidenceV2Result: """单帧 v2 证据与分类结果(所有坐标均为原图像素)。""" state: int = int(SceneState.UNKNOWN) confidence: float = 0.0 view: ViewMode = ViewMode.UNKNOWN box_bottom_y: Optional[float] = None box_top_y: Optional[float] = None texture_top_y: Optional[float] = None box_h_px: Optional[float] = None px_per_m: Optional[float] = None scale_ok: bool = False bed_top_y: Optional[float] = None gap_px: Optional[float] = None gap_m: Optional[float] = None door_posts: int = 0 post_spacing_px: Optional[float] = None post_spacing_cv: Optional[float] = None rect_doors: int = 0 diagonal_braces: int = 0 wall_opacity: float = 0.0 deck_edge: bool = False under_deck: bool = False wheel_count: int = 0 ground_ratio: float = 0.0 phase: CommitPhase = CommitPhase.T1 committed: bool = False commit_reason: str = "init" stable_frames: int = 0 structure_frames: int = 0 motion_ok: bool = True hoist_high: bool = False abstain_reason: str = "" below_roi: Tuple[int, int, int, int] = (0, 0, 0, 0) diagnostics: Dict[str, object] = field(default_factory=dict) @property def candidate_state(self) -> int: """分类候选(未经 commit 门);诊断/回放用。""" return int(self.state) def publishable(self, require_commit: bool = True) -> bool: if int(self.state) not in (0, 1, 2): return False if not require_commit: return True return bool(self.committed) def to_observation( self, ts: float = 0.0, frame_id: int = 0, detections: Optional[Sequence[object]] = None, *, require_commit: bool = True, ) -> Observation: """转成现有 ``TemporalVoter`` 可消费的 ``Observation``。 commit 不成立时输出内部 255(不是 0),并保留分类候选在 reason 里。 """ ok = self.publishable(require_commit) state = int(self.state) if ok else int(SceneState.UNKNOWN) conf = float(self.confidence) if ok else 0.0 reason = "v2:%s view=%s top=%s posts=%d opacity=%.2f deck=%d under_deck=%d gap=%s commit=%s hoist=%d" % ( "ok" if ok else "abstain", self.view.value, "n/a" if self.texture_top_y is None else "%.0f" % self.texture_top_y, int(self.door_posts), float(self.wall_opacity), int(bool(self.deck_edge)), int(bool(self.under_deck)), "n/a" if self.gap_px is None else "%.0fpx" % self.gap_px, self.commit_reason, int(bool(self.hoist_high)), ) if not ok and self.abstain_reason: reason += " reason=%s" % self.abstain_reason return Observation( ts=float(ts), state=state, confidence=conf, detections=list(detections or []), reason=reason, frame_id=int(frame_id), ) def to_dict(self) -> Dict[str, object]: return { "state": int(self.state), "confidence": round(float(self.confidence), 4), "view": self.view.value, "box_bottom_y": _round_opt(self.box_bottom_y), "box_top_y": _round_opt(self.box_top_y), "texture_top_y": _round_opt(self.texture_top_y), "box_h_px": _round_opt(self.box_h_px), "px_per_m": _round_opt(self.px_per_m), "scale_ok": bool(self.scale_ok), "bed_top_y": _round_opt(self.bed_top_y), "gap_px": _round_opt(self.gap_px), "gap_m": _round_opt(self.gap_m, 4), "door_posts": int(self.door_posts), "post_spacing_px": _round_opt(self.post_spacing_px), "post_spacing_cv": _round_opt(self.post_spacing_cv, 3), "rect_doors": int(self.rect_doors), "diagonal_braces": int(self.diagonal_braces), "wall_opacity": round(float(self.wall_opacity), 3), "deck_edge": bool(self.deck_edge), "under_deck": bool(self.under_deck), "wheel_count": int(self.wheel_count), "ground_ratio": round(float(self.ground_ratio), 3), "phase": self.phase.value, "committed": bool(self.committed), "commit_reason": self.commit_reason, "stable_frames": int(self.stable_frames), "structure_frames": int(self.structure_frames), "motion_ok": bool(self.motion_ok), "hoist_high": bool(self.hoist_high), "abstain_reason": self.abstain_reason, "below_roi": [int(v) for v in self.below_roi], "diagnostics": dict(self.diagnostics), } def _round_opt(value: Optional[float], digits: int = 2) -> Optional[float]: if value is None: return None return round(float(value), digits) def _to_gray(image: np.ndarray) -> np.ndarray: if image is None: return np.zeros((0, 0), dtype=np.uint8) if image.ndim == 2: return image.astype(np.uint8, copy=False) if cv2 is None: # pragma: no cover raise RuntimeError("需要 opencv-python 进行彩色转换") if image.shape[2] == 4: return cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) def find_texture_top(gray: np.ndarray, window: Tuple[int, int, int, int], params: EvidenceV2Params) -> float: """P0-Q4:用“竖向梯度块覆盖率”找车体顶;-1 = 未找到/关闭。""" if not params.texture_top_enable or gray.size == 0: return -1.0 gx = np.abs(cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)) x0 = max(0, min(int(window[0]), gray.shape[1])) x1 = min(gray.shape[1], max(x0, int(window[2]))) block = max(4, int(params.texture_block_px)) nb = (x1 - x0) // block if nb < 2: return -1.0 cov = np.zeros(gray.shape[0], dtype=np.float32) for y in range(gray.shape[0]): hit = 0 for i in range(nb): bx = x0 + i * block if float((gx[y, bx:bx + block] >= params.texture_grad_th).mean()) >= \ params.texture_block_hit_ratio: hit += 1 cov[y] = hit / nb smooth = max(1, int(params.texture_smooth_rows)) sm = np.convolve(cov, np.ones(smooth, dtype=np.float32) / smooth, mode="same") run = max(1, int(params.texture_run_rows)) for y in range(max(0, int(window[1])), gray.shape[0] - run + 1): if all(sm[y + k] >= params.texture_coverage_min for k in range(run)): return float(y) return -1.0 def _row_mean(gray: np.ndarray, x0: int, x1: int, y0: int, y1: int) -> float: """``[x0,x1) × [y0,y1)`` 的灰度均值(越界自动钳制;空框返回 0)。""" h, w = gray.shape[:2] xa = max(0, min(int(x0), w)) xb = max(xa, min(int(x1), w)) ya = max(0, min(int(y0), h)) yb = max(ya, min(int(y1), h)) if xb <= xa or yb <= ya: return 0.0 return float(gray[ya:yb, xa:xb].mean()) def horizontal_bands( gray: np.ndarray, roi: Tuple[int, int, int, int], min_h: int = 3, max_h: int = 90, topn: int = 12, ) -> Tuple[List[Band], List[Band]]: """行均值纵向 Sobel 找水平亮带/暗带(P0 算法的生产化版本)。 返回 ``(bright, dark)``;``y0/y1`` 是原图坐标。亮带 = 中间比上下亮, 暗带 = 中间比上下暗。算法只用行均值,因此在箱体移动/局部纹理下比 全画面霍夫更稳定。 """ if cv2 is None: # pragma: no cover raise RuntimeError("evidence_v2 需要 opencv-python") x0, y0, x1, y1 = [int(v) for v in roi] x0 = max(0, x0) y0 = max(0, y0) x1 = min(int(gray.shape[1]), x1) y1 = min(int(gray.shape[0]), y1) if x1 <= x0 or y1 <= y0: return [], [] 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 [], [] if mag.size < 3: return [], [] limit = float(mag.mean() + 0.9 * mag.std()) # 峰值抑制:同一道边缘常在相邻 1~2 行出现两个极值(例如箱底 3 px # 暗带:y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内 # 严格最大:167 会压掉 168,168 又压掉 170,最终只剩一个负峰, # 暗带无法配对,整帧直接 no_box。这里先取 ±1 行局部极大,再按幅值 # 贪心抑制 3 px 内的重复峰,既保留 3 px 薄带,又不拆散同一道边缘。 min_sep = max(2, int(round(min_h))) candidates = [ i for i in range(1, len(mag) - 1) if mag[i] >= limit and mag[i] >= mag[i - 1] and mag[i] >= mag[i + 1] ] picked: List[int] = [] for i in sorted(candidates, key=lambda j: mag[j], reverse=True): if all(abs(i - j) >= min_sep for j in picked): picked.append(i) picked.sort() events: List[Tuple[int, float]] = [(i, float(gy[i])) for i in picked] bright: List[Band] = [] dark: List[Band] = [] 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(Band(float(y0 + i1), float(y0 + i2), strength)) elif v1 < 0.0 < v2: dark.append(Band(float(y0 + i1), float(y0 + i2), strength)) 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: Sequence[Band], dark: Sequence[Band], frame_h: int, *, box_bottom_max_ratio: float = 0.78, bed_search_px: float = 120.0, ) -> Tuple[Optional[Band], Optional[Band]]: """选箱底暗带与它下方最近的车体上缘亮带(与 P0 同口径)。""" upper = [ b for b in dark if b.y1 <= box_bottom_max_ratio * 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) below = [b for b in bright if b.y0 >= box.y1 - 1.0 and b.y0 <= box.y1 + bed_search_px] bed = min(below, key=lambda b: b.y0) if below else None return box, bed def ground_like_ratio( gray: np.ndarray, roi: Tuple[int, int, int, int], segments: Sequence[Dict[str, float]], *, block_px: int = 32, density_lo: float = 0.02, density_hi: float = 0.35, ) -> Tuple[float, int]: """分块“地面样”比例:纹理密度在区间内且块内无长直线。 与 v1 ``edge_evidence.cpp::region_stats`` 的 ``ground_like`` 同口径; 门板立柱是**竖线**、门板横梁/车面边梁是**横线**,两者都算结构面。 """ if cv2 is None: # pragma: no cover return 0.0, 0 x0, y0, x1, y1 = [int(v) for v in roi] crop = gray[y0:y1, x0:x1] if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8: return 0.0, 0 gx = cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3) gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3) mag = np.sqrt(gx * gx + gy * gy) ref = float(np.percentile(mag, 60.0)) hot = mag > ref b = max(6, int(block_px)) total = 0 ground = 0 for by in range(0, crop.shape[0], b): for bx in range(0, crop.shape[1], b): ex = min(crop.shape[1], bx + b) ey = min(crop.shape[0], by + b) block = hot[by:ey, bx:ex] if block.size == 0: continue density = float(block.mean()) long_line = any( float(seg["length"]) >= 0.6 * b and bx + x0 <= (float(seg["x0"]) + float(seg["x1"])) * 0.5 <= ex + x0 and by + y0 <= (float(seg["y0"]) + float(seg["y1"])) * 0.5 <= ey + y0 for seg in segments if "x0" in seg and "x1" in seg and "y0" in seg and "y1" in seg ) total += 1 if not long_line and density_lo <= density <= density_hi: ground += 1 return (float(ground) / float(total) if total else 0.0), total def _cluster_positions(values: Sequence[float], gap_px: float) -> List[float]: ordered = sorted(float(v) for v in values) if not ordered: return [] clusters: List[List[float]] = [[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_v2( gray: np.ndarray, roi: Tuple[int, int, int, int], *, min_post_len_ratio: float = 0.30, cluster_gap_px: float = 9.0, scale: float = 1.0, ) -> Dict[str, object]: """箱底以下 ROI 的门板立柱 / 斜撑 / 矩形门 / 水平边梁。 只做**证据计数**,不做分类;返回的坐标相对 ROI(线段另带 ``y`` 原图坐标,供 deck_edge 使用)。 """ if cv2 is None: # pragma: no cover raise RuntimeError("evidence_v2 需要 opencv-python") x0, y0, x1, y1 = [int(v) for v in roi] crop = gray[y0:y1, x0:x1] empty = { "vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0, "rect_doors": 0, "post_count": 0, "post_positions": [], "post_spacing_median": None, "post_spacing_cv": None, "edge_density": 0.0, "horizontal": [], "lines": [], } if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8: return empty crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop) edges = cv2.Canny(crop, 50, 150) roi_h = max(1, crop.shape[0]) roi_area = float(crop.shape[0] * crop.shape[1]) lines = cv2.HoughLinesP( edges, 1, math.pi / 180.0, threshold=24, minLineLength=max(12, int(round(20 * scale))), maxLineGap=max(4, int(round(8 * scale))), ) vertical: List[Tuple[float, float, float]] = [] horizontal: List[Dict[str, float]] = [] all_lines: List[Dict[str, float]] = [] diagonal = 0 if lines is not None: flat = np.asarray(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 < max(12.0, 20.0 * scale): continue all_lines.append({ "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb), "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb), "length": length, }) if abs(dy) >= 1.8 * abs(dx): vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb))) elif abs(dx) >= 1.8 * abs(dy): horizontal.append({ "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb), "y": y0 + (ya + yb) * 0.5, "length": length, "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb), }) else: diagonal += 1 posts = [v for v in vertical if (v[2] - v[1]) >= min_post_len_ratio * roi_h] post_x = _cluster_positions([v[0] for v in posts], max(3.0, cluster_gap_px * scale)) 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_doors = 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_doors += 1 return { "vertical_lines": len(posts), "diagonal_lines": int(diagonal), "horizontal_lines": len(horizontal), "rect_doors": int(rect_doors), "post_count": len(post_x), "post_positions": [float(x) for x in post_x], "post_spacing_median": spacing_median, "post_spacing_cv": spacing_cv, "edge_density": float(edges.mean() / 255.0), "horizontal": horizontal, "lines": all_lines, } def detect_spreader_contact( gray: np.ndarray, container_bbox: Tuple[float, float, float, float], *, dark_max: int = 110, dark_ratio: float = 0.55, ) -> Tuple[bool, Dict[str, object]]: """检测集装箱上沿紧邻的吊具横梁(吊具仍夹着箱)。 负样本里最典型的误判是:算法把**箱侧壁瓦楞**当成车斗门板,箱底 又恰好贴到画面上某个横向结构,于是 5 帧后 commit。真正落位时, 箱顶上方不应存在一条“紧贴箱顶、横跨箱宽、明显更暗”的横梁;吊具 未松开时这条横梁必然存在。 只使用检测器给出的 container 框(不是 ``box_top`` 自标尺),因此 不受箱高估计误差影响。返回值第二项为诊断。 """ empty = {"spreader_contact": False, "dark_run_px": 0, "band_delta": 0.0} if gray is None or gray.size == 0: return False, empty h, w = gray.shape[:2] x1, y1, x2, y2 = [int(round(v)) for v in container_bbox] x1, x2 = max(0, min(x1, x2)), min(w, max(x1, x2)) y1, y2 = max(0, min(y1, y2)), min(h, max(y1, y2)) box_h = y2 - y1 box_w = x2 - x1 if box_h < 20 or box_w < 20: return False, empty probe = max(4, int(0.30 * box_h)) y0 = max(0, y1 - probe) roi = gray[y0:y1, x1:x2] if roi.shape[0] < 3: return False, empty dark = roi < int(dark_max) frac = dark.mean(axis=1) min_run = max(3, int(0.02 * box_h)) runs = [] run_start = None for row, value in enumerate(frac): if value >= dark_ratio: if run_start is None: run_start = row elif run_start is not None: if (row - run_start) >= min_run: runs.append((run_start, row - 1)) run_start = None if run_start is not None and (len(frac) - run_start) >= min_run: runs.append((run_start, len(frac) - 1)) if not runs: return False, empty # 优先选离箱顶最近的一条暗横梁:吊具夹着箱时它紧贴箱顶;更长的 # 远处吊臂不能替代它,否则会把“远处横梁”误当成“已落位”。 best_start, best_end = min(runs, key=lambda item: (len(frac) - 1 - item[1], item[0] - item[1])) if (len(frac) - 1 - best_end) > max(2, int(0.08 * box_h)): return False, empty band = roi[best_start:best_end + 1, :] below = gray[y1:min(h, y1 + max(6, int(0.06 * box_h))), x1:x2] if band.size == 0 or below.size == 0: return False, empty band_mean = float(band.mean()) below_mean = float(below.mean()) if below_mean < band_mean + 10.0: return False, empty return True, { "spreader_contact": True, "dark_run_px": int(best_end - best_start + 1), "band_delta": round(below_mean - band_mean, 2), } def detect_hoist_high( gray: np.ndarray, box_top_y: float, *, dark_max: int = 75, band_frac: float = 0.035, line_ratio: float = 0.30, dark_ratio: float = 0.55, bright_delta: float = 12.0, ) -> Tuple[bool, Dict[str, object]]: """检测箱体上方的吊具/臂架/钢缆高悬特征。 只看**候选箱体上沿以上**的区域,要求同时满足: * 至少一条横跨画面中央的长横线(Hough); * 横线上方是一条暗带(吊具/臂架本体); * 暗带下方明显更亮(天空、箱顶或车体),说明暗带是遮挡物而不是 箱体本身的暗边。 这三个条件是为了避开集装箱侧壁的竖向瓦楞和车体横梁:A/B 正样本的 箱顶通常已被画幅裁掉(``box_top_y`` 很小),不会进入该区域;负样本 (屏幕录制)上方有明显黑色吊臂/吊具,会被拦下。返回值第二项只用于 诊断,不参与安全判定。 """ empty = {"hoist_high": False, "horizontal_lines": 0, "cables": 0} if cv2 is None or gray is None or gray.size == 0: return False, empty h, w = gray.shape[:2] limit = int(min(max(8.0, float(box_top_y) - 2.0), 0.45 * h)) if limit < max(12, int(0.06 * h)) or w < 32: return False, empty scale = min(1.0, 480.0 / float(w)) if scale < 1.0: work = cv2.resize( gray, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA, ) else: work = gray hh, ww = work.shape[:2] limit_w = min(hh, max(1, int(round(limit * scale)))) roi = work[:limit_w, :] if roi.shape[0] < 12 or roi.shape[1] < 32: return False, empty blur = cv2.GaussianBlur(roi, (5, 5), 0) edges = cv2.Canny(blur, 50, 150) lines = cv2.HoughLinesP( edges, 1, math.pi / 180.0, threshold=15, minLineLength=max(10, int(line_ratio * ww)), maxLineGap=max(4, int(0.03 * ww)), ) horizontal_hits = 0 cables = 0 x0 = int(0.10 * ww) x1 = max(x0 + 8, int(0.90 * ww)) band_h = max(3, int(band_frac * hh)) if lines is not None: for raw in np.asarray(lines).reshape(-1, 4): xa, ya, xb, yb = (float(v) for v in raw) dx, dy = abs(xb - xa), abs(yb - ya) if dx < line_ratio * ww * 0.8: continue # 近水平线:吊具横梁/臂架下缘 if dy <= max(3.0, 0.04 * dx): y = int(round((ya + yb) * 0.5)) if y - band_h < 0 or y + 2 >= limit_w: continue band = blur[y - band_h:y, x0:x1] below = blur[y + 2:min(limit_w, y + 2 + 2 * band_h), x0:x1] if band.size == 0 or below.size == 0: continue dark = float(np.mean(band < int(dark_max))) if dark >= dark_ratio and float(below.mean()) >= float(band.mean()) + bright_delta: horizontal_hits += 1 # 近竖直线:钢缆/油管(只作诊断与辅助确认) elif dy >= max(6.0, 4.0 * dx) and dy >= 0.12 * hh: xs = np.linspace(xa, xb, num=12) ys = np.linspace(ya, yb, num=12) samples = [ blur[int(round(yv)), int(round(xv))] for xv, yv in zip(xs, ys) if 0 <= int(round(yv)) < limit_w and 0 <= int(round(xv)) < ww ] if samples and float(np.mean(samples)) <= float(dark_max) + 25.0: cables += 1 hoist = horizontal_hits >= 1 return hoist, { "hoist_high": bool(hoist), "horizontal_lines": int(horizontal_hits), "cables": int(cables), } class EvidenceV2: """前视 v2 证据提取 + 分类 + commit 门(线程内使用)。""" def __init__(self, params: Optional[EvidenceV2Params] = None, tracker: Optional[CommitTracker] = None) -> None: self.p = params or EvidenceV2Params() self.tracker = tracker or CommitTracker() self._last = EvidenceV2Result(view=self.p.view) self._prev_thumb: Optional[np.ndarray] = None self._prev_mag = 0.0 @classmethod def from_config(cls, cfg: Config) -> "EvidenceV2": return cls(EvidenceV2Params.from_config(cfg), CommitTracker.from_config(cfg)) @property def last(self) -> EvidenceV2Result: return self._last def reset(self) -> None: self.tracker.reset() self._prev_thumb = None self._prev_mag = 0.0 self._last = EvidenceV2Result(view=self.p.view) # ------------------------------------------------------------ 运动门控 def _motion(self, gray: np.ndarray) -> Tuple[bool, float, float]: if cv2 is None: # pragma: no cover return True, 0.0, 1.0 thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA) lap = cv2.Laplacian(thumb, cv2.CV_32F) mag = float(np.abs(lap).mean()) if self._prev_thumb is None: self._prev_thumb = thumb self._prev_mag = mag return True, 0.0, 1.0 diff = float(np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean()) ratio = (mag / self._prev_mag) if self._prev_mag > 1e-6 else 1.0 ok = diff <= self.p.motion_diff_max and ratio >= self.p.motion_grad_ratio_min self._prev_thumb = thumb self._prev_mag = 0.8 * self._prev_mag + 0.2 * mag if self._prev_mag > 0 else mag return ok, diff, ratio # ------------------------------------------------------------ 自标尺 def _scale_from_vertical( self, gray: np.ndarray, box: Band, window: Tuple[int, int, int, int], scale: float, ) -> Tuple[Optional[float], Optional[float]]: """用箱体近端竖棱估 ``px_per_m``;失败返回 ``(None, None)``。""" if cv2 is None: # pragma: no cover return None, None if self.p.px_per_m > 0.0: px_per_m = float(self.p.px_per_m) return px_per_m, None x0, y0, x1, _ = [int(v) for v in window] y1 = max(1, int(box.y0)) crop = gray[max(0, y0):y1, max(0, x0):min(gray.shape[1], x1)] if crop.size == 0: return None, None edges = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop), 50, 150) lines = cv2.HoughLinesP( edges, 1, math.pi / 180.0, threshold=24, minLineLength=max(12, int(self.p.min_scale_px * scale)), maxLineGap=max(4, int(10 * scale)), ) best = 0.0 if lines is not None: for raw in np.asarray(lines).reshape(-1, 4): xa, ya, xb, yb = (float(v) for v in raw) dx, dy = abs(xb - xa), abs(yb - ya) if dy >= 2.0 * dx and dy > best: best = dy if best < self.p.min_scale_px * scale: return None, None px_per_m_work = best / self.p.box_height_m return px_per_m_work / max(scale, 1e-6), best # ------------------------------------------------------------ 分类 def _classify( self, *, posts: int, spacing_cv: Optional[float], opacity: float, ground: float, deck: bool, wheels: int, gap_px: Optional[float], motion_ok: bool, view: ViewMode, under_deck: bool = False, post_spacing_px: Optional[float] = None, diagonal_braces: int = 0, post_span_ratio: float = 0.0, ) -> Tuple[int, float, float, str]: """返回 ``(state, confidence, structure_hits, reason)``。 ``under_deck``:车面亮带下方是否找到"车底空隙/阴影"暗带(P0-Q3)。 ``post_spacing_px``:门板立柱间距(**原图像素**);容器瓦楞 10~20 px, C70 门板 63~185 px。``None``/``<=0`` 表示不可用(不因此拒绝)。 """ if view == ViewMode.UNKNOWN: return int(SceneState.UNKNOWN), 0.0, 0.0, "view_unknown" if not motion_ok: return int(SceneState.UNKNOWN), 0.0, 0.0, "motion" spacing_ok = ( post_spacing_px is None or float(post_spacing_px) <= 0.0 or float(post_spacing_px) >= self.p.min_post_spacing_px ) # P0-Q3:门板阵列必须横跨足够宽;平车的车轮/制动梁伪立柱只在窄区。 span_ok = float(post_span_ratio) >= self.p.min_post_span_ratio # P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。 # 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权; # 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。 contact_bed = gap_px is None or float(gap_px) <= 1.0 doors_ok = (not contact_bed) or ( int(diagonal_braces) >= self.p.min_diagonal_braces ) bed_strong = ( self.p.min_door_posts <= posts <= self.p.max_door_posts and opacity >= self.p.min_wall_opacity and (gap_px is None or gap_px <= self.p.max_bed_gap_px) and (spacing_cv is None or spacing_cv <= self.p.max_post_spacing_cv) and spacing_ok and doors_ok and span_ok ) # 平车:没有门板阵列 + 箱底下有可见车面边梁 + 边梁下方有"车底空隙/阴影"。 # `under_deck` 是 P0-Q3 加的硬门:地面/堆场/下层箱顶只有亮面, # 找不到这条暗带 → 不判 2(宁可 255,绝不允许把地面堆料当平车)。 # 地面比例只作置信度加分:B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。 flat_strong = ( posts <= self.p.flat_max_door_posts and deck and under_deck and (gap_px is None or gap_px <= self.p.max_flat_gap_px) ) if bed_strong and flat_strong: return int(SceneState.UNKNOWN), 0.0, 0.0, "conflict_1_2" if bed_strong: conf = 0.55 + 0.25 * min(1.0, posts / 8.0) + 0.15 * opacity hits = min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity) return int(SceneState.BED), min(1.0, conf), hits, "wall_posts" if flat_strong: conf = 0.60 + 0.20 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0) hits = min(1.0, 0.55 + 0.15 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0)) return int(SceneState.FLATBED), min(1.0, conf), hits, "deck_edge" if posts <= 1 and ground >= self.p.min_zero_ground_ratio and not deck: conf = 0.55 + 0.30 * ground hits = min(1.0, 0.50 + 0.40 * ground) return int(SceneState.NOT_ON_TRAIN), min(1.0, conf), hits, "ground_only" return int(SceneState.UNKNOWN), 0.0, 0.0, "weak_evidence" # ------------------------------------------------------------ 车轮(辅助) @staticmethod def _wheel_count(gray: np.ndarray, roi: Tuple[int, int, int, int], scale: float) -> int: if cv2 is None: # pragma: no cover return 0 x0, y0, x1, y1 = roi crop = gray[y0:y1, x0:x1] if crop.size == 0 or min(crop.shape[:2]) < 40: return 0 crop = cv2.medianBlur(crop, 5) try: circles = cv2.HoughCircles( crop, cv2.HOUGH_GRADIENT, dp=1.2, minDist=max(20, int(36 * scale)), param1=100, param2=26, minRadius=max(7, int(12 * scale)), maxRadius=max(20, int(60 * scale)), ) except cv2.error: # pragma: no cover - 某些精简版 OpenCV return 0 if circles is None: return 0 return int(len(np.asarray(circles).reshape(-1, 3))) # ------------------------------------------------------------ 主入口 def analyze( self, image: np.ndarray, ts: float = 0.0, frame_id: int = 0, *, plc_arrived: bool = False, plc_spreader_released: bool = False, detections: Optional[Sequence[Box]] = None, hoist_high: Optional[bool] = None, ) -> EvidenceV2Result: """提取一帧证据并更新 commit 状态。 ``image`` 可以是灰度或 BGR;坐标一律按**原图**返回。 ``detections`` 是检测器本帧输出(可选);有 container 框时,用 箱顶正上方的暗横梁判断吊具是否仍夹着箱。``hoist_high`` 仅用于 离线回放/单测注入;生产路径由图像 + 检测框自动判定。 """ gray0 = _to_gray(image) if gray0.size == 0: self._last = EvidenceV2Result( view=self.p.view, abstain_reason="no_image", commit_reason="no_image", phase=CommitPhase.T1, ) return self._last h, w = gray0.shape[:2] scale = min(1.0, float(self.p.work_width) / float(w)) if scale < 1.0: gray = cv2.resize(gray0, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA) else: gray = gray0 motion_ok, motion_diff, motion_ratio = self._motion(gray) wh, ww = gray.shape[:2] window = ( int(self.p.window[0] * ww), int(self.p.window[1] * wh), int(self.p.window[2] * ww), int(self.p.window[3] * wh), ) max_h = max(6, int(self.p.band_max_h_ratio * wh)) # P0-Q4:车体顶以上(天空电线/水印)的亮/暗带不参与 box/bed 选择。 texture_top = find_texture_top(gray, window, self.p) bright, dark = horizontal_bands( gray, window, min_h=max(1, int(self.p.band_min_h * scale)), max_h=max_h ) if texture_top > 0.0 and texture_top > window[1] + 0.05 * wh: margin = self.p.texture_top_margin_ratio * wh bright_all, dark_all = list(bright), list(dark) bright = [b for b in bright if b.y1 >= texture_top - margin] dark = [b for b in dark if b.y1 >= texture_top - margin] if not bright: bright = bright_all if not dark: dark = dark_all # 先估一个箱高,用于“车体上缘搜索窗”(P0 固定 120 px 的等价物)。 box_hint = max(80.0, 0.40 * wh) box, bed = pick_box_and_bed( bright, dark, wh, box_bottom_max_ratio=self.p.box_bottom_max_ratio, bed_search_px=max(24.0, self.p.bed_search_ratio * box_hint), ) if box is None and dark: # 兜底:取上半幅最强的暗带(仍要求离顶部有一点距离)。 candidates = [b for b in dark if b.y0 >= 0.03 * wh and b.y1 <= 0.90 * wh] box = max(candidates, key=lambda b: b.strength) if candidates else None if box is None: self._last = EvidenceV2Result( view=self.p.view, motion_ok=motion_ok, abstain_reason="no_box", commit_reason="no_box", phase=CommitPhase.T3 if not motion_ok else CommitPhase.T1, diagnostics={"motion_diff": round(motion_diff, 2), "motion_ratio": round(motion_ratio, 3)}, ) return self._last if bed is None and bright: below = [b for b in bright if b.y0 >= box.y1 - 1.0] bed = min(below, key=lambda b: b.y0) if below else None # P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/ # 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里 # `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。 est_h = max(60.0, box.y0 - 0.05 * wh) thick_contact = False if bed is not None and bed.y0 <= box.y1 + 1.0: if (bed.y1 - bed.y0) > self.p.contact_max_h_ratio * est_h: thick_contact = True bed = None px_per_m, vertical_run = self._scale_from_vertical(gray, box, window, scale) box_h_px = None if px_per_m is not None: box_h_px = px_per_m * self.p.box_height_m elif vertical_run is not None: box_h_px = vertical_run / max(scale, 1e-6) box_top = None if box_h_px is not None: box_top = max(0.0, box.y1 / max(scale, 1e-6) - box_h_px) # P0-0 安全门:看箱体上沿以上有没有吊具/臂架/钢缆。没有可靠箱高时 # 用“箱底暗带往上 0.35 画幅”保守估计,宁可多弃权。 hoist_flag = False hoist_cues: Dict[str, object] = { "hoist_high": False, "horizontal_lines": 0, "cables": 0, } if hoist_high is not None: hoist_flag = bool(hoist_high) hoist_cues = { "hoist_high": bool(hoist_flag), "horizontal_lines": 0, "cables": 0, "injected": True, } elif self.p.reject_hoist_high: # 首选:检测器 container 框 + 箱顶正上方的暗横梁。它比 # “用箱高猜箱顶”稳,因为负样本里箱高估计会被前景集装箱 # 侧壁带偏(i=668 估到 136 px,真实箱顶在 ~208 px)。 container = None for det in detections or []: name = str(getattr(det, "class_name", "") or "").lower() if "container" not in name: continue if container is None or getattr(det, "area", 0.0) > getattr(container, "area", 0.0): container = det if container is not None: contact_flag, contact_cues = detect_spreader_contact( gray0, (container.x1, container.y1, container.x2, container.y2), ) line_flag, line_cues = detect_hoist_high( gray0, float(container.y1), dark_max=self.p.hoist_dark_max, band_frac=self.p.hoist_band_frac, line_ratio=self.p.hoist_line_ratio, dark_ratio=self.p.hoist_dark_ratio, bright_delta=self.p.hoist_bright_delta, ) hoist_flag = bool(contact_flag or line_flag) hoist_cues = dict(contact_cues) hoist_cues.update({ "source": "detector_box", "spreader_contact": bool(contact_flag), "horizontal_lines": int(line_cues.get("horizontal_lines", 0)), "cables": int(line_cues.get("cables", 0)), }) else: probe_top = ( float(box_top) if box_top is not None else max(0.0, box.y0 / max(scale, 1e-6) - 0.35 * h) ) hoist_flag, hoist_cues = detect_hoist_high( gray0, probe_top, dark_max=self.p.hoist_dark_max, band_frac=self.p.hoist_band_frac, line_ratio=self.p.hoist_line_ratio, dark_ratio=self.p.hoist_dark_ratio, bright_delta=self.p.hoist_bright_delta, ) hoist_cues = dict(hoist_cues) hoist_cues["source"] = "image_rows" # 动态 ROI:y 从本帧箱底下沿开始,绝不复用 P0 固定 y=475..619。 # (est_h 在"贴合亮带厚度门"处已算好,此处复用。) # 起点要越过箱体下侧梁/车体上缘的强横线:从箱底下方约 7% 箱高开始。 # 但若箱底已经贴近画面底边,剩余高度不足以再跳过 7%,就只留 2 px # 保护带。否则整段动态 ROI 会落到画面外,平车的车面边梁/地板线 # 完全看不到(本帧 25 px 车面 → deck=False、gap=None → 不能提交 2)。 start = max(2.0, self.p.below_start_ratio * est_h) min_below_h = self.p.below_min_height_px * max(scale, 1e-6) if (wh - 1) - box.y1 <= start + min_below_h: start = 2.0 y0w = min( wh - 2, int(math.ceil(box.y1 + start)), ) below_h = max( min_below_h, min(self.p.below_height_ratio * est_h, 0.30 * wh), ) y1w = min(wh - 1, max(y0w + below_h, box.y1 + 0.10 * est_h)) x0w = max(0, int(0.05 * ww)) x1w = min(ww - 1, int(0.95 * ww)) below_work = (x0w, y0w, x1w, max(y0w + 8, int(y1w))) structure = detect_structure_v2( gray, below_work, min_post_len_ratio=self.p.min_post_len_ratio, cluster_gap_px=9.0, scale=scale, ) posts = int(structure["post_count"]) spacing_median = structure["post_spacing_median"] spacing_cv = structure["post_spacing_cv"] edge_density = float(structure["edge_density"]) ground, ground_blocks = ground_like_ratio( gray, below_work, structure.get("lines", []), # type: ignore[arg-type] block_px=self.p.ground_block_px, density_lo=self.p.ground_density_lo, density_hi=self.p.ground_density_hi, ) if ground_blocks > 0: opacity = max(0.0, min(1.0, 1.0 - ground)) else: span = max(1e-6, float(self.p.wall_edge_density_span)) opacity = max(0.0, min(1.0, (self.p.wall_edge_density_ref - edge_density) / span)) ground = max(0.0, min(1.0, 1.0 - opacity)) below_h_work = max(1.0, below_work[3] - below_work[1]) deck_min_len = max(20.0, self.p.deck_min_len_ratio * 0.55 * ww) deck_edge = any( box.y1 - 2.0 <= float(seg["y"]) <= box.y1 + 0.35 * below_h_work and float(seg["length"]) >= deck_min_len for seg in structure.get("horizontal", []) # type: ignore[union-attr] ) wheels = self._wheel_count(gray, below_work, scale) # P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。 # 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。 # 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。 under_deck = False if bed is not None and (bed.y1 - bed.y0) > 0.0: band_mean = _row_mean(gray, window[0], window[2], bed.y0, bed.y1) probe_h = max(2, int(round(self.p.under_deck_min_h_ratio * wh))) search_h = max(probe_h + 1, int(round(self.p.under_deck_search_h_ratio * wh))) probe_y0 = max(0, int(round(bed.y1))) probe_y1 = min(wh - 1, probe_y0 + search_h) darkest = None for y in range(probe_y0, max(probe_y0 + 1, probe_y1 - probe_h + 1)): value = _row_mean(gray, window[0], window[2], y, y + probe_h) if darkest is None or value < darkest: darkest = value under_deck = ( darkest is not None and darkest <= band_mean - self.p.under_deck_dark_delta ) deck_edge = bool(deck_edge and under_deck) positions = structure.get("post_positions") or [] post_span_ratio = 0.0 if len(positions) >= 2: post_span_ratio = (max(positions) - min(positions)) / max(1.0, float(ww)) gap_px = None if bed is not None: gap_px = max(0.0, (bed.y0 - box.y1) / max(scale, 1e-6)) state, conf, hits, reason = self._classify( posts=posts, spacing_cv=spacing_cv, opacity=opacity, ground=ground, deck=deck_edge, wheels=wheels, gap_px=gap_px, motion_ok=motion_ok, view=self.p.view, under_deck=under_deck, post_spacing_px=( None if spacing_median is None else float(spacing_median) / max(scale, 1e-6) ), diagonal_braces=int(structure["diagonal_lines"]), post_span_ratio=float(post_span_ratio), ) body = None body_roi = None if (self.p.body_fallback_enable and texture_top > 0.0 and state != 1 and texture_top > window[1] + 0.05 * wh): by0 = max(int(window[1]), int(round(texture_top))) by1 = min(int(window[3]), int(round( texture_top + self.p.body_bottom_ratio * (window[3] - texture_top)))) if by1 > by0: body_roi = (window[0], by0, window[2], by1) bst = detect_structure_v2( gray, body_roi, min_post_len_ratio=self.p.min_post_len_ratio, cluster_gap_px=9.0, scale=scale, ) bpos = bst.get("post_positions") or [] bspan = ( (max(bpos) - min(bpos)) / max(1.0, float(body_roi[2] - body_roi[0])) if len(bpos) >= 2 else 0.0 ) bground, bblocks = ground_like_ratio( gray, body_roi, bst.get("lines", []), # type: ignore[arg-type] block_px=self.p.ground_block_px, density_lo=self.p.ground_density_lo, density_hi=self.p.ground_density_hi, ) bopacity = 1.0 - bground if bblocks > 0 else 0.0 bh = (by1 - by0) / max(scale, 1e-6) if (bh >= self.p.body_min_roi_px and int(bst["post_count"]) >= self.p.min_door_posts and bspan >= self.p.min_post_span_ratio and bopacity >= self.p.body_min_opacity and int(bst["diagonal_lines"]) >= self.p.min_diagonal_braces): state = 1 conf = min(1.0, 0.55 + 0.25 * min(1.0, bst["post_count"] / 8.0) + 0.15 * bopacity) hits = min(1.0, 0.40 + 0.05 * bst["post_count"] + 0.20 * bopacity) reason = "body_fallback_wall" gap_px = 0.0 body = { "posts": int(bst["post_count"]), "diagonal": int(bst["diagonal_lines"]), "opacity": bopacity, } gap_m = ( None if gap_px is None or px_per_m is None or px_per_m <= 0.0 else gap_px / px_per_m ) if body is not None: gap_m = 0.0 if (body is None and texture_top > 0.0 and state == 2 and posts == 0 and box.y1 > texture_top + 0.02 * wh): state = 255 conf = 0.0 hits = 0.0 reason = "ambiguous_empty_vehicle" commit = self.tracker.update( ts, state=state, gap_m=gap_m, gap_px=gap_px, structure_hits=hits, motion_ok=motion_ok, view_known=self.p.view != ViewMode.UNKNOWN, plc_arrived=plc_arrived, plc_spreader_released=plc_spreader_released, hoist_high=hoist_flag, ) phase = CommitPhase.T3 if not motion_ok else CommitPhase(commit.phase) result = EvidenceV2Result( state=int(state), confidence=float(conf), view=self.p.view, box_bottom_y=box.y1 / max(scale, 1e-6), box_top_y=box_top, texture_top_y=( None if texture_top <= 0.0 else texture_top / max(scale, 1e-6) ), box_h_px=box_h_px, px_per_m=px_per_m, scale_ok=px_per_m is not None, bed_top_y=None if bed is None else bed.y0 / max(scale, 1e-6), gap_px=gap_px, gap_m=gap_m, door_posts=(body["posts"] if body else posts), post_spacing_px=( None if spacing_median is None else float(spacing_median) / max(scale, 1e-6) ), post_spacing_cv=None if spacing_cv is None else float(spacing_cv), rect_doors=int(structure["rect_doors"]), diagonal_braces=(body["diagonal"] if body else int(structure["diagonal_lines"])), wall_opacity=(body["opacity"] if body else opacity), deck_edge=bool(deck_edge) and body is None, under_deck=bool(under_deck) and body is None, wheel_count=int(wheels), ground_ratio=(1.0 - body["opacity"]) if body else ground, phase=phase, committed=bool(commit.committed), commit_reason=commit.reason, stable_frames=int(commit.stable_frames), structure_frames=int(commit.structure_frames), motion_ok=bool(motion_ok), hoist_high=bool(hoist_flag), abstain_reason=( "hoist_high" if hoist_flag and state in (0, 1, 2) else ("" if state in (0, 1, 2) else reason) ), below_roi=( (int(round(body_roi[0] / scale)), int(round(body_roi[1] / scale)), int(round(body_roi[2] / scale)), int(round(body_roi[3] / scale))) if body else (int(round(below_work[0] / scale)), int(round(below_work[1] / scale)), int(round(below_work[2] / scale)), int(round(below_work[3] / scale))) ), diagnostics={ "class_reason": reason, "texture_top": None if texture_top <= 0.0 else round(texture_top / scale, 2), "body_fallback": bool(body), "box_band": [round(box.y0 / scale, 2), round(box.y1 / scale, 2)], "bed_band": None if bed is None else [round(bed.y0 / scale, 2), round(bed.y1 / scale, 2)], "under_deck": bool(under_deck), "thick_contact": bool(thick_contact), "vertical_run_px": None if vertical_run is None else round(vertical_run / scale, 2), "motion_diff": round(motion_diff, 2), "motion_ratio": round(motion_ratio, 3), "edge_density": round(edge_density, 4), "ground_blocks": int(ground_blocks), "vertical_lines": int(structure["vertical_lines"]), "horizontal_lines": int(structure["horizontal_lines"]), "hoist_cues": dict(hoist_cues), "scale": round(scale, 4), }, ) self._last = result return result def classify(self, image: np.ndarray, ts: float = 0.0, frame_id: int = 0, **kwargs) -> Observation: """``analyze`` + ``to_observation`` 的便捷入口(pipeline 使用)。""" result = self.analyze(image, ts=ts, frame_id=frame_id, **kwargs) return result.to_observation( ts=ts, frame_id=frame_id, require_commit=self.p.require_commit )