evidence_v2.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. """P1b:前视 v2 结构证据(箱底以下的门板 / 边梁 / 地面)。
  2. 设计依据
  3. --------
  4. ``docs/route_v2.md`` §2–§4 与 P0 实测(``docs/evidence/p0_v2``):
  5. * **1(敞车)**:箱底以下是一整面不透明侧墙,门板立柱 ``8–14`` 根、
  6. 立柱间距有规律,斜撑/矩形门可作加分;
  7. * **2(平车)**:箱底以下只有薄车面边梁,下方透空,能看到地面/植被;
  8. 门板立柱 ``0–4`` 根;
  9. * **0(其他)**:只有连续地面,既无门板阵列也无可信车面边梁。
  10. 与 v1 的区别
  11. -------------
  12. v1 用固定高位带(箱底以上 0.55–0.85 箱高)找围挡,方向是错的;本模块
  13. **只在箱底以下**取证,ROI 的 y 起点跟随每帧箱底下沿,不再使用
  14. ``y=475..619`` 的固定带。单帧输出只是“候选”,是否允许提交给 PLC 由
  15. :mod:`portcv.logic.commit` 的 T2 门决定。
  16. 工程约束
  17. --------
  18. * 运行期依赖 ``numpy`` + ``opencv-python``(取流层本来就需要 OpenCV);
  19. * 所有几何量用**原图像素**输出,内部按 ``work_width`` 缩放;
  20. * 单帧确定性:不使用随机数,Hough 参数固定;
  21. * 看不清一律内部 255,绝不硬判 2。
  22. """
  23. from __future__ import annotations
  24. import math
  25. import statistics
  26. from dataclasses import dataclass, field
  27. from typing import Dict, List, Optional, Sequence, Tuple
  28. import numpy as np
  29. try: # pragma: no cover - 无 OpenCV 时给出明确错误,而不是静默降级
  30. import cv2
  31. except ImportError: # pragma: no cover
  32. cv2 = None # type: ignore
  33. from ..config import Config
  34. from ..schema import Box, CommitPhase, Observation, SceneState, ViewMode
  35. from .commit import CommitState, CommitTracker
  36. __all__ = [
  37. "Band",
  38. "EvidenceV2",
  39. "EvidenceV2Params",
  40. "EvidenceV2Result",
  41. "detect_hoist_high",
  42. "detect_spreader_contact",
  43. "detect_structure_v2",
  44. "ground_like_ratio",
  45. "horizontal_bands",
  46. "pick_box_and_bed",
  47. ]
  48. Point = Tuple[float, float]
  49. @dataclass(frozen=True)
  50. class Band:
  51. """水平亮带/暗带(原图像素坐标)。"""
  52. y0: float
  53. y1: float
  54. strength: float
  55. @property
  56. def height(self) -> float:
  57. return max(0.0, self.y1 - self.y0)
  58. @dataclass(frozen=True)
  59. class EvidenceV2Params:
  60. """``evidence_v2.*`` 配置(与 ``configs/edge-v2-front.json`` 同名同义)。"""
  61. enabled: bool = False
  62. view: ViewMode = ViewMode.FRONT
  63. work_width: int = 960
  64. window: Tuple[float, float, float, float] = (0.24, 0.02, 0.78, 0.95)
  65. band_min_h: int = 3
  66. band_max_h_ratio: float = 0.15
  67. bed_search_ratio: float = 0.40
  68. box_bottom_max_ratio: float = 0.78
  69. below_start_ratio: float = 0.07
  70. below_height_ratio: float = 0.55
  71. below_min_height_px: int = 24
  72. min_door_posts: int = 5
  73. max_door_posts: int = 16
  74. max_bed_gap_px: float = 40.0
  75. flat_max_door_posts: int = 4
  76. max_post_spacing_cv: float = 6.0
  77. min_post_len_ratio: float = 0.30
  78. min_wall_opacity: float = 0.35
  79. max_flat_gap_px: float = 40.0
  80. wall_edge_density_ref: float = 0.14
  81. wall_edge_density_span: float = 0.04
  82. ground_block_px: int = 32
  83. ground_density_lo: float = 0.02
  84. ground_density_hi: float = 0.35
  85. min_flat_ground_ratio: float = 0.40
  86. min_zero_ground_ratio: float = 0.65
  87. deck_min_len_ratio: float = 0.30
  88. box_height_m: float = 2.591
  89. px_per_m: float = 0.0
  90. min_scale_px: float = 60.0
  91. motion_diff_max: float = 12.0
  92. motion_grad_ratio_min: float = 0.72
  93. require_commit: bool = True
  94. allow_state2: bool = True
  95. structure_hits_min: float = 0.60
  96. # P0-0:吊具/钢缆/臂架高悬安全门(默认开)。只在箱体上方区域找
  97. # “长横线 + 上方暗带 + 下方更亮”的组合;宁可弃权,不可把悬空箱
  98. # 当成已落位。
  99. reject_hoist_high: bool = True
  100. hoist_dark_max: int = 75
  101. hoist_band_frac: float = 0.035
  102. hoist_line_ratio: float = 0.20
  103. hoist_dark_ratio: float = 0.55
  104. hoist_bright_delta: float = 12.0
  105. def __post_init__(self) -> None:
  106. if self.work_width < 160:
  107. raise ValueError("work_width 至少 160")
  108. if self.band_min_h < 1:
  109. raise ValueError("band_min_h 至少 1")
  110. if not 0.0 < self.band_max_h_ratio <= 1.0:
  111. raise ValueError("band_max_h_ratio 必须在 (0,1]")
  112. if self.bed_search_ratio <= 0.0:
  113. raise ValueError("bed_search_ratio 必须为正")
  114. if self.below_height_ratio <= 0.0:
  115. raise ValueError("below_height_ratio 必须为正")
  116. if self.min_door_posts < 1:
  117. raise ValueError("min_door_posts 至少 1")
  118. if self.box_height_m <= 0.0:
  119. raise ValueError("box_height_m 必须为正")
  120. @classmethod
  121. def from_config(cls, cfg: Config) -> "EvidenceV2Params":
  122. raw = cfg.section("evidence_v2")
  123. window = raw.get("window") or [0.24, 0.02, 0.78, 0.95]
  124. if len(window) != 4:
  125. raise ValueError("evidence_v2.window 需要 4 个数字")
  126. return cls(
  127. enabled=bool(raw.get("enabled", False)),
  128. view=ViewMode.parse(raw.get("view", "front")),
  129. work_width=int(raw.get("work_width", 960)),
  130. window=tuple(float(v) for v in window), # type: ignore[arg-type]
  131. band_min_h=int(raw.get("band_min_h", 3)),
  132. band_max_h_ratio=float(raw.get("band_max_h_ratio", 0.15)),
  133. bed_search_ratio=float(raw.get("bed_search_ratio", 0.40)),
  134. box_bottom_max_ratio=float(raw.get("box_bottom_max_ratio", 0.78)),
  135. below_start_ratio=float(raw.get("below_start_ratio", 0.07)),
  136. below_height_ratio=float(raw.get("below_height_ratio", 0.55)),
  137. below_min_height_px=int(raw.get("below_min_height_px", 24)),
  138. min_door_posts=int(raw.get("min_door_posts", 5)),
  139. max_door_posts=int(raw.get("max_door_posts", 16)),
  140. max_bed_gap_px=float(raw.get("max_bed_gap_px", 40.0)),
  141. flat_max_door_posts=int(raw.get("flat_max_door_posts", 4)),
  142. max_post_spacing_cv=float(raw.get("max_post_spacing_cv", 6.0)),
  143. min_post_len_ratio=float(raw.get("min_post_len_ratio", 0.30)),
  144. min_wall_opacity=float(raw.get("min_wall_opacity", 0.35)),
  145. max_flat_gap_px=float(raw.get("max_flat_gap_px", 40.0)),
  146. wall_edge_density_ref=float(raw.get("wall_edge_density_ref", 0.14)),
  147. wall_edge_density_span=float(raw.get("wall_edge_density_span", 0.04)),
  148. ground_block_px=int(raw.get("ground_block_px", 32)),
  149. ground_density_lo=float(raw.get("ground_density_lo", 0.02)),
  150. ground_density_hi=float(raw.get("ground_density_hi", 0.35)),
  151. min_flat_ground_ratio=float(raw.get("min_flat_ground_ratio", 0.40)),
  152. min_zero_ground_ratio=float(raw.get("min_zero_ground_ratio", 0.65)),
  153. deck_min_len_ratio=float(raw.get("deck_min_len_ratio", 0.30)),
  154. box_height_m=float(raw.get("box_height_m", 2.591)),
  155. px_per_m=float(raw.get("px_per_m", 0.0)),
  156. min_scale_px=float(raw.get("min_scale_px", 60.0)),
  157. motion_diff_max=float(raw.get("motion_diff_max", 12.0)),
  158. motion_grad_ratio_min=float(raw.get("motion_grad_ratio_min", 0.72)),
  159. require_commit=bool(raw.get("require_commit", True)),
  160. allow_state2=bool(raw.get("allow_state2", True)),
  161. structure_hits_min=float(raw.get("structure_hits_min", 0.60)),
  162. reject_hoist_high=bool(raw.get("reject_hoist_high", True)),
  163. hoist_dark_max=int(raw.get("hoist_dark_max", 75)),
  164. hoist_band_frac=float(raw.get("hoist_band_frac", 0.035)),
  165. hoist_line_ratio=float(raw.get("hoist_line_ratio", 0.20)),
  166. hoist_dark_ratio=float(raw.get("hoist_dark_ratio", 0.55)),
  167. hoist_bright_delta=float(raw.get("hoist_bright_delta", 12.0)),
  168. )
  169. @dataclass
  170. class EvidenceV2Result:
  171. """单帧 v2 证据与分类结果(所有坐标均为原图像素)。"""
  172. state: int = int(SceneState.UNKNOWN)
  173. confidence: float = 0.0
  174. view: ViewMode = ViewMode.UNKNOWN
  175. box_bottom_y: Optional[float] = None
  176. box_top_y: Optional[float] = None
  177. box_h_px: Optional[float] = None
  178. px_per_m: Optional[float] = None
  179. scale_ok: bool = False
  180. bed_top_y: Optional[float] = None
  181. gap_px: Optional[float] = None
  182. gap_m: Optional[float] = None
  183. door_posts: int = 0
  184. post_spacing_px: Optional[float] = None
  185. post_spacing_cv: Optional[float] = None
  186. rect_doors: int = 0
  187. diagonal_braces: int = 0
  188. wall_opacity: float = 0.0
  189. deck_edge: bool = False
  190. wheel_count: int = 0
  191. ground_ratio: float = 0.0
  192. phase: CommitPhase = CommitPhase.T1
  193. committed: bool = False
  194. commit_reason: str = "init"
  195. stable_frames: int = 0
  196. structure_frames: int = 0
  197. motion_ok: bool = True
  198. hoist_high: bool = False
  199. abstain_reason: str = ""
  200. below_roi: Tuple[int, int, int, int] = (0, 0, 0, 0)
  201. diagnostics: Dict[str, object] = field(default_factory=dict)
  202. @property
  203. def candidate_state(self) -> int:
  204. """分类候选(未经 commit 门);诊断/回放用。"""
  205. return int(self.state)
  206. def publishable(self, require_commit: bool = True) -> bool:
  207. if int(self.state) not in (0, 1, 2):
  208. return False
  209. if not require_commit:
  210. return True
  211. return bool(self.committed)
  212. def to_observation(
  213. self,
  214. ts: float = 0.0,
  215. frame_id: int = 0,
  216. detections: Optional[Sequence[object]] = None,
  217. *,
  218. require_commit: bool = True,
  219. ) -> Observation:
  220. """转成现有 ``TemporalVoter`` 可消费的 ``Observation``。
  221. commit 不成立时输出内部 255(不是 0),并保留分类候选在 reason 里。
  222. """
  223. ok = self.publishable(require_commit)
  224. state = int(self.state) if ok else int(SceneState.UNKNOWN)
  225. conf = float(self.confidence) if ok else 0.0
  226. reason = "v2:%s view=%s posts=%d opacity=%.2f gap=%s commit=%s hoist=%d" % (
  227. "ok" if ok else "abstain",
  228. self.view.value,
  229. int(self.door_posts),
  230. float(self.wall_opacity),
  231. "n/a" if self.gap_px is None else "%.0fpx" % self.gap_px,
  232. self.commit_reason,
  233. int(bool(self.hoist_high)),
  234. )
  235. if not ok and self.abstain_reason:
  236. reason += " reason=%s" % self.abstain_reason
  237. return Observation(
  238. ts=float(ts),
  239. state=state,
  240. confidence=conf,
  241. detections=list(detections or []),
  242. reason=reason,
  243. frame_id=int(frame_id),
  244. )
  245. def to_dict(self) -> Dict[str, object]:
  246. return {
  247. "state": int(self.state),
  248. "confidence": round(float(self.confidence), 4),
  249. "view": self.view.value,
  250. "box_bottom_y": _round_opt(self.box_bottom_y),
  251. "box_top_y": _round_opt(self.box_top_y),
  252. "box_h_px": _round_opt(self.box_h_px),
  253. "px_per_m": _round_opt(self.px_per_m),
  254. "scale_ok": bool(self.scale_ok),
  255. "bed_top_y": _round_opt(self.bed_top_y),
  256. "gap_px": _round_opt(self.gap_px),
  257. "gap_m": _round_opt(self.gap_m, 4),
  258. "door_posts": int(self.door_posts),
  259. "post_spacing_px": _round_opt(self.post_spacing_px),
  260. "post_spacing_cv": _round_opt(self.post_spacing_cv, 3),
  261. "rect_doors": int(self.rect_doors),
  262. "diagonal_braces": int(self.diagonal_braces),
  263. "wall_opacity": round(float(self.wall_opacity), 3),
  264. "deck_edge": bool(self.deck_edge),
  265. "wheel_count": int(self.wheel_count),
  266. "ground_ratio": round(float(self.ground_ratio), 3),
  267. "phase": self.phase.value,
  268. "committed": bool(self.committed),
  269. "commit_reason": self.commit_reason,
  270. "stable_frames": int(self.stable_frames),
  271. "structure_frames": int(self.structure_frames),
  272. "motion_ok": bool(self.motion_ok),
  273. "hoist_high": bool(self.hoist_high),
  274. "abstain_reason": self.abstain_reason,
  275. "below_roi": [int(v) for v in self.below_roi],
  276. "diagnostics": dict(self.diagnostics),
  277. }
  278. def _round_opt(value: Optional[float], digits: int = 2) -> Optional[float]:
  279. if value is None:
  280. return None
  281. return round(float(value), digits)
  282. def _to_gray(image: np.ndarray) -> np.ndarray:
  283. if image is None:
  284. return np.zeros((0, 0), dtype=np.uint8)
  285. if image.ndim == 2:
  286. return image.astype(np.uint8, copy=False)
  287. if cv2 is None: # pragma: no cover
  288. raise RuntimeError("需要 opencv-python 进行彩色转换")
  289. if image.shape[2] == 4:
  290. return cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
  291. return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  292. def horizontal_bands(
  293. gray: np.ndarray,
  294. roi: Tuple[int, int, int, int],
  295. min_h: int = 3,
  296. max_h: int = 90,
  297. topn: int = 12,
  298. ) -> Tuple[List[Band], List[Band]]:
  299. """行均值纵向 Sobel 找水平亮带/暗带(P0 算法的生产化版本)。
  300. 返回 ``(bright, dark)``;``y0/y1`` 是原图坐标。亮带 = 中间比上下亮,
  301. 暗带 = 中间比上下暗。算法只用行均值,因此在箱体移动/局部纹理下比
  302. 全画面霍夫更稳定。
  303. """
  304. if cv2 is None: # pragma: no cover
  305. raise RuntimeError("evidence_v2 需要 opencv-python")
  306. x0, y0, x1, y1 = [int(v) for v in roi]
  307. x0 = max(0, x0)
  308. y0 = max(0, y0)
  309. x1 = min(int(gray.shape[1]), x1)
  310. y1 = min(int(gray.shape[0]), y1)
  311. if x1 <= x0 or y1 <= y0:
  312. return [], []
  313. crop = gray[y0:y1, x0:x1].astype(np.float32)
  314. if crop.size == 0:
  315. return [], []
  316. crop = cv2.GaussianBlur(crop, (3, 3), 0)
  317. gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  318. mag = np.abs(gy)
  319. if mag.size == 0:
  320. return [], []
  321. if mag.size < 3:
  322. return [], []
  323. limit = float(mag.mean() + 0.9 * mag.std())
  324. # 峰值抑制:同一道边缘常在相邻 1~2 行出现两个极值(例如箱底 3 px
  325. # 暗带:y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内
  326. # 严格最大:167 会压掉 168,168 又压掉 170,最终只剩一个负峰,
  327. # 暗带无法配对,整帧直接 no_box。这里先取 ±1 行局部极大,再按幅值
  328. # 贪心抑制 3 px 内的重复峰,既保留 3 px 薄带,又不拆散同一道边缘。
  329. min_sep = max(2, int(round(min_h)))
  330. candidates = [
  331. i for i in range(1, len(mag) - 1)
  332. if mag[i] >= limit and mag[i] >= mag[i - 1] and mag[i] >= mag[i + 1]
  333. ]
  334. picked: List[int] = []
  335. for i in sorted(candidates, key=lambda j: mag[j], reverse=True):
  336. if all(abs(i - j) >= min_sep for j in picked):
  337. picked.append(i)
  338. picked.sort()
  339. events: List[Tuple[int, float]] = [(i, float(gy[i])) for i in picked]
  340. bright: List[Band] = []
  341. dark: List[Band] = []
  342. for j in range(len(events) - 1):
  343. i1, v1 = events[j]
  344. i2, v2 = events[j + 1]
  345. height = i2 - i1
  346. if height < min_h or height > max_h:
  347. continue
  348. strength = min(abs(v1), abs(v2))
  349. if strength <= 0.0:
  350. continue
  351. if v1 > 0.0 > v2:
  352. bright.append(Band(float(y0 + i1), float(y0 + i2), strength))
  353. elif v1 < 0.0 < v2:
  354. dark.append(Band(float(y0 + i1), float(y0 + i2), strength))
  355. bright.sort(key=lambda b: b.strength, reverse=True)
  356. dark.sort(key=lambda b: b.strength, reverse=True)
  357. return bright[:topn], dark[:topn]
  358. def pick_box_and_bed(
  359. bright: Sequence[Band],
  360. dark: Sequence[Band],
  361. frame_h: int,
  362. *,
  363. box_bottom_max_ratio: float = 0.78,
  364. bed_search_px: float = 120.0,
  365. ) -> Tuple[Optional[Band], Optional[Band]]:
  366. """选箱底暗带与它下方最近的车体上缘亮带(与 P0 同口径)。"""
  367. upper = [
  368. b for b in dark
  369. if b.y1 <= box_bottom_max_ratio * frame_h and b.y0 >= 0.02 * frame_h
  370. ]
  371. if not upper:
  372. return None, None
  373. strongest = max(b.strength for b in upper)
  374. strong = [b for b in upper if b.strength >= 0.45 * strongest]
  375. box = min(strong, key=lambda b: b.y0)
  376. below = [b for b in bright if b.y0 >= box.y1 - 1.0 and b.y0 <= box.y1 + bed_search_px]
  377. bed = min(below, key=lambda b: b.y0) if below else None
  378. return box, bed
  379. def ground_like_ratio(
  380. gray: np.ndarray,
  381. roi: Tuple[int, int, int, int],
  382. segments: Sequence[Dict[str, float]],
  383. *,
  384. block_px: int = 32,
  385. density_lo: float = 0.02,
  386. density_hi: float = 0.35,
  387. ) -> Tuple[float, int]:
  388. """分块“地面样”比例:纹理密度在区间内且块内无长直线。
  389. 与 v1 ``edge_evidence.cpp::region_stats`` 的 ``ground_like`` 同口径;
  390. 门板立柱是**竖线**、门板横梁/车面边梁是**横线**,两者都算结构面。
  391. """
  392. if cv2 is None: # pragma: no cover
  393. return 0.0, 0
  394. x0, y0, x1, y1 = [int(v) for v in roi]
  395. crop = gray[y0:y1, x0:x1]
  396. if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
  397. return 0.0, 0
  398. gx = cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3)
  399. gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3)
  400. mag = np.sqrt(gx * gx + gy * gy)
  401. ref = float(np.percentile(mag, 60.0))
  402. hot = mag > ref
  403. b = max(6, int(block_px))
  404. total = 0
  405. ground = 0
  406. for by in range(0, crop.shape[0], b):
  407. for bx in range(0, crop.shape[1], b):
  408. ex = min(crop.shape[1], bx + b)
  409. ey = min(crop.shape[0], by + b)
  410. block = hot[by:ey, bx:ex]
  411. if block.size == 0:
  412. continue
  413. density = float(block.mean())
  414. long_line = any(
  415. float(seg["length"]) >= 0.6 * b
  416. and bx + x0 <= (float(seg["x0"]) + float(seg["x1"])) * 0.5 <= ex + x0
  417. and by + y0 <= (float(seg["y0"]) + float(seg["y1"])) * 0.5 <= ey + y0
  418. for seg in segments
  419. if "x0" in seg and "x1" in seg and "y0" in seg and "y1" in seg
  420. )
  421. total += 1
  422. if not long_line and density_lo <= density <= density_hi:
  423. ground += 1
  424. return (float(ground) / float(total) if total else 0.0), total
  425. def _cluster_positions(values: Sequence[float], gap_px: float) -> List[float]:
  426. ordered = sorted(float(v) for v in values)
  427. if not ordered:
  428. return []
  429. clusters: List[List[float]] = [[ordered[0]]]
  430. for value in ordered[1:]:
  431. if value - clusters[-1][-1] <= gap_px:
  432. clusters[-1].append(value)
  433. else:
  434. clusters.append([value])
  435. return [float(statistics.median(c)) for c in clusters]
  436. def detect_structure_v2(
  437. gray: np.ndarray,
  438. roi: Tuple[int, int, int, int],
  439. *,
  440. min_post_len_ratio: float = 0.30,
  441. cluster_gap_px: float = 9.0,
  442. scale: float = 1.0,
  443. ) -> Dict[str, object]:
  444. """箱底以下 ROI 的门板立柱 / 斜撑 / 矩形门 / 水平边梁。
  445. 只做**证据计数**,不做分类;返回的坐标相对 ROI(线段另带
  446. ``y`` 原图坐标,供 deck_edge 使用)。
  447. """
  448. if cv2 is None: # pragma: no cover
  449. raise RuntimeError("evidence_v2 需要 opencv-python")
  450. x0, y0, x1, y1 = [int(v) for v in roi]
  451. crop = gray[y0:y1, x0:x1]
  452. empty = {
  453. "vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0,
  454. "rect_doors": 0, "post_count": 0, "post_spacing_median": None,
  455. "post_spacing_cv": None, "edge_density": 0.0,
  456. "horizontal": [], "lines": [],
  457. }
  458. if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
  459. return empty
  460. crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop)
  461. edges = cv2.Canny(crop, 50, 150)
  462. roi_h = max(1, crop.shape[0])
  463. roi_area = float(crop.shape[0] * crop.shape[1])
  464. lines = cv2.HoughLinesP(
  465. edges, 1, math.pi / 180.0, threshold=24,
  466. minLineLength=max(12, int(round(20 * scale))), maxLineGap=max(4, int(round(8 * scale))),
  467. )
  468. vertical: List[Tuple[float, float, float]] = []
  469. horizontal: List[Dict[str, float]] = []
  470. all_lines: List[Dict[str, float]] = []
  471. diagonal = 0
  472. if lines is not None:
  473. flat = np.asarray(lines).reshape(-1, 4)
  474. for raw in flat:
  475. xa, ya, xb, yb = (float(v) for v in raw)
  476. dx, dy = xb - xa, yb - ya
  477. length = math.hypot(dx, dy)
  478. if length < max(12.0, 20.0 * scale):
  479. continue
  480. all_lines.append({
  481. "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
  482. "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
  483. "length": length,
  484. })
  485. if abs(dy) >= 1.8 * abs(dx):
  486. vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb)))
  487. elif abs(dx) >= 1.8 * abs(dy):
  488. horizontal.append({
  489. "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
  490. "y": y0 + (ya + yb) * 0.5, "length": length,
  491. "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
  492. })
  493. else:
  494. diagonal += 1
  495. posts = [v for v in vertical if (v[2] - v[1]) >= min_post_len_ratio * roi_h]
  496. post_x = _cluster_positions([v[0] for v in posts], max(3.0, cluster_gap_px * scale))
  497. spacings = [post_x[i + 1] - post_x[i] for i in range(len(post_x) - 1)]
  498. spacing_median = float(statistics.median(spacings)) if spacings else None
  499. spacing_cv = None
  500. if len(spacings) >= 2 and spacing_median:
  501. spacing_cv = float(statistics.pstdev(spacings) / spacing_median)
  502. contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  503. rect_doors = 0
  504. for contour in contours:
  505. area = cv2.contourArea(contour)
  506. if area < 180.0 or area > 0.20 * roi_area:
  507. continue
  508. peri = cv2.arcLength(contour, True)
  509. if peri <= 0.0:
  510. continue
  511. approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
  512. if not (4 <= len(approx) <= 6):
  513. continue
  514. _, _, bw, bh = cv2.boundingRect(approx)
  515. if bh <= 0:
  516. continue
  517. aspect = bw / float(bh)
  518. if 0.30 <= aspect <= 3.2:
  519. rect_doors += 1
  520. return {
  521. "vertical_lines": len(posts),
  522. "diagonal_lines": int(diagonal),
  523. "horizontal_lines": len(horizontal),
  524. "rect_doors": int(rect_doors),
  525. "post_count": len(post_x),
  526. "post_spacing_median": spacing_median,
  527. "post_spacing_cv": spacing_cv,
  528. "edge_density": float(edges.mean() / 255.0),
  529. "horizontal": horizontal,
  530. "lines": all_lines,
  531. }
  532. def detect_spreader_contact(
  533. gray: np.ndarray,
  534. container_bbox: Tuple[float, float, float, float],
  535. *,
  536. dark_max: int = 110,
  537. dark_ratio: float = 0.55,
  538. ) -> Tuple[bool, Dict[str, object]]:
  539. """检测集装箱上沿紧邻的吊具横梁(吊具仍夹着箱)。
  540. 负样本里最典型的误判是:算法把**箱侧壁瓦楞**当成车斗门板,箱底
  541. 又恰好贴到画面上某个横向结构,于是 5 帧后 commit。真正落位时,
  542. 箱顶上方不应存在一条“紧贴箱顶、横跨箱宽、明显更暗”的横梁;吊具
  543. 未松开时这条横梁必然存在。
  544. 只使用检测器给出的 container 框(不是 ``box_top`` 自标尺),因此
  545. 不受箱高估计误差影响。返回值第二项为诊断。
  546. """
  547. empty = {"spreader_contact": False, "dark_run_px": 0, "band_delta": 0.0}
  548. if gray is None or gray.size == 0:
  549. return False, empty
  550. h, w = gray.shape[:2]
  551. x1, y1, x2, y2 = [int(round(v)) for v in container_bbox]
  552. x1, x2 = max(0, min(x1, x2)), min(w, max(x1, x2))
  553. y1, y2 = max(0, min(y1, y2)), min(h, max(y1, y2))
  554. box_h = y2 - y1
  555. box_w = x2 - x1
  556. if box_h < 20 or box_w < 20:
  557. return False, empty
  558. probe = max(4, int(0.30 * box_h))
  559. y0 = max(0, y1 - probe)
  560. roi = gray[y0:y1, x1:x2]
  561. if roi.shape[0] < 3:
  562. return False, empty
  563. dark = roi < int(dark_max)
  564. frac = dark.mean(axis=1)
  565. min_run = max(3, int(0.02 * box_h))
  566. runs = []
  567. run_start = None
  568. for row, value in enumerate(frac):
  569. if value >= dark_ratio:
  570. if run_start is None:
  571. run_start = row
  572. elif run_start is not None:
  573. if (row - run_start) >= min_run:
  574. runs.append((run_start, row - 1))
  575. run_start = None
  576. if run_start is not None and (len(frac) - run_start) >= min_run:
  577. runs.append((run_start, len(frac) - 1))
  578. if not runs:
  579. return False, empty
  580. # 优先选离箱顶最近的一条暗横梁:吊具夹着箱时它紧贴箱顶;更长的
  581. # 远处吊臂不能替代它,否则会把“远处横梁”误当成“已落位”。
  582. best_start, best_end = min(runs, key=lambda item: (len(frac) - 1 - item[1], item[0] - item[1]))
  583. if (len(frac) - 1 - best_end) > max(2, int(0.08 * box_h)):
  584. return False, empty
  585. band = roi[best_start:best_end + 1, :]
  586. below = gray[y1:min(h, y1 + max(6, int(0.06 * box_h))), x1:x2]
  587. if band.size == 0 or below.size == 0:
  588. return False, empty
  589. band_mean = float(band.mean())
  590. below_mean = float(below.mean())
  591. if below_mean < band_mean + 10.0:
  592. return False, empty
  593. return True, {
  594. "spreader_contact": True,
  595. "dark_run_px": int(best_end - best_start + 1),
  596. "band_delta": round(below_mean - band_mean, 2),
  597. }
  598. def detect_hoist_high(
  599. gray: np.ndarray,
  600. box_top_y: float,
  601. *,
  602. dark_max: int = 75,
  603. band_frac: float = 0.035,
  604. line_ratio: float = 0.30,
  605. dark_ratio: float = 0.55,
  606. bright_delta: float = 12.0,
  607. ) -> Tuple[bool, Dict[str, object]]:
  608. """检测箱体上方的吊具/臂架/钢缆高悬特征。
  609. 只看**候选箱体上沿以上**的区域,要求同时满足:
  610. * 至少一条横跨画面中央的长横线(Hough);
  611. * 横线上方是一条暗带(吊具/臂架本体);
  612. * 暗带下方明显更亮(天空、箱顶或车体),说明暗带是遮挡物而不是
  613. 箱体本身的暗边。
  614. 这三个条件是为了避开集装箱侧壁的竖向瓦楞和车体横梁:A/B 正样本的
  615. 箱顶通常已被画幅裁掉(``box_top_y`` 很小),不会进入该区域;负样本
  616. (屏幕录制)上方有明显黑色吊臂/吊具,会被拦下。返回值第二项只用于
  617. 诊断,不参与安全判定。
  618. """
  619. empty = {"hoist_high": False, "horizontal_lines": 0, "cables": 0}
  620. if cv2 is None or gray is None or gray.size == 0:
  621. return False, empty
  622. h, w = gray.shape[:2]
  623. limit = int(min(max(8.0, float(box_top_y) - 2.0), 0.45 * h))
  624. if limit < max(12, int(0.06 * h)) or w < 32:
  625. return False, empty
  626. scale = min(1.0, 480.0 / float(w))
  627. if scale < 1.0:
  628. work = cv2.resize(
  629. gray, (int(round(w * scale)), int(round(h * scale))),
  630. interpolation=cv2.INTER_AREA,
  631. )
  632. else:
  633. work = gray
  634. hh, ww = work.shape[:2]
  635. limit_w = min(hh, max(1, int(round(limit * scale))))
  636. roi = work[:limit_w, :]
  637. if roi.shape[0] < 12 or roi.shape[1] < 32:
  638. return False, empty
  639. blur = cv2.GaussianBlur(roi, (5, 5), 0)
  640. edges = cv2.Canny(blur, 50, 150)
  641. lines = cv2.HoughLinesP(
  642. edges,
  643. 1,
  644. math.pi / 180.0,
  645. threshold=15,
  646. minLineLength=max(10, int(line_ratio * ww)),
  647. maxLineGap=max(4, int(0.03 * ww)),
  648. )
  649. horizontal_hits = 0
  650. cables = 0
  651. x0 = int(0.10 * ww)
  652. x1 = max(x0 + 8, int(0.90 * ww))
  653. band_h = max(3, int(band_frac * hh))
  654. if lines is not None:
  655. for raw in np.asarray(lines).reshape(-1, 4):
  656. xa, ya, xb, yb = (float(v) for v in raw)
  657. dx, dy = abs(xb - xa), abs(yb - ya)
  658. if dx < line_ratio * ww * 0.8:
  659. continue
  660. # 近水平线:吊具横梁/臂架下缘
  661. if dy <= max(3.0, 0.04 * dx):
  662. y = int(round((ya + yb) * 0.5))
  663. if y - band_h < 0 or y + 2 >= limit_w:
  664. continue
  665. band = blur[y - band_h:y, x0:x1]
  666. below = blur[y + 2:min(limit_w, y + 2 + 2 * band_h), x0:x1]
  667. if band.size == 0 or below.size == 0:
  668. continue
  669. dark = float(np.mean(band < int(dark_max)))
  670. if dark >= dark_ratio and float(below.mean()) >= float(band.mean()) + bright_delta:
  671. horizontal_hits += 1
  672. # 近竖直线:钢缆/油管(只作诊断与辅助确认)
  673. elif dy >= max(6.0, 4.0 * dx) and dy >= 0.12 * hh:
  674. xs = np.linspace(xa, xb, num=12)
  675. ys = np.linspace(ya, yb, num=12)
  676. samples = [
  677. blur[int(round(yv)), int(round(xv))]
  678. for xv, yv in zip(xs, ys)
  679. if 0 <= int(round(yv)) < limit_w and 0 <= int(round(xv)) < ww
  680. ]
  681. if samples and float(np.mean(samples)) <= float(dark_max) + 25.0:
  682. cables += 1
  683. hoist = horizontal_hits >= 1
  684. return hoist, {
  685. "hoist_high": bool(hoist),
  686. "horizontal_lines": int(horizontal_hits),
  687. "cables": int(cables),
  688. }
  689. class EvidenceV2:
  690. """前视 v2 证据提取 + 分类 + commit 门(线程内使用)。"""
  691. def __init__(self, params: Optional[EvidenceV2Params] = None,
  692. tracker: Optional[CommitTracker] = None) -> None:
  693. self.p = params or EvidenceV2Params()
  694. self.tracker = tracker or CommitTracker()
  695. self._last = EvidenceV2Result(view=self.p.view)
  696. self._prev_thumb: Optional[np.ndarray] = None
  697. self._prev_mag = 0.0
  698. @classmethod
  699. def from_config(cls, cfg: Config) -> "EvidenceV2":
  700. return cls(EvidenceV2Params.from_config(cfg), CommitTracker.from_config(cfg))
  701. @property
  702. def last(self) -> EvidenceV2Result:
  703. return self._last
  704. def reset(self) -> None:
  705. self.tracker.reset()
  706. self._prev_thumb = None
  707. self._prev_mag = 0.0
  708. self._last = EvidenceV2Result(view=self.p.view)
  709. # ------------------------------------------------------------ 运动门控
  710. def _motion(self, gray: np.ndarray) -> Tuple[bool, float, float]:
  711. if cv2 is None: # pragma: no cover
  712. return True, 0.0, 1.0
  713. thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA)
  714. lap = cv2.Laplacian(thumb, cv2.CV_32F)
  715. mag = float(np.abs(lap).mean())
  716. if self._prev_thumb is None:
  717. self._prev_thumb = thumb
  718. self._prev_mag = mag
  719. return True, 0.0, 1.0
  720. diff = float(np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean())
  721. ratio = (mag / self._prev_mag) if self._prev_mag > 1e-6 else 1.0
  722. ok = diff <= self.p.motion_diff_max and ratio >= self.p.motion_grad_ratio_min
  723. self._prev_thumb = thumb
  724. self._prev_mag = 0.8 * self._prev_mag + 0.2 * mag if self._prev_mag > 0 else mag
  725. return ok, diff, ratio
  726. # ------------------------------------------------------------ 自标尺
  727. def _scale_from_vertical(
  728. self,
  729. gray: np.ndarray,
  730. box: Band,
  731. window: Tuple[int, int, int, int],
  732. scale: float,
  733. ) -> Tuple[Optional[float], Optional[float]]:
  734. """用箱体近端竖棱估 ``px_per_m``;失败返回 ``(None, None)``。"""
  735. if cv2 is None: # pragma: no cover
  736. return None, None
  737. if self.p.px_per_m > 0.0:
  738. px_per_m = float(self.p.px_per_m)
  739. return px_per_m, None
  740. x0, y0, x1, _ = [int(v) for v in window]
  741. y1 = max(1, int(box.y0))
  742. crop = gray[max(0, y0):y1, max(0, x0):min(gray.shape[1], x1)]
  743. if crop.size == 0:
  744. return None, None
  745. edges = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop), 50, 150)
  746. lines = cv2.HoughLinesP(
  747. edges, 1, math.pi / 180.0, threshold=24,
  748. minLineLength=max(12, int(self.p.min_scale_px * scale)),
  749. maxLineGap=max(4, int(10 * scale)),
  750. )
  751. best = 0.0
  752. if lines is not None:
  753. for raw in np.asarray(lines).reshape(-1, 4):
  754. xa, ya, xb, yb = (float(v) for v in raw)
  755. dx, dy = abs(xb - xa), abs(yb - ya)
  756. if dy >= 2.0 * dx and dy > best:
  757. best = dy
  758. if best < self.p.min_scale_px * scale:
  759. return None, None
  760. px_per_m_work = best / self.p.box_height_m
  761. return px_per_m_work / max(scale, 1e-6), best
  762. # ------------------------------------------------------------ 分类
  763. def _classify(
  764. self,
  765. *,
  766. posts: int,
  767. spacing_cv: Optional[float],
  768. opacity: float,
  769. ground: float,
  770. deck: bool,
  771. wheels: int,
  772. gap_px: Optional[float],
  773. motion_ok: bool,
  774. view: ViewMode,
  775. ) -> Tuple[int, float, float, str]:
  776. """返回 ``(state, confidence, structure_hits, reason)``。"""
  777. if view == ViewMode.UNKNOWN:
  778. return int(SceneState.UNKNOWN), 0.0, 0.0, "view_unknown"
  779. if not motion_ok:
  780. return int(SceneState.UNKNOWN), 0.0, 0.0, "motion"
  781. bed_strong = (
  782. self.p.min_door_posts <= posts <= self.p.max_door_posts
  783. and opacity >= self.p.min_wall_opacity
  784. and (gap_px is None or gap_px <= self.p.max_bed_gap_px)
  785. and (spacing_cv is None or spacing_cv <= self.p.max_post_spacing_cv)
  786. )
  787. # 平车:没有门板阵列 + 箱底下有可见车面边梁。地面比例只作置信度加分:
  788. # B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。
  789. flat_strong = (
  790. posts <= self.p.flat_max_door_posts
  791. and deck
  792. and (gap_px is None or gap_px <= self.p.max_flat_gap_px)
  793. )
  794. if bed_strong and flat_strong:
  795. return int(SceneState.UNKNOWN), 0.0, 0.0, "conflict_1_2"
  796. if bed_strong:
  797. conf = 0.55 + 0.25 * min(1.0, posts / 8.0) + 0.15 * opacity
  798. hits = min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity)
  799. return int(SceneState.BED), min(1.0, conf), hits, "wall_posts"
  800. if flat_strong:
  801. conf = 0.60 + 0.20 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0)
  802. hits = min(1.0, 0.55 + 0.15 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0))
  803. return int(SceneState.FLATBED), min(1.0, conf), hits, "deck_edge"
  804. if posts <= 1 and ground >= self.p.min_zero_ground_ratio and not deck:
  805. conf = 0.55 + 0.30 * ground
  806. hits = min(1.0, 0.50 + 0.40 * ground)
  807. return int(SceneState.NOT_ON_TRAIN), min(1.0, conf), hits, "ground_only"
  808. return int(SceneState.UNKNOWN), 0.0, 0.0, "weak_evidence"
  809. # ------------------------------------------------------------ 车轮(辅助)
  810. @staticmethod
  811. def _wheel_count(gray: np.ndarray, roi: Tuple[int, int, int, int], scale: float) -> int:
  812. if cv2 is None: # pragma: no cover
  813. return 0
  814. x0, y0, x1, y1 = roi
  815. crop = gray[y0:y1, x0:x1]
  816. if crop.size == 0 or min(crop.shape[:2]) < 40:
  817. return 0
  818. crop = cv2.medianBlur(crop, 5)
  819. try:
  820. circles = cv2.HoughCircles(
  821. crop, cv2.HOUGH_GRADIENT, dp=1.2,
  822. minDist=max(20, int(36 * scale)),
  823. param1=100, param2=26,
  824. minRadius=max(7, int(12 * scale)), maxRadius=max(20, int(60 * scale)),
  825. )
  826. except cv2.error: # pragma: no cover - 某些精简版 OpenCV
  827. return 0
  828. if circles is None:
  829. return 0
  830. return int(len(np.asarray(circles).reshape(-1, 3)))
  831. # ------------------------------------------------------------ 主入口
  832. def analyze(
  833. self,
  834. image: np.ndarray,
  835. ts: float = 0.0,
  836. frame_id: int = 0,
  837. *,
  838. plc_arrived: bool = False,
  839. plc_spreader_released: bool = False,
  840. detections: Optional[Sequence[Box]] = None,
  841. hoist_high: Optional[bool] = None,
  842. ) -> EvidenceV2Result:
  843. """提取一帧证据并更新 commit 状态。
  844. ``image`` 可以是灰度或 BGR;坐标一律按**原图**返回。
  845. ``detections`` 是检测器本帧输出(可选);有 container 框时,用
  846. 箱顶正上方的暗横梁判断吊具是否仍夹着箱。``hoist_high`` 仅用于
  847. 离线回放/单测注入;生产路径由图像 + 检测框自动判定。
  848. """
  849. gray0 = _to_gray(image)
  850. if gray0.size == 0:
  851. self._last = EvidenceV2Result(
  852. view=self.p.view, abstain_reason="no_image",
  853. commit_reason="no_image", phase=CommitPhase.T1,
  854. )
  855. return self._last
  856. h, w = gray0.shape[:2]
  857. scale = min(1.0, float(self.p.work_width) / float(w))
  858. if scale < 1.0:
  859. gray = cv2.resize(gray0, (int(round(w * scale)), int(round(h * scale))),
  860. interpolation=cv2.INTER_AREA)
  861. else:
  862. gray = gray0
  863. motion_ok, motion_diff, motion_ratio = self._motion(gray)
  864. wh, ww = gray.shape[:2]
  865. window = (
  866. int(self.p.window[0] * ww), int(self.p.window[1] * wh),
  867. int(self.p.window[2] * ww), int(self.p.window[3] * wh),
  868. )
  869. max_h = max(6, int(self.p.band_max_h_ratio * wh))
  870. bright, dark = horizontal_bands(
  871. gray, window, min_h=max(1, int(self.p.band_min_h * scale)), max_h=max_h
  872. )
  873. # 先估一个箱高,用于“车体上缘搜索窗”(P0 固定 120 px 的等价物)。
  874. box_hint = max(80.0, 0.40 * wh)
  875. box, bed = pick_box_and_bed(
  876. bright, dark, wh,
  877. box_bottom_max_ratio=self.p.box_bottom_max_ratio,
  878. bed_search_px=max(24.0, self.p.bed_search_ratio * box_hint),
  879. )
  880. if box is None and dark:
  881. # 兜底:取上半幅最强的暗带(仍要求离顶部有一点距离)。
  882. candidates = [b for b in dark if b.y0 >= 0.03 * wh and b.y1 <= 0.90 * wh]
  883. box = max(candidates, key=lambda b: b.strength) if candidates else None
  884. if box is None:
  885. self._last = EvidenceV2Result(
  886. view=self.p.view, motion_ok=motion_ok, abstain_reason="no_box",
  887. commit_reason="no_box", phase=CommitPhase.T3 if not motion_ok else CommitPhase.T1,
  888. diagnostics={"motion_diff": round(motion_diff, 2),
  889. "motion_ratio": round(motion_ratio, 3)},
  890. )
  891. return self._last
  892. if bed is None and bright:
  893. below = [b for b in bright if b.y0 >= box.y1 - 1.0]
  894. bed = min(below, key=lambda b: b.y0) if below else None
  895. px_per_m, vertical_run = self._scale_from_vertical(gray, box, window, scale)
  896. box_h_px = None
  897. if px_per_m is not None:
  898. box_h_px = px_per_m * self.p.box_height_m
  899. elif vertical_run is not None:
  900. box_h_px = vertical_run / max(scale, 1e-6)
  901. box_top = None
  902. if box_h_px is not None:
  903. box_top = max(0.0, box.y1 / max(scale, 1e-6) - box_h_px)
  904. # P0-0 安全门:看箱体上沿以上有没有吊具/臂架/钢缆。没有可靠箱高时
  905. # 用“箱底暗带往上 0.35 画幅”保守估计,宁可多弃权。
  906. hoist_flag = False
  907. hoist_cues: Dict[str, object] = {
  908. "hoist_high": False, "horizontal_lines": 0, "cables": 0,
  909. }
  910. if hoist_high is not None:
  911. hoist_flag = bool(hoist_high)
  912. hoist_cues = {
  913. "hoist_high": bool(hoist_flag),
  914. "horizontal_lines": 0,
  915. "cables": 0,
  916. "injected": True,
  917. }
  918. elif self.p.reject_hoist_high:
  919. # 首选:检测器 container 框 + 箱顶正上方的暗横梁。它比
  920. # “用箱高猜箱顶”稳,因为负样本里箱高估计会被前景集装箱
  921. # 侧壁带偏(i=668 估到 136 px,真实箱顶在 ~208 px)。
  922. container = None
  923. for det in detections or []:
  924. name = str(getattr(det, "class_name", "") or "").lower()
  925. if "container" not in name:
  926. continue
  927. if container is None or getattr(det, "area", 0.0) > getattr(container, "area", 0.0):
  928. container = det
  929. if container is not None:
  930. contact_flag, contact_cues = detect_spreader_contact(
  931. gray0,
  932. (container.x1, container.y1, container.x2, container.y2),
  933. )
  934. line_flag, line_cues = detect_hoist_high(
  935. gray0,
  936. float(container.y1),
  937. dark_max=self.p.hoist_dark_max,
  938. band_frac=self.p.hoist_band_frac,
  939. line_ratio=self.p.hoist_line_ratio,
  940. dark_ratio=self.p.hoist_dark_ratio,
  941. bright_delta=self.p.hoist_bright_delta,
  942. )
  943. hoist_flag = bool(contact_flag or line_flag)
  944. hoist_cues = dict(contact_cues)
  945. hoist_cues.update({
  946. "source": "detector_box",
  947. "spreader_contact": bool(contact_flag),
  948. "horizontal_lines": int(line_cues.get("horizontal_lines", 0)),
  949. "cables": int(line_cues.get("cables", 0)),
  950. })
  951. else:
  952. probe_top = (
  953. float(box_top)
  954. if box_top is not None
  955. else max(0.0, box.y0 / max(scale, 1e-6) - 0.35 * h)
  956. )
  957. hoist_flag, hoist_cues = detect_hoist_high(
  958. gray0,
  959. probe_top,
  960. dark_max=self.p.hoist_dark_max,
  961. band_frac=self.p.hoist_band_frac,
  962. line_ratio=self.p.hoist_line_ratio,
  963. dark_ratio=self.p.hoist_dark_ratio,
  964. bright_delta=self.p.hoist_bright_delta,
  965. )
  966. hoist_cues = dict(hoist_cues)
  967. hoist_cues["source"] = "image_rows"
  968. # 动态 ROI:y 从本帧箱底下沿开始,绝不复用 P0 固定 y=475..619。
  969. est_h = max(60.0, box.y0 - 0.05 * wh)
  970. # 起点要越过箱体下侧梁/车体上缘的强横线:从箱底下方约 7% 箱高开始。
  971. # 但若箱底已经贴近画面底边,剩余高度不足以再跳过 7%,就只留 2 px
  972. # 保护带。否则整段动态 ROI 会落到画面外,平车的车面边梁/地板线
  973. # 完全看不到(本帧 25 px 车面 → deck=False、gap=None → 不能提交 2)。
  974. start = max(2.0, self.p.below_start_ratio * est_h)
  975. min_below_h = self.p.below_min_height_px * max(scale, 1e-6)
  976. if (wh - 1) - box.y1 <= start + min_below_h:
  977. start = 2.0
  978. y0w = min(
  979. wh - 2,
  980. int(math.ceil(box.y1 + start)),
  981. )
  982. below_h = max(
  983. min_below_h,
  984. min(self.p.below_height_ratio * est_h, 0.30 * wh),
  985. )
  986. y1w = min(wh - 1, max(y0w + below_h, box.y1 + 0.10 * est_h))
  987. x0w = max(0, int(0.05 * ww))
  988. x1w = min(ww - 1, int(0.95 * ww))
  989. below_work = (x0w, y0w, x1w, max(y0w + 8, int(y1w)))
  990. structure = detect_structure_v2(
  991. gray, below_work,
  992. min_post_len_ratio=self.p.min_post_len_ratio,
  993. cluster_gap_px=9.0, scale=scale,
  994. )
  995. posts = int(structure["post_count"])
  996. spacing_median = structure["post_spacing_median"]
  997. spacing_cv = structure["post_spacing_cv"]
  998. edge_density = float(structure["edge_density"])
  999. ground, ground_blocks = ground_like_ratio(
  1000. gray, below_work, structure.get("lines", []), # type: ignore[arg-type]
  1001. block_px=self.p.ground_block_px,
  1002. density_lo=self.p.ground_density_lo,
  1003. density_hi=self.p.ground_density_hi,
  1004. )
  1005. if ground_blocks > 0:
  1006. opacity = max(0.0, min(1.0, 1.0 - ground))
  1007. else:
  1008. span = max(1e-6, float(self.p.wall_edge_density_span))
  1009. opacity = max(0.0, min(1.0, (self.p.wall_edge_density_ref - edge_density) / span))
  1010. ground = max(0.0, min(1.0, 1.0 - opacity))
  1011. below_h_work = max(1.0, below_work[3] - below_work[1])
  1012. deck_min_len = max(20.0, self.p.deck_min_len_ratio * 0.55 * ww)
  1013. deck_edge = any(
  1014. box.y1 - 2.0 <= float(seg["y"]) <= box.y1 + 0.35 * below_h_work
  1015. and float(seg["length"]) >= deck_min_len
  1016. for seg in structure.get("horizontal", []) # type: ignore[union-attr]
  1017. )
  1018. wheels = self._wheel_count(gray, below_work, scale)
  1019. gap_px = None
  1020. if bed is not None:
  1021. gap_px = max(0.0, (bed.y0 - box.y1) / max(scale, 1e-6))
  1022. state, conf, hits, reason = self._classify(
  1023. posts=posts,
  1024. spacing_cv=spacing_cv,
  1025. opacity=opacity,
  1026. ground=ground,
  1027. deck=deck_edge,
  1028. wheels=wheels,
  1029. gap_px=gap_px,
  1030. motion_ok=motion_ok,
  1031. view=self.p.view,
  1032. )
  1033. gap_m = (
  1034. None if gap_px is None or px_per_m is None or px_per_m <= 0.0
  1035. else gap_px / px_per_m
  1036. )
  1037. commit = self.tracker.update(
  1038. ts,
  1039. state=state,
  1040. gap_m=gap_m,
  1041. gap_px=gap_px,
  1042. structure_hits=hits,
  1043. motion_ok=motion_ok,
  1044. view_known=self.p.view != ViewMode.UNKNOWN,
  1045. plc_arrived=plc_arrived,
  1046. plc_spreader_released=plc_spreader_released,
  1047. hoist_high=hoist_flag,
  1048. )
  1049. phase = CommitPhase.T3 if not motion_ok else CommitPhase(commit.phase)
  1050. result = EvidenceV2Result(
  1051. state=int(state),
  1052. confidence=float(conf),
  1053. view=self.p.view,
  1054. box_bottom_y=box.y1 / max(scale, 1e-6),
  1055. box_top_y=box_top,
  1056. box_h_px=box_h_px,
  1057. px_per_m=px_per_m,
  1058. scale_ok=px_per_m is not None,
  1059. bed_top_y=None if bed is None else bed.y0 / max(scale, 1e-6),
  1060. gap_px=gap_px,
  1061. gap_m=gap_m,
  1062. door_posts=posts,
  1063. post_spacing_px=(
  1064. None if spacing_median is None else float(spacing_median) / max(scale, 1e-6)
  1065. ),
  1066. post_spacing_cv=None if spacing_cv is None else float(spacing_cv),
  1067. rect_doors=int(structure["rect_doors"]),
  1068. diagonal_braces=int(structure["diagonal_lines"]),
  1069. wall_opacity=opacity,
  1070. deck_edge=bool(deck_edge),
  1071. wheel_count=int(wheels),
  1072. ground_ratio=ground,
  1073. phase=phase,
  1074. committed=bool(commit.committed),
  1075. commit_reason=commit.reason,
  1076. stable_frames=int(commit.stable_frames),
  1077. structure_frames=int(commit.structure_frames),
  1078. motion_ok=bool(motion_ok),
  1079. hoist_high=bool(hoist_flag),
  1080. abstain_reason=(
  1081. "hoist_high" if hoist_flag and state in (0, 1, 2)
  1082. else ("" if state in (0, 1, 2) else reason)
  1083. ),
  1084. below_roi=(
  1085. int(round(below_work[0] / scale)), int(round(below_work[1] / scale)),
  1086. int(round(below_work[2] / scale)), int(round(below_work[3] / scale)),
  1087. ),
  1088. diagnostics={
  1089. "class_reason": reason,
  1090. "box_band": [round(box.y0 / scale, 2), round(box.y1 / scale, 2)],
  1091. "bed_band": None if bed is None else [round(bed.y0 / scale, 2), round(bed.y1 / scale, 2)],
  1092. "vertical_run_px": None if vertical_run is None else round(vertical_run / scale, 2),
  1093. "motion_diff": round(motion_diff, 2),
  1094. "motion_ratio": round(motion_ratio, 3),
  1095. "edge_density": round(edge_density, 4),
  1096. "ground_blocks": int(ground_blocks),
  1097. "vertical_lines": int(structure["vertical_lines"]),
  1098. "horizontal_lines": int(structure["horizontal_lines"]),
  1099. "hoist_cues": dict(hoist_cues),
  1100. "scale": round(scale, 4),
  1101. },
  1102. )
  1103. self._last = result
  1104. return result
  1105. def classify(self, image: np.ndarray, ts: float = 0.0, frame_id: int = 0,
  1106. **kwargs) -> Observation:
  1107. """``analyze`` + ``to_observation`` 的便捷入口(pipeline 使用)。"""
  1108. result = self.analyze(image, ts=ts, frame_id=frame_id, **kwargs)
  1109. return result.to_observation(
  1110. ts=ts, frame_id=frame_id, require_commit=self.p.require_commit
  1111. )