"""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.50 body_min_roi_px: int = 90 # 车体兜底 ROI 里"立柱"的最短长度(占 ROI 高)。必须比主判据的 # `min_post_len_ratio`(0.30)短:集装箱/敞车的竖棱常被锈迹、铆钉打断成 # 60~120 px 的短段,用 0.30 会一根都数不到(1920 宽图上实测 posts=0)。 body_min_post_len_ratio: float = 0.15 body_x_margin_ratio: float = 0.03 body_min_posts: int = 3 # P0-Q6:箱底暗带缺失时(罐箱箱底被车帮挡住)“只看车体”的判据。 # 立柱跨度下限:敞车横跨整车(实测 0.66~0.92),平车上集装箱波纹只占中间 # 一段(0.36~0.45)→ 用跨度而不是立柱个数区分;上限放宽是因为 C++ 线段 # 通道会把门框/铰链算成多根(C70E 实测 20 根)。 vehicle_min_span_ratio: float = 0.50 vehicle_max_posts: int = 60 # P0-Q9:空车(敞车、车斗内无箱)识别 → `state=3`。 # 判据只用车体侧墙顶线(texture_top)以下那一片侧墙,要求它是**完整的一节 # 敞车侧墙**:门板立柱 3~16 根、横跨 ≥empty_min_span_ratio、侧墙不透明占比 # 高、有“八”字斜撑,并且这段侧墙在画面里足够高(≥empty_min_wall_h_ratio)。 # 载车为什么过不了: # * 平车 + 集装箱 → 侧墙 ROI 其实是集装箱瓦楞(18~63 根 > max_door_posts); # * 敞车 + 罐箱(箱底被车帮挡住)→ 车帮被箱压到画面底部,可见墙高只有 # ~13%(实测 04_container_on_gondola),`empty_min_wall_h_ratio` 挡掉。 empty_vehicle_enable: bool = True empty_min_posts: int = 3 empty_min_span_ratio: float = 0.60 empty_min_opacity: float = 0.55 empty_min_wall_h_ratio: float = 0.25 # 空车判据专用的“竖棱最短长度 / 侧墙 ROI 高”。必须比 `body_min_post_len_ratio` # (0.15)严:真正敞车门板立柱贯穿侧墙(>0.5×ROI),而平车车面下方的地面/噪声 # 只有碎短竖棱;用 0.15 会把地面当成“完整敞车侧墙” → 把 2 压成 3/255。 empty_min_post_len_ratio: float = 0.30 # 低分辨率/低对比素材的**有界兜底**:严格竖棱门数不到时,允许用宽松门 # (`body_min_post_len_ratio`)再量一次,但只接受“**极少数**立柱” # (≤ empty_fallback_max_posts)且跨度 ≥0.70 的情况 —— 512 压缩的空 C70EA # 实测严格门 0 根 / 宽松门 3 根;而平车+蓝箱(NX70A)宽松门会聚成 7 根, # 正好被这条上限挡住(否则载车会被判成空车)。 empty_fallback_max_posts: int = 4 # 空车判据的斜撑门(与 `min_diagonal_braces` 分开,便于现场按车型单独放宽)。 empty_min_diagonal_braces: int = 1 # ---- P0-Q10:空平车(平车、车面裸露)→ 也输出 state=3 ---- # 平车没有侧墙,空载时直接看到**车底板**:薄车面边梁 + 车底透空 + 边梁上方是 # 一片光滑亮面(车面),且**没有箱底暗带紧贴边梁**(载车的箱底阴影必然贴着边梁, # 实测 01/img00/img01 三张载车样本 gap=0)。 empty_flatbed_enable: bool = True # 车面纵深下限(原图像素):近侧边梁 → 车面远端边缘线。载车 gap≈0 → 直接排除。 empty_flatbed_min_gap_px: float = 16.0 # 车面 ROI 的边缘覆盖率上限(竖向/横向):车面几乎无纹理,集装箱侧壁有瓦楞/立柱。 empty_flatbed_max_plane_edge: float = 0.12 # 车面灰度相对边梁的最大下降(灰阶):车面是亮面,车底/阴影/地面会明显更暗。 empty_flatbed_max_gray_drop: float = 80.0 # 车体顶相对搜索窗顶的最小余量(×画幅高)。0 = 不设门槛:车把画面填满 # (`02_C70E` 实测 texture_top≈2% 画幅)时也用整个窗口做侧墙 ROI,靠 # `empty_*` 那组门来判断——否则“空车占满画面”这一类永远进不来。 empty_top_margin_ratio: float = 0.0 # 空车 `3` 是否允许提交(与 allow_state2 同级;false = 只识别、不提交)。 allow_state3: bool = True # 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_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 # 箱底以下动态 ROI 的最小高度(**原图像素**):太矮时立柱只有 20~27 px, # 与地面/钢轨纹理不可区分 → 不判 1(与 C++ `min_bed_roi_px` 同口径)。 min_bed_roi_px: int = 90 # 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 not 0.0 <= self.body_x_margin_ratio <= 0.5: raise ValueError("body_x_margin_ratio 必须在 [0,0.5]") if self.body_min_posts < 1: raise ValueError("body_min_posts 至少 1") 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.50)), body_min_roi_px=int(raw.get("body_min_roi_px", 90)), body_min_post_len_ratio=float(raw.get("body_min_post_len_ratio", 0.15)), body_x_margin_ratio=float(raw.get("body_x_margin_ratio", 0.03)), body_min_posts=int(raw.get("body_min_posts", 3)), vehicle_min_span_ratio=float(raw.get("vehicle_min_span_ratio", 0.50)), vehicle_max_posts=int(raw.get("vehicle_max_posts", 60)), empty_vehicle_enable=bool(raw.get("empty_vehicle_enable", True)), empty_min_posts=int(raw.get("empty_min_posts", 3)), empty_min_span_ratio=float(raw.get("empty_min_span_ratio", 0.60)), empty_min_opacity=float(raw.get("empty_min_opacity", 0.55)), empty_min_wall_h_ratio=float(raw.get("empty_min_wall_h_ratio", 0.25)), empty_min_post_len_ratio=float(raw.get("empty_min_post_len_ratio", 0.30)), empty_fallback_max_posts=int(raw.get("empty_fallback_max_posts", 4)), empty_min_diagonal_braces=int(raw.get("empty_min_diagonal_braces", 1)), empty_flatbed_enable=bool(raw.get("empty_flatbed_enable", True)), empty_flatbed_min_gap_px=float(raw.get("empty_flatbed_min_gap_px", 16.0)), empty_flatbed_max_plane_edge=float( raw.get("empty_flatbed_max_plane_edge", 0.12)), empty_flatbed_max_gray_drop=float( raw.get("empty_flatbed_max_gray_drop", 35.0)), empty_top_margin_ratio=float(raw.get("empty_top_margin_ratio", 0.0)), allow_state3=bool(raw.get("allow_state3", True)), 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_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)), min_bed_roi_px=int(raw.get("min_bed_roi_px", 90)), 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 = "" # 分类器给出的理由(与 C++ `EvidenceV2Result::class_reason` 同名同义): # `wall_posts` / `deck_edge` / `bed_roi_small` / `vehicle_wall` / # `ambiguous_empty_vehicle` / `no_box` / `weak_evidence` … class_reason: str = "" body_posts: int = 0 body_span: float = 0.0 body_opacity: float = 0.0 body_diagonal: int = 0 # P0-Q9:本帧是否按“空车(敞车、车斗内无箱)”判出 `state=3`; # `empty_reason` 记录未通过的那一道门(`empty_span` / `empty_wall_short` …)。 empty_vehicle: bool = False empty_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, 3): 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, "class_reason": self.class_reason, "body_posts": int(self.body_posts), "body_span": round(float(self.body_span), 3), "body_opacity": round(float(self.body_opacity), 3), "body_diagonal": int(self.body_diagonal), "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, below_roi_h_px: 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`` 表示不可用(不因此拒绝)。 ``below_roi_h_px``:箱底以下动态 ROI 的高度(**原图像素**),用于 ``min_bed_roi_px`` 门 —— 与 C++ ``classify()`` 同口径。 本函数与 ``cpp/src/edge_v2.cpp`` 的 ``EdgeV2::classify()`` **逐条同构**: ``post_array_regular`` / ``relaxed_post_array`` / ``prefer_bed_on_conflict`` / ``bed_roi_ok`` 都在这边实现,否则"Python 调好的参数搬到 C++ 结论会变"。 """ 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 ) # ---- 以下三条与 C++ 同口径(Python Hough 会把同一门板两侧描边算 2 根, # C++ 自定义拟合会合并成 1 根:A 稳定帧 Python 5~8 根 / C++ 4 根)。 # 1) 门板阵列的间距是规则的;≥8 根且 CV>1.5 视为杂波(<8 根样本少,不看 CV)。 post_array_regular = ( posts < 8 or spacing_cv is None or float(spacing_cv) <= 1.5 ) # 2) posts = min_door_posts-1 时若侧墙不透明且间距规则,仍按门板阵列处理。 relaxed_min_posts = max(1, int(self.p.min_door_posts) - 1) relaxed_post_array = ( posts >= relaxed_min_posts and opacity >= 0.65 and (spacing_cv is None or float(spacing_cv) <= 1.0) ) posts_ok = posts >= int(self.p.min_door_posts) or relaxed_post_array # 3) 冲突(1 与 2 同时成立)时:A 的真实门板阵列可能只剩 min_posts-1 根, # 同时又误检到车面边梁 → 按"门板阵列"优先。 prefer_bed_on_conflict = ( posts < int(self.p.min_door_posts) and relaxed_post_array ) bed_evidence = ( posts_ok and posts <= int(self.p.max_door_posts) and opacity >= self.p.min_wall_opacity and post_array_regular 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 ) # 箱底以下动态 ROI 太矮时,立柱只有 20~27 px,与地面/钢轨纹理不可区分 # (B 片段实测 5~16 条伪立柱被投票成"已发布 1",真值 2)。不足门限 → 弃权。 bed_roi_ok = float(below_roi_h_px) >= float(self.p.min_bed_roi_px) bed_strong = bed_evidence and bed_roi_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 and not prefer_bed_on_conflict: return int(SceneState.UNKNOWN), 0.0, 0.0, "conflict_1_2" if bed_evidence and not bed_roi_ok and not flat_strong: return int(SceneState.UNKNOWN), 0.0, 0.0, "bed_roi_small" 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 _detect_empty_vehicle(self, gray: np.ndarray, window: Tuple[int, int, int, int], texture_top: float, scale: float, box_bottom: Optional[float] = None, deck_edge: bool = False, main_posts: int = 0, main_post_span: float = 0.0) -> Optional[Dict[str, object]]: """空车(敞车、车斗内无箱)证据 —— P0-Q9,判据见 ``EvidenceV2Params``。 与旧 `body_fallback`(“空车歧义帧一律 255”)的区别:这里要求侧墙 ROI 在画面里**足够高**(`empty_min_wall_h_ratio`),并要求门板阵列**横跨 整车**(`empty_min_span_ratio`)。因此它只在“能看见一整节空敞车侧墙” 时成立;罐箱把车帮压到画面底部时侧墙只有十几 % 高,过不了。 返回 ``None`` = 没有车体证据;否则返回 dict: * ``ok``:是否满足空车门(严格) * ``basic``:是否满足旧口径的车体结构门(宽松,用于保留“歧义弃权”) * ``reason`` / ``stats`` / ``roi`` / ``confidence`` / ``hits`` """ p = self.p if not p.empty_vehicle_enable: return None wh, ww = gray.shape[:2] if texture_top <= 0.0: return None if texture_top < window[1] + p.empty_top_margin_ratio * wh: return None wy0 = max(int(window[1]), int(round(texture_top))) wy1 = min(int(window[3]), wh - 1) if wy1 <= wy0: return None # 侧墙 ROI 到底多少:用 `body_bottom_ratio`(与旧车体兜底同一口径), # 而“可见墙高”按 到窗口底 的绝对高度算 —— 两者用途不同,不要混。 wall_h_ratio = float(wy1 - wy0) / max(1.0, float(wh)) wy1 = min(wy1, int(round(texture_top + p.body_bottom_ratio * (wy1 - texture_top)))) if wy1 <= wy0: return None bx0 = max(0, int(round(p.body_x_margin_ratio * ww))) bx1 = min(ww - 1, int(round((1.0 - p.body_x_margin_ratio) * ww))) roi = (bx0, wy0, bx1, wy1) b = self._measure_body(gray, roi, scale, post_len_ratio=p.empty_min_post_len_ratio) # 有界兜底:严格门数不到 → 用宽松门再量一次,但只接受“极少数立柱 + 大跨度”。 # 见 `empty_fallback_max_posts` 注释(防 NX70A 平车+蓝箱被聚成 7 根后误判空车)。 if (int(b["posts"]) < p.empty_min_posts and p.body_min_post_len_ratio < p.empty_min_post_len_ratio): b2 = self._measure_body(gray, roi, scale, post_len_ratio=p.body_min_post_len_ratio) if (p.empty_min_posts <= int(b2["posts"]) <= p.empty_fallback_max_posts and float(b2["span"]) >= 0.70 and float(b2["opacity"]) >= p.empty_min_opacity and int(b2["diagonal"]) >= p.empty_min_diagonal_braces): b = b2 stats = { "posts": int(b["posts"]), "span": float(b["span"]), "opacity": float(b["opacity"]), "diagonal": int(b["diagonal"]), "height": float(b["height"]), "wall_h_ratio": wall_h_ratio, } out: Dict[str, object] = {"ok": False, "basic": False, "stats": stats, "roi": roi} if b["height"] < p.body_min_roi_px: out["reason"] = "empty_roi_small" return out # 若“薄车面边梁 + 车面下暗带”(平车特征)出现在这段“侧墙”**之上**, # 说明这段“墙”其实是平车车面以下的地面/堆场 —— 不能当敞车侧墙。 # (平车 + 集装箱的 texture_top 常落在车面下方的地面上。) if deck_edge and box_bottom is not None and float(box_bottom) <= texture_top: out["reason"] = "empty_wall_below_deck" return out # 正常路径已经在箱底下方看到一簇**窄跨度**竖棱(span < min_post_span_ratio) # → 那是平车的车轮/制动梁/端部结构(实测 B 片段 postx=666..858,span≈0.20), # 不是敞车侧墙。此时整段 ROI 里的"立柱"也只是同一簇结构,不能判空车。 if main_posts >= 2 and main_post_span < p.min_post_span_ratio: out["reason"] = "empty_narrow_post_cluster" return out basic = ( p.body_min_posts <= b["posts"] <= p.max_door_posts and b["span"] >= p.min_post_span_ratio and b["opacity"] >= p.body_min_opacity and b["diagonal"] >= p.min_diagonal_braces ) out["basic"] = bool(basic) if wall_h_ratio < p.empty_min_wall_h_ratio: out["reason"] = "empty_wall_short" return out if not (p.empty_min_posts <= b["posts"] <= p.max_door_posts): out["reason"] = "empty_posts" return out if b["span"] < p.empty_min_span_ratio: out["reason"] = "empty_span" return out if b["opacity"] < p.empty_min_opacity: out["reason"] = "empty_opacity" return out if b["diagonal"] < p.empty_min_diagonal_braces: out["reason"] = "empty_braces" return out out["ok"] = True out["reason"] = "empty_vehicle" out["confidence"] = min( 1.0, 0.60 + 0.10 * min(1.0, b["posts"] / 8.0) + 0.20 * b["opacity"] ) out["hits"] = min(1.0, 0.45 + 0.04 * b["posts"] + 0.25 * b["opacity"]) return out @staticmethod def _plane_stats(gray: np.ndarray, roi: Tuple[int, int, int, int], block: int = 16, th: float = 50.0, hit: float = 0.03) -> Optional[Dict[str, float]]: """ROI 的灰度均值 + 竖向/横向边缘块覆盖率(与 ``find_texture_top`` 同口径)。 车底板几乎无纹理(两项覆盖率都低);集装箱侧壁有瓦楞/立柱(覆盖率高)。 """ x0, y0, x1, y1 = [int(v) for v in roi] x0, y0 = max(0, x0), max(0, y0) x1 = min(int(gray.shape[1]), x1) y1 = min(int(gray.shape[0]), y1) if x1 - x0 < 16 or y1 - y0 < 6: return None crop = gray[y0:y1, x0:x1] gx = np.abs(cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3)) gy = np.abs(cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3)) nb = max(1, crop.shape[1] // block) vhit = 0 hhit = 0 for b in range(nb): xs = b * block xe = min(crop.shape[1], xs + block) if xe <= xs: continue if float((gx[:, xs:xe] >= th).mean()) >= hit: vhit += 1 if float((gy[:, xs:xe] >= th).mean()) >= hit: hhit += 1 return { "mean": float(crop.mean()), "vcov": vhit / float(nb), "hcov": hhit / float(nb), } def _detect_empty_flatbed(self, gray: np.ndarray, window: Tuple[int, int, int, int], box, bed, deck_edge: bool, under_deck: bool, gap_px: Optional[float]) -> Optional[Dict[str, object]]: """空平车(平车、车面裸露)证据 —— P0-Q10,判据见 ``EvidenceV2Params``。 与载车的本质差别:**载车必然有箱底暗带紧贴(或很近)车面边梁**,空平车的 “箱底”其实是车底板**远端边缘线**,与近侧边梁之间隔着整片车面(纵深 ≥ ``empty_flatbed_min_gap_px``)。再要求那片车面**光滑 + 亮**,排除集装箱 侧壁(瓦楞/立柱 → 边缘覆盖率高)和地面(暗且纹理多)。 """ p = self.p if not p.empty_flatbed_enable: return None if bed is None or float(bed.height) <= 0.0: return None if not under_deck: return None # 车底透空必须是一个**暗带**(不是“地面本来就比边梁暗”):边梁下方 # `under_deck_search_h_ratio` 内先出现明显更暗的行,再明显变亮(地面)。 search = max(8, int(round(p.under_deck_search_h_ratio * float(gray.shape[0])))) y0 = int(round(bed.y1)) y1 = min(int(gray.shape[0]), y0 + search) if y1 - y0 < 4: return None means = [_row_mean(gray, int(window[0]), int(window[2]), y, y + 1) for y in range(y0, y1)] sill_mean0 = _row_mean(gray, int(window[0]), int(window[2]), int(round(bed.y0)), max(int(round(bed.y1)), int(round(bed.y0)) + 1)) lo = min(means) tail_n = max(1, len(means) // 4) tail = sum(means[-tail_n:]) / float(tail_n) if not (lo <= sill_mean0 - p.under_deck_dark_delta and tail >= lo + p.under_deck_dark_delta): return {"ok": False, "reason": "empty_flatbed_no_void", "stats": {}, "roi": (0, 0, 0, 0)} # 边梁必须是“薄边”(厚亮面是地面/月台/下层箱顶) est_h = max(60.0, (float(box.y0) - 0.05 * float(gray.shape[0])) if box is not None else 0.45 * float(gray.shape[0])) if float(bed.height) > p.contact_max_h_ratio * est_h: return {"ok": False, "reason": "empty_flatbed_thick_sill", "stats": {}, "roi": (0, 0, 0, 0)} # 载车:箱底暗带紧贴/贴近边梁(实测 01/img00/img01 三张载车样本 gap≈0) if box is not None and (gap_px is None or float(gap_px) < p.empty_flatbed_min_gap_px): return None wh, ww = gray.shape[:2] sill = float(bed.y0) depth = float(gap_px) if gap_px is not None else 0.0 plane_h = int(round(min(max(depth, p.empty_flatbed_min_gap_px), 0.25 * wh))) top = max(int(window[1]), int(round(sill)) - plane_h) bot = int(round(sill)) if bot - top < 6: return None roi = (int(window[0]), top, int(window[2]), bot) stats = self._plane_stats(gray, roi) if stats is None: return None sill_mean = _row_mean(gray, int(window[0]), int(window[2]), int(round(bed.y0)), max(int(round(bed.y1)), int(round(bed.y0)) + 1)) out: Dict[str, object] = { "ok": False, "reason": "empty_flatbed_plane", "stats": dict(stats, sill_mean=sill_mean, plane_h=bot - top, depth=depth), "roi": roi, } if stats["vcov"] > p.empty_flatbed_max_plane_edge: out["reason"] = "empty_flatbed_texture" return out if stats["hcov"] > p.empty_flatbed_max_plane_edge * 1.5: out["reason"] = "empty_flatbed_texture" return out if stats["mean"] < sill_mean - p.empty_flatbed_max_gray_drop: out["reason"] = "empty_flatbed_dark" return out edge_ratio = min(1.0, stats["vcov"] / max(1e-6, p.empty_flatbed_max_plane_edge)) out["ok"] = True out["reason"] = "empty_flatbed" out["confidence"] = min(1.0, 0.65 + 0.20 * (1.0 - edge_ratio)) out["hits"] = min(1.0, 0.62 + 0.25 * (1.0 - edge_ratio)) return out def _measure_body(self, gray: np.ndarray, roi: Tuple[int, int, int, int], scale: float, post_len_ratio: Optional[float] = None) -> Dict[str, float]: """车体 ROI 的结构证据(与 C++ ``measure_body`` 同口径)。 返回 ``posts`` / ``span``(立柱跨度 ÷ ROI 宽)/ ``opacity``(不透明占比)/ ``diagonal``(斜撑数)/ ``height``(原图像素高度)。 ``post_len_ratio`` 覆盖“竖棱最短长度占 ROI 高的比例”: * 默认用 ``body_min_post_len_ratio``(0.15):箱体瓦楞被锈迹/铆钉打断 成短段时也要数得出来(平车兜底/罐箱判 1 用); * 空车判据传 ``empty_min_post_len_ratio``(0.30):要求门板立柱**贯穿 侧墙**,地面/噪声里的碎短竖棱不算立柱(否则平车车面下方的地面会被 当成“完整敞车侧墙”)。 """ structure = detect_structure_v2( gray, roi, # C++ `measure_body` 用的是 `body_min_post_len_ratio`(0.15), # 不是主判据的 `min_post_len_ratio`(0.30):后者会把集装箱 # 波纹这种"被锈迹/铆钉打断的短竖棱"全部滤掉(1920 宽图上数到 0 根)。 min_post_len_ratio=( float(post_len_ratio) if post_len_ratio is not None else self.p.body_min_post_len_ratio ), cluster_gap_px=9.0, scale=scale, ) positions = structure.get("post_positions") or [] span = 0.0 if len(positions) >= 2: span = (max(positions) - min(positions)) / max(1.0, float(roi[2] - roi[0])) ground, blocks = ground_like_ratio( gray, roi, 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, ) opacity = 1.0 - ground if blocks > 0 else 0.0 # P0-Q11:立柱间距变异系数(门板阵列等距;接触网杆/箱棱/杂物不等距)。 spcv = 0.0 if len(positions) >= 3: gaps = [positions[i + 1] - positions[i] for i in range(len(positions) - 1)] mean_gap = sum(gaps) / float(len(gaps)) if mean_gap > 1e-6: var = sum((g - mean_gap) ** 2 for g in gaps) / float(len(gaps)) spcv = float(np.sqrt(var) / mean_gap) return { "posts": int(structure["post_count"]), "span": float(span), "opacity": float(opacity), "diagonal": int(structure["diagonal_lines"]), "spcv": float(spcv), "height": float(roi[3] - roi[1]) / max(scale, 1e-6), } # ------------------------------------------------------------ 主入口 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: # P0-Q6:没有“箱底暗带”不等于判不了车型。现场目标是判「平车 / 敞车」, # 罐箱(`04_container_on_gondola.png`)的箱底常被车帮挡住,但车体结构 # (门板立柱 + 斜撑 + 不透明侧墙)仍可见。这里退化为“只看车体”: # 判得出 → 敞车 1(gap 记 0:箱在车斗内,不存在间隙); # 判不出 → 仍按 `no_box` 弃权,**绝不**因此猜成平车。 # # P0-Q9:先看是不是**空车**——若 texture_top 以下是一整节空敞车侧墙 # (墙高 ≥25%、门板 3~16 根横跨整车、斜撑在),输出 3 而不是 1。 # 罐箱载车只剩画面底部一条薄车帮(实测墙高 ~13%),过不了这道门, # 仍然走下面的 vehicle_wall → 1。 empty = self._detect_empty_vehicle(gray, window, texture_top, scale) wall_state, wall_reason = 1, "vehicle_wall" if empty is not None and empty["ok"]: wall_state, wall_reason = 3, "empty_vehicle" if self.p.body_fallback_enable: # ROI 用整个搜索窗口:罐箱会把 texture_top 定到车帮上沿, # 按 texture_top 取 ROI 只剩几十像素,数不到立柱。 vy0 = max(0, int(window[1])) vy1 = min(wh - 1, int(window[3])) if vy1 > vy0: vx0 = max(0, int(round(self.p.body_x_margin_ratio * ww))) vx1 = min(ww - 1, int(round( (1.0 - self.p.body_x_margin_ratio) * ww))) body = self._measure_body(gray, (vx0, vy0, vx1, vy1), scale) if (body["height"] >= self.p.body_min_roi_px and self.p.body_min_posts <= body["posts"] <= self.p.vehicle_max_posts and body["span"] >= self.p.vehicle_min_span_ratio and body["opacity"] >= self.p.body_min_opacity and body["diagonal"] >= self.p.min_diagonal_braces): if wall_state == 3: # 空车:证据换成 texture_top 以下那一片侧墙(与 3 的门同一份 ROI) body = dict(empty["stats"]) # type: ignore[arg-type] conf = float(empty["confidence"]) hits = float(empty["hits"]) else: conf = min(1.0, 0.55 + 0.25 * min(1.0, body["posts"] / 8.0) + 0.15 * body["opacity"]) hits = min(1.0, 0.40 + 0.05 * body["posts"] + 0.20 * body["opacity"]) commit = self.tracker.update( ts, state=wall_state, gap_m=0.0, gap_px=0.0, 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=bool(hoist_high), ) self._last = EvidenceV2Result( state=wall_state, confidence=conf, view=self.p.view, class_reason=wall_reason, empty_vehicle=(wall_state == 3), empty_reason=("empty_vehicle" if wall_state == 3 else ""), texture_top_y=(float(texture_top) / max(scale, 1e-6) if texture_top > 0.0 else None), body_posts=int(body["posts"]), body_span=float(body["span"]), body_opacity=float(body["opacity"]), body_diagonal=int(body["diagonal"]), door_posts=int(body["posts"]), diagonal_braces=int(body["diagonal"]), wall_opacity=float(body["opacity"]), ground_ratio=float(1.0 - body["opacity"]), gap_px=0.0, gap_m=0.0, phase=(commit.phase if motion_ok else CommitPhase.T3), committed=commit.committed, commit_reason=commit.reason, stable_frames=commit.stable_frames, structure_frames=commit.structure_frames, motion_ok=motion_ok, hoist_high=bool(hoist_high), diagnostics={"vehicle_only": True, "reason": "vehicle_wall"}, ) return self._last self._last = EvidenceV2Result( view=self.p.view, motion_ok=motion_ok, abstain_reason="no_box", class_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)) # 与 C++ `flat_contact` 同口径:侧视平车的箱底与车面直接贴合时,车面边梁 # 落在动态 ROI 之外(Hough 水平线通道看不到它:实拍图 deck=False、gap 被 # 错取成 62.9 px → weak_evidence)。这里补一条"贴合薄亮边"证据: # 箱底下沿紧邻(±1 px)的亮带,高度 >= 1.5% 画幅(至少 4 px),且不超过 # `contact_max_h_ratio`×估箱高(排除地面 / 下层箱顶 / 月台等厚亮面)。 # 命中后把这条亮边当作车面(bed),gap 归 0。 min_contact_h = max(4.0, 0.015 * wh) contact_band: Optional[Band] = None for band in bright: if not (box.y1 - 1.0 <= band.y0 < box.y1 + 1.0): continue height = band.y1 - band.y0 if height >= min_contact_h and ( contact_band is None or height > (contact_band.y1 - contact_band.y0) ): contact_band = band if (contact_band is not None and (contact_band.y1 - contact_band.y0) > self.p.contact_max_h_ratio * est_h): contact_band = None flat_contact = ( not thick_contact and contact_band is not None and posts <= int(self.p.flat_max_door_posts) and opacity >= self.p.min_wall_opacity and ground < self.p.min_zero_ground_ratio ) if flat_contact: bed = contact_band 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 = bool(flat_contact) or 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), below_roi_h_px=float(below_h_work) / max(scale, 1e-6), ) body = None body_stats = None body_roi = None empty_flag = False empty_reason = "" flat_stats: Optional[Dict[str, float]] = None # P0-Q9:空车识别(state=3)。判据只看 texture_top 以下那一片**敞车侧墙**: # 完整的一节空敞车侧墙 → 3;只是“看得见车体结构但不够完整” → 保持旧的 # 弃权口径(255 ambiguous_empty_vehicle),绝不判 1/2。 # 载车为什么过不了:平车+集装箱的侧墙 ROI 实为箱体瓦楞(>max_door_posts); # 罐箱载车只剩底部一条薄车帮(墙高 0.0 and state != 1: empty = self._detect_empty_vehicle( gray, window, texture_top, scale, box_bottom=float(box.y1) if box is not None else None, deck_edge=bool(deck_edge), main_posts=int(posts), main_post_span=float(post_span_ratio), ) if empty is not None: estats = dict(empty["stats"]) # type: ignore[arg-type] empty_reason = str(empty.get("reason") or "") if empty["ok"]: state = 3 conf = float(empty["confidence"]) hits = float(empty["hits"]) reason = "empty_vehicle" gap_px = 0.0 body = estats body_stats = estats body_roi = tuple(empty["roi"]) # type: ignore[arg-type] empty_flag = True elif (empty["basic"] and state == 2 and posts <= 1 and box.y1 > texture_top + 0.02 * wh): # 车体结构可见、但不足以判空车、且箱底以下几乎没有立柱 → # 保持旧口径(P0-Q4):空车歧义帧弃权,绝不判 2。 state = 255 conf = 0.0 hits = 0.0 reason = "ambiguous_empty_vehicle" body_stats = estats # P0-Q10:空平车(平车、车面裸露)→ 也输出 3。 # 与空敞车**互斥**:上面已先判敞车侧墙;这里是“薄车面边梁 + 车底透空 + # 边梁上方是一片光滑亮车面 + 没有箱底紧贴边梁”。载车(01/img00/img01) # 的箱底暗带 gap≈0 → 直接排除。 if not empty_flag and state != 1: flat = self._detect_empty_flatbed( gray, window, box if box is not None and float(box.height) > 0.0 else None, bed if bed is not None and float(bed.height) > 0.0 else None, bool(deck_edge), bool(under_deck), gap_px, ) if flat is not None: if flat.get("ok"): state = 3 conf = float(flat["confidence"]) hits = float(flat["hits"]) reason = "empty_flatbed" gap_px = 0.0 empty_flag = True empty_reason = "empty_flatbed" flat_stats = dict(flat["stats"]) # type: ignore[arg-type] elif not empty_reason: empty_reason = str(flat.get("reason") or "") 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 <= 1 and box.y1 > texture_top + 0.02 * wh and (body_stats is None or (body_stats["posts"] <= self.p.max_door_posts and float(body_stats.get("span", 0.0)) >= self.p.min_post_span_ratio))): state = 255 conf = 0.0 hits = 0.0 reason = "ambiguous_empty_vehicle" # P0-Q11:作业帧(吊具高悬 / 吊具仍夹箱)**绝不判车型**。 # 根因:吊具/箱体悬在车体上方时,空车判据会把“吊具横梁 + 箱体侧壁”当成 # 敞车侧墙(实测 root_test1:posts=9 span=0.95 → 误判 3)。hoist_flag 已算好, # 这里在空车/空平车覆写之后、commit 之前拦一道。 if hoist_flag and state in (1, 2, 3): state = int(SceneState.UNKNOWN) conf = 0.0 hits = 0.0 reason = "hoist_high" 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, 3) else ("" if state in (0, 1, 2, 3) else reason) ), class_reason=reason, empty_vehicle=bool(empty_flag), empty_reason=empty_reason, body_posts=int(body_stats["posts"]) if body_stats else 0, body_span=float(body_stats.get("span", 0.0)) if body_stats else 0.0, body_opacity=float(body_stats["opacity"]) if body_stats else 0.0, body_diagonal=int(body_stats["diagonal"]) if body_stats else 0, 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), "empty_vehicle": bool(empty_flag), "empty_reason": empty_reason, "empty_flatbed": flat_stats, "body_wall_h_ratio": ( None if not body_stats else body_stats.get("wall_h_ratio") ), "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 )