evidence_v2.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. """P1b:前视 v2 结构证据(箱底以下的门板 / 边梁 / 地面)。
  2. 设计依据
  3. --------
  4. ``docs/route_v2.md`` §2–§4 与 P0 实测(``docs/evidence/p0_v2``):
  5. * **1(敞车)**:箱底以下是一整面不透明侧墙,门板立柱 ``8–14`` 根、
  6. 立柱间距有规律,斜撑/矩形门可作加分;**贴合形态**(箱底与墙顶/箱顶贴住)
  7. 必须有"八"字斜撑,防"上层箱坐在下层箱上"被判 1;
  8. * **2(平车)**:箱底以下只有薄车面边梁,下方透空,能看到地面/植被;
  9. 门板立柱 ``0–4`` 根;**边梁必须是薄边,且下方有车底空隙/阴影暗带**,
  10. 否则地面/堆料/下层箱顶会被误判 2;
  11. * **0(其他)**:只有连续地面,既无门板阵列也无可信车面边梁。
  12. 与 v1 的区别
  13. -------------
  14. v1 用固定高位带(箱底以上 0.55–0.85 箱高)找围挡,方向是错的;本模块
  15. **只在箱底以下**取证,ROI 的 y 起点跟随每帧箱底下沿,不再使用
  16. ``y=475..619`` 的固定带。单帧输出只是“候选”,是否允许提交给 PLC 由
  17. :mod:`portcv.logic.commit` 的 T2 门决定。
  18. 工程约束
  19. --------
  20. * 运行期依赖 ``numpy`` + ``opencv-python``(取流层本来就需要 OpenCV);
  21. * 所有几何量用**原图像素**输出,内部按 ``work_width`` 缩放;
  22. * 单帧确定性:不使用随机数,Hough 参数固定;
  23. * 看不清一律内部 255,绝不硬判 2。
  24. """
  25. from __future__ import annotations
  26. import math
  27. import statistics
  28. from dataclasses import dataclass, field
  29. from typing import Dict, List, Optional, Sequence, Tuple
  30. import numpy as np
  31. try: # pragma: no cover - 无 OpenCV 时给出明确错误,而不是静默降级
  32. import cv2
  33. except ImportError: # pragma: no cover
  34. cv2 = None # type: ignore
  35. from ..config import Config
  36. from ..schema import Box, CommitPhase, Observation, SceneState, ViewMode
  37. from .commit import CommitState, CommitTracker
  38. __all__ = [
  39. "Band",
  40. "EvidenceV2",
  41. "EvidenceV2Params",
  42. "EvidenceV2Result",
  43. "detect_hoist_high",
  44. "detect_spreader_contact",
  45. "detect_structure_v2",
  46. "find_texture_top",
  47. "ground_like_ratio",
  48. "horizontal_bands",
  49. "pick_box_and_bed",
  50. ]
  51. Point = Tuple[float, float]
  52. @dataclass(frozen=True)
  53. class Band:
  54. """水平亮带/暗带(原图像素坐标)。"""
  55. y0: float
  56. y1: float
  57. strength: float
  58. @property
  59. def height(self) -> float:
  60. return max(0.0, self.y1 - self.y0)
  61. @dataclass(frozen=True)
  62. class EvidenceV2Params:
  63. """``evidence_v2.*`` 配置(与 ``configs/edge-v2-front.json`` 同名同义)。"""
  64. enabled: bool = False
  65. view: ViewMode = ViewMode.FRONT
  66. work_width: int = 960
  67. window: Tuple[float, float, float, float] = (0.24, 0.02, 0.78, 0.95)
  68. band_min_h: int = 3
  69. band_max_h_ratio: float = 0.15
  70. bed_search_ratio: float = 0.40
  71. box_bottom_max_ratio: float = 0.78
  72. below_start_ratio: float = 0.07
  73. below_height_ratio: float = 0.55
  74. below_min_height_px: int = 24
  75. min_door_posts: int = 5
  76. max_door_posts: int = 16
  77. max_bed_gap_px: float = 40.0
  78. flat_max_door_posts: int = 4
  79. max_post_spacing_cv: float = 6.0
  80. min_post_len_ratio: float = 0.30
  81. # P0-Q3:门板立柱间距下限(**原图像素**)。容器侧壁瓦楞周期通常 10~20 px,
  82. # C70 门板立柱 63~185 px(docs/edge_evidence.md §4.1)→ 低于该值不构成门板阵列。
  83. # 没有这条时,"上层箱坐在下层箱上"会把下层箱的瓦楞当成车斗门板 → 误判 1。
  84. min_post_spacing_px: float = 24.0
  85. # P0-Q3:门板阵列的 x 跨度下限(占工作宽度)。真实 C70 横跨车体(A 25%~66%),
  86. # 平车车轮/制动梁只在窄区给伪立柱(B ~20%)→ 取 0.23(B 挡、A f1100 保留)。
  87. min_post_span_ratio: float = 0.23
  88. # P0-Q4:天空/电线 ROI 约束(与 C++ 同名同义)。
  89. texture_top_enable: bool = True
  90. texture_grad_th: float = 50.0
  91. texture_block_px: int = 16
  92. texture_block_hit_ratio: float = 0.03
  93. texture_coverage_min: float = 0.50
  94. texture_run_rows: int = 3
  95. texture_smooth_rows: int = 7
  96. texture_top_margin_ratio: float = 0.02
  97. # P0-Q4:空车/无箱兜底(纹理车体 ROI 再数一次门板立柱)
  98. body_fallback_enable: bool = True
  99. body_bottom_ratio: float = 0.75
  100. body_min_opacity: float = 0.50
  101. body_min_roi_px: int = 90
  102. body_x_margin_ratio: float = 0.03
  103. body_min_posts: int = 3
  104. # P0-Q6:箱底暗带缺失时(罐箱箱底被车帮挡住)“只看车体”的判据。
  105. # 立柱跨度下限:敞车横跨整车(实测 0.66~0.92),平车上集装箱波纹只占中间
  106. # 一段(0.36~0.45)→ 用跨度而不是立柱个数区分;上限放宽是因为 C++ 线段
  107. # 通道会把门框/铰链算成多根(C70E 实测 20 根)。
  108. vehicle_min_span_ratio: float = 0.50
  109. vehicle_max_posts: int = 60
  110. # P0-Q3:`1`(敞车)还必须有"八"字斜撑/三角撑证据(docs/edge_evidence.md §4.1)。
  111. # 容器侧壁只有瓦楞、没有斜撑 → 防"上层箱坐在下层箱上"被判成敞车。
  112. # 0 = 关闭该门(只用于对照实验,现场不要关)。
  113. min_diagonal_braces: int = 1
  114. min_wall_opacity: float = 0.35
  115. max_flat_gap_px: float = 40.0
  116. wall_edge_density_ref: float = 0.14
  117. wall_edge_density_span: float = 0.04
  118. ground_block_px: int = 32
  119. ground_density_lo: float = 0.02
  120. ground_density_hi: float = 0.35
  121. min_zero_ground_ratio: float = 0.65
  122. deck_min_len_ratio: float = 0.30
  123. # P0-Q3:`2`(平车)必须是"薄车面边梁 + 车面下方暗带"。
  124. # 箱底紧贴的亮带若比 contact_max_h_ratio × 估箱高更厚,它不是车面边梁,
  125. # 而是地面 / 下层箱顶 / 月台 / 货台等大平面 → 不当作车面、不判 2。
  126. contact_max_h_ratio: float = 0.12
  127. # 车面亮带下方必须在 under_deck_search_h_ratio × 画幅内找到一条更暗的
  128. # under_deck_min_h_ratio × 画幅高的带(车底空隙/阴影);找不到 → 不判 2。
  129. under_deck_dark_delta: float = 12.0
  130. under_deck_min_h_ratio: float = 0.01
  131. under_deck_search_h_ratio: float = 0.10
  132. box_height_m: float = 2.591
  133. px_per_m: float = 0.0
  134. min_scale_px: float = 60.0
  135. motion_diff_max: float = 12.0
  136. motion_grad_ratio_min: float = 0.72
  137. require_commit: bool = True
  138. allow_state2: bool = True
  139. structure_hits_min: float = 0.60
  140. # 箱底以下动态 ROI 的最小高度(**原图像素**):太矮时立柱只有 20~27 px,
  141. # 与地面/钢轨纹理不可区分 → 不判 1(与 C++ `min_bed_roi_px` 同口径)。
  142. min_bed_roi_px: int = 90
  143. # P0-0:吊具/钢缆/臂架高悬安全门(默认开)。只在箱体上方区域找
  144. # “长横线 + 上方暗带 + 下方更亮”的组合;宁可弃权,不可把悬空箱
  145. # 当成已落位。
  146. reject_hoist_high: bool = True
  147. hoist_dark_max: int = 75
  148. hoist_band_frac: float = 0.035
  149. hoist_line_ratio: float = 0.20
  150. hoist_dark_ratio: float = 0.55
  151. hoist_bright_delta: float = 12.0
  152. def __post_init__(self) -> None:
  153. if self.work_width < 160:
  154. raise ValueError("work_width 至少 160")
  155. if self.band_min_h < 1:
  156. raise ValueError("band_min_h 至少 1")
  157. if not 0.0 < self.band_max_h_ratio <= 1.0:
  158. raise ValueError("band_max_h_ratio 必须在 (0,1]")
  159. if self.bed_search_ratio <= 0.0:
  160. raise ValueError("bed_search_ratio 必须为正")
  161. if self.below_height_ratio <= 0.0:
  162. raise ValueError("below_height_ratio 必须为正")
  163. if self.min_door_posts < 1:
  164. raise ValueError("min_door_posts 至少 1")
  165. if not 0.0 < self.contact_max_h_ratio <= 0.5:
  166. raise ValueError("contact_max_h_ratio 必须在 (0,0.5]")
  167. if self.under_deck_dark_delta < 0.0:
  168. raise ValueError("under_deck_dark_delta 不能为负")
  169. if not 0.0 < self.under_deck_min_h_ratio <= 0.1:
  170. raise ValueError("under_deck_min_h_ratio 必须在 (0,0.1]")
  171. if not 0.0 < self.under_deck_search_h_ratio <= 0.5:
  172. raise ValueError("under_deck_search_h_ratio 必须在 (0,0.5]")
  173. if self.min_post_spacing_px < 0.0:
  174. raise ValueError("min_post_spacing_px 不能为负")
  175. if not 0.0 <= self.min_post_span_ratio <= 1.0:
  176. raise ValueError("min_post_span_ratio 必须在 [0,1]")
  177. if self.texture_grad_th <= 0.0:
  178. raise ValueError("texture_grad_th 必须 > 0")
  179. if self.texture_block_px < 4:
  180. raise ValueError("texture_block_px 至少 4")
  181. if not 0.0 <= self.texture_block_hit_ratio <= 1.0:
  182. raise ValueError("texture_block_hit_ratio 必须在 [0,1]")
  183. if not 0.0 <= self.texture_coverage_min <= 1.0:
  184. raise ValueError("texture_coverage_min 必须在 [0,1]")
  185. if self.texture_run_rows < 1 or self.texture_smooth_rows < 1:
  186. raise ValueError("texture_run_rows / texture_smooth_rows 至少 1")
  187. if not 0.0 <= self.texture_top_margin_ratio <= 0.5:
  188. raise ValueError("texture_top_margin_ratio 必须在 [0,0.5]")
  189. if not 0.0 < self.body_bottom_ratio <= 1.0:
  190. raise ValueError("body_bottom_ratio 必须在 (0,1]")
  191. if not 0.0 <= self.body_min_opacity <= 1.0:
  192. raise ValueError("body_min_opacity 必须在 [0,1]")
  193. if self.body_min_roi_px < 8:
  194. raise ValueError("body_min_roi_px 至少 8")
  195. if not 0.0 <= self.body_x_margin_ratio <= 0.5:
  196. raise ValueError("body_x_margin_ratio 必须在 [0,0.5]")
  197. if self.body_min_posts < 1:
  198. raise ValueError("body_min_posts 至少 1")
  199. if self.min_diagonal_braces < 0:
  200. raise ValueError("min_diagonal_braces 不能为负")
  201. if self.box_height_m <= 0.0:
  202. raise ValueError("box_height_m 必须为正")
  203. @classmethod
  204. def from_config(cls, cfg: Config) -> "EvidenceV2Params":
  205. raw = cfg.section("evidence_v2")
  206. window = raw.get("window") or [0.24, 0.02, 0.78, 0.95]
  207. if len(window) != 4:
  208. raise ValueError("evidence_v2.window 需要 4 个数字")
  209. return cls(
  210. enabled=bool(raw.get("enabled", False)),
  211. view=ViewMode.parse(raw.get("view", "front")),
  212. work_width=int(raw.get("work_width", 960)),
  213. window=tuple(float(v) for v in window), # type: ignore[arg-type]
  214. band_min_h=int(raw.get("band_min_h", 3)),
  215. band_max_h_ratio=float(raw.get("band_max_h_ratio", 0.15)),
  216. bed_search_ratio=float(raw.get("bed_search_ratio", 0.40)),
  217. box_bottom_max_ratio=float(raw.get("box_bottom_max_ratio", 0.78)),
  218. below_start_ratio=float(raw.get("below_start_ratio", 0.07)),
  219. below_height_ratio=float(raw.get("below_height_ratio", 0.55)),
  220. below_min_height_px=int(raw.get("below_min_height_px", 24)),
  221. min_door_posts=int(raw.get("min_door_posts", 5)),
  222. max_door_posts=int(raw.get("max_door_posts", 16)),
  223. max_bed_gap_px=float(raw.get("max_bed_gap_px", 40.0)),
  224. flat_max_door_posts=int(raw.get("flat_max_door_posts", 4)),
  225. max_post_spacing_cv=float(raw.get("max_post_spacing_cv", 6.0)),
  226. min_post_len_ratio=float(raw.get("min_post_len_ratio", 0.30)),
  227. min_post_spacing_px=float(raw.get("min_post_spacing_px", 24.0)),
  228. min_post_span_ratio=float(raw.get("min_post_span_ratio", 0.23)),
  229. texture_top_enable=bool(raw.get("texture_top_enable", True)),
  230. texture_grad_th=float(raw.get("texture_grad_th", 50.0)),
  231. texture_block_px=int(raw.get("texture_block_px", 16)),
  232. texture_block_hit_ratio=float(raw.get("texture_block_hit_ratio", 0.03)),
  233. texture_coverage_min=float(raw.get("texture_coverage_min", 0.50)),
  234. texture_run_rows=int(raw.get("texture_run_rows", 3)),
  235. texture_smooth_rows=int(raw.get("texture_smooth_rows", 7)),
  236. texture_top_margin_ratio=float(raw.get("texture_top_margin_ratio", 0.02)),
  237. body_fallback_enable=bool(raw.get("body_fallback_enable", True)),
  238. body_bottom_ratio=float(raw.get("body_bottom_ratio", 0.75)),
  239. body_min_opacity=float(raw.get("body_min_opacity", 0.50)),
  240. body_min_roi_px=int(raw.get("body_min_roi_px", 90)),
  241. body_x_margin_ratio=float(raw.get("body_x_margin_ratio", 0.03)),
  242. body_min_posts=int(raw.get("body_min_posts", 3)),
  243. vehicle_min_span_ratio=float(raw.get("vehicle_min_span_ratio", 0.50)),
  244. vehicle_max_posts=int(raw.get("vehicle_max_posts", 60)),
  245. min_diagonal_braces=int(raw.get("min_diagonal_braces", 1)),
  246. min_wall_opacity=float(raw.get("min_wall_opacity", 0.35)),
  247. max_flat_gap_px=float(raw.get("max_flat_gap_px", 40.0)),
  248. wall_edge_density_ref=float(raw.get("wall_edge_density_ref", 0.14)),
  249. wall_edge_density_span=float(raw.get("wall_edge_density_span", 0.04)),
  250. ground_block_px=int(raw.get("ground_block_px", 32)),
  251. ground_density_lo=float(raw.get("ground_density_lo", 0.02)),
  252. ground_density_hi=float(raw.get("ground_density_hi", 0.35)),
  253. min_zero_ground_ratio=float(raw.get("min_zero_ground_ratio", 0.65)),
  254. deck_min_len_ratio=float(raw.get("deck_min_len_ratio", 0.30)),
  255. contact_max_h_ratio=float(raw.get("contact_max_h_ratio", 0.12)),
  256. under_deck_dark_delta=float(raw.get("under_deck_dark_delta", 12.0)),
  257. under_deck_min_h_ratio=float(raw.get("under_deck_min_h_ratio", 0.01)),
  258. under_deck_search_h_ratio=float(raw.get("under_deck_search_h_ratio", 0.10)),
  259. box_height_m=float(raw.get("box_height_m", 2.591)),
  260. px_per_m=float(raw.get("px_per_m", 0.0)),
  261. min_scale_px=float(raw.get("min_scale_px", 60.0)),
  262. motion_diff_max=float(raw.get("motion_diff_max", 12.0)),
  263. motion_grad_ratio_min=float(raw.get("motion_grad_ratio_min", 0.72)),
  264. require_commit=bool(raw.get("require_commit", True)),
  265. allow_state2=bool(raw.get("allow_state2", True)),
  266. structure_hits_min=float(raw.get("structure_hits_min", 0.60)),
  267. min_bed_roi_px=int(raw.get("min_bed_roi_px", 90)),
  268. reject_hoist_high=bool(raw.get("reject_hoist_high", True)),
  269. hoist_dark_max=int(raw.get("hoist_dark_max", 75)),
  270. hoist_band_frac=float(raw.get("hoist_band_frac", 0.035)),
  271. hoist_line_ratio=float(raw.get("hoist_line_ratio", 0.20)),
  272. hoist_dark_ratio=float(raw.get("hoist_dark_ratio", 0.55)),
  273. hoist_bright_delta=float(raw.get("hoist_bright_delta", 12.0)),
  274. )
  275. @dataclass
  276. class EvidenceV2Result:
  277. """单帧 v2 证据与分类结果(所有坐标均为原图像素)。"""
  278. state: int = int(SceneState.UNKNOWN)
  279. confidence: float = 0.0
  280. view: ViewMode = ViewMode.UNKNOWN
  281. box_bottom_y: Optional[float] = None
  282. box_top_y: Optional[float] = None
  283. texture_top_y: Optional[float] = None
  284. box_h_px: Optional[float] = None
  285. px_per_m: Optional[float] = None
  286. scale_ok: bool = False
  287. bed_top_y: Optional[float] = None
  288. gap_px: Optional[float] = None
  289. gap_m: Optional[float] = None
  290. door_posts: int = 0
  291. post_spacing_px: Optional[float] = None
  292. post_spacing_cv: Optional[float] = None
  293. rect_doors: int = 0
  294. diagonal_braces: int = 0
  295. wall_opacity: float = 0.0
  296. deck_edge: bool = False
  297. under_deck: bool = False
  298. wheel_count: int = 0
  299. ground_ratio: float = 0.0
  300. phase: CommitPhase = CommitPhase.T1
  301. committed: bool = False
  302. commit_reason: str = "init"
  303. stable_frames: int = 0
  304. structure_frames: int = 0
  305. motion_ok: bool = True
  306. hoist_high: bool = False
  307. abstain_reason: str = ""
  308. below_roi: Tuple[int, int, int, int] = (0, 0, 0, 0)
  309. diagnostics: Dict[str, object] = field(default_factory=dict)
  310. @property
  311. def candidate_state(self) -> int:
  312. """分类候选(未经 commit 门);诊断/回放用。"""
  313. return int(self.state)
  314. def publishable(self, require_commit: bool = True) -> bool:
  315. if int(self.state) not in (0, 1, 2):
  316. return False
  317. if not require_commit:
  318. return True
  319. return bool(self.committed)
  320. def to_observation(
  321. self,
  322. ts: float = 0.0,
  323. frame_id: int = 0,
  324. detections: Optional[Sequence[object]] = None,
  325. *,
  326. require_commit: bool = True,
  327. ) -> Observation:
  328. """转成现有 ``TemporalVoter`` 可消费的 ``Observation``。
  329. commit 不成立时输出内部 255(不是 0),并保留分类候选在 reason 里。
  330. """
  331. ok = self.publishable(require_commit)
  332. state = int(self.state) if ok else int(SceneState.UNKNOWN)
  333. conf = float(self.confidence) if ok else 0.0
  334. reason = "v2:%s view=%s top=%s posts=%d opacity=%.2f deck=%d under_deck=%d gap=%s commit=%s hoist=%d" % (
  335. "ok" if ok else "abstain",
  336. self.view.value,
  337. "n/a" if self.texture_top_y is None else "%.0f" % self.texture_top_y,
  338. int(self.door_posts),
  339. float(self.wall_opacity),
  340. int(bool(self.deck_edge)),
  341. int(bool(self.under_deck)),
  342. "n/a" if self.gap_px is None else "%.0fpx" % self.gap_px,
  343. self.commit_reason,
  344. int(bool(self.hoist_high)),
  345. )
  346. if not ok and self.abstain_reason:
  347. reason += " reason=%s" % self.abstain_reason
  348. return Observation(
  349. ts=float(ts),
  350. state=state,
  351. confidence=conf,
  352. detections=list(detections or []),
  353. reason=reason,
  354. frame_id=int(frame_id),
  355. )
  356. def to_dict(self) -> Dict[str, object]:
  357. return {
  358. "state": int(self.state),
  359. "confidence": round(float(self.confidence), 4),
  360. "view": self.view.value,
  361. "box_bottom_y": _round_opt(self.box_bottom_y),
  362. "box_top_y": _round_opt(self.box_top_y),
  363. "texture_top_y": _round_opt(self.texture_top_y),
  364. "box_h_px": _round_opt(self.box_h_px),
  365. "px_per_m": _round_opt(self.px_per_m),
  366. "scale_ok": bool(self.scale_ok),
  367. "bed_top_y": _round_opt(self.bed_top_y),
  368. "gap_px": _round_opt(self.gap_px),
  369. "gap_m": _round_opt(self.gap_m, 4),
  370. "door_posts": int(self.door_posts),
  371. "post_spacing_px": _round_opt(self.post_spacing_px),
  372. "post_spacing_cv": _round_opt(self.post_spacing_cv, 3),
  373. "rect_doors": int(self.rect_doors),
  374. "diagonal_braces": int(self.diagonal_braces),
  375. "wall_opacity": round(float(self.wall_opacity), 3),
  376. "deck_edge": bool(self.deck_edge),
  377. "under_deck": bool(self.under_deck),
  378. "wheel_count": int(self.wheel_count),
  379. "ground_ratio": round(float(self.ground_ratio), 3),
  380. "phase": self.phase.value,
  381. "committed": bool(self.committed),
  382. "commit_reason": self.commit_reason,
  383. "stable_frames": int(self.stable_frames),
  384. "structure_frames": int(self.structure_frames),
  385. "motion_ok": bool(self.motion_ok),
  386. "hoist_high": bool(self.hoist_high),
  387. "abstain_reason": self.abstain_reason,
  388. "below_roi": [int(v) for v in self.below_roi],
  389. "diagnostics": dict(self.diagnostics),
  390. }
  391. def _round_opt(value: Optional[float], digits: int = 2) -> Optional[float]:
  392. if value is None:
  393. return None
  394. return round(float(value), digits)
  395. def _to_gray(image: np.ndarray) -> np.ndarray:
  396. if image is None:
  397. return np.zeros((0, 0), dtype=np.uint8)
  398. if image.ndim == 2:
  399. return image.astype(np.uint8, copy=False)
  400. if cv2 is None: # pragma: no cover
  401. raise RuntimeError("需要 opencv-python 进行彩色转换")
  402. if image.shape[2] == 4:
  403. return cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
  404. return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  405. def find_texture_top(gray: np.ndarray, window: Tuple[int, int, int, int],
  406. params: EvidenceV2Params) -> float:
  407. """P0-Q4:用“竖向梯度块覆盖率”找车体顶;-1 = 未找到/关闭。"""
  408. if not params.texture_top_enable or gray.size == 0:
  409. return -1.0
  410. gx = np.abs(cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3))
  411. x0 = max(0, min(int(window[0]), gray.shape[1]))
  412. x1 = min(gray.shape[1], max(x0, int(window[2])))
  413. block = max(4, int(params.texture_block_px))
  414. nb = (x1 - x0) // block
  415. if nb < 2:
  416. return -1.0
  417. cov = np.zeros(gray.shape[0], dtype=np.float32)
  418. for y in range(gray.shape[0]):
  419. hit = 0
  420. for i in range(nb):
  421. bx = x0 + i * block
  422. if float((gx[y, bx:bx + block] >= params.texture_grad_th).mean()) >= \
  423. params.texture_block_hit_ratio:
  424. hit += 1
  425. cov[y] = hit / nb
  426. smooth = max(1, int(params.texture_smooth_rows))
  427. sm = np.convolve(cov, np.ones(smooth, dtype=np.float32) / smooth, mode="same")
  428. run = max(1, int(params.texture_run_rows))
  429. for y in range(max(0, int(window[1])), gray.shape[0] - run + 1):
  430. if all(sm[y + k] >= params.texture_coverage_min for k in range(run)):
  431. return float(y)
  432. return -1.0
  433. def _row_mean(gray: np.ndarray, x0: int, x1: int, y0: int, y1: int) -> float:
  434. """``[x0,x1) × [y0,y1)`` 的灰度均值(越界自动钳制;空框返回 0)。"""
  435. h, w = gray.shape[:2]
  436. xa = max(0, min(int(x0), w))
  437. xb = max(xa, min(int(x1), w))
  438. ya = max(0, min(int(y0), h))
  439. yb = max(ya, min(int(y1), h))
  440. if xb <= xa or yb <= ya:
  441. return 0.0
  442. return float(gray[ya:yb, xa:xb].mean())
  443. def horizontal_bands(
  444. gray: np.ndarray,
  445. roi: Tuple[int, int, int, int],
  446. min_h: int = 3,
  447. max_h: int = 90,
  448. topn: int = 12,
  449. ) -> Tuple[List[Band], List[Band]]:
  450. """行均值纵向 Sobel 找水平亮带/暗带(P0 算法的生产化版本)。
  451. 返回 ``(bright, dark)``;``y0/y1`` 是原图坐标。亮带 = 中间比上下亮,
  452. 暗带 = 中间比上下暗。算法只用行均值,因此在箱体移动/局部纹理下比
  453. 全画面霍夫更稳定。
  454. """
  455. if cv2 is None: # pragma: no cover
  456. raise RuntimeError("evidence_v2 需要 opencv-python")
  457. x0, y0, x1, y1 = [int(v) for v in roi]
  458. x0 = max(0, x0)
  459. y0 = max(0, y0)
  460. x1 = min(int(gray.shape[1]), x1)
  461. y1 = min(int(gray.shape[0]), y1)
  462. if x1 <= x0 or y1 <= y0:
  463. return [], []
  464. crop = gray[y0:y1, x0:x1].astype(np.float32)
  465. if crop.size == 0:
  466. return [], []
  467. crop = cv2.GaussianBlur(crop, (3, 3), 0)
  468. gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
  469. mag = np.abs(gy)
  470. if mag.size == 0:
  471. return [], []
  472. if mag.size < 3:
  473. return [], []
  474. limit = float(mag.mean() + 0.9 * mag.std())
  475. # 峰值抑制:同一道边缘常在相邻 1~2 行出现两个极值(例如箱底 3 px
  476. # 暗带:y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内
  477. # 严格最大:167 会压掉 168,168 又压掉 170,最终只剩一个负峰,
  478. # 暗带无法配对,整帧直接 no_box。这里先取 ±1 行局部极大,再按幅值
  479. # 贪心抑制 3 px 内的重复峰,既保留 3 px 薄带,又不拆散同一道边缘。
  480. min_sep = max(2, int(round(min_h)))
  481. candidates = [
  482. i for i in range(1, len(mag) - 1)
  483. if mag[i] >= limit and mag[i] >= mag[i - 1] and mag[i] >= mag[i + 1]
  484. ]
  485. picked: List[int] = []
  486. for i in sorted(candidates, key=lambda j: mag[j], reverse=True):
  487. if all(abs(i - j) >= min_sep for j in picked):
  488. picked.append(i)
  489. picked.sort()
  490. events: List[Tuple[int, float]] = [(i, float(gy[i])) for i in picked]
  491. bright: List[Band] = []
  492. dark: List[Band] = []
  493. for j in range(len(events) - 1):
  494. i1, v1 = events[j]
  495. i2, v2 = events[j + 1]
  496. height = i2 - i1
  497. if height < min_h or height > max_h:
  498. continue
  499. strength = min(abs(v1), abs(v2))
  500. if strength <= 0.0:
  501. continue
  502. if v1 > 0.0 > v2:
  503. bright.append(Band(float(y0 + i1), float(y0 + i2), strength))
  504. elif v1 < 0.0 < v2:
  505. dark.append(Band(float(y0 + i1), float(y0 + i2), strength))
  506. bright.sort(key=lambda b: b.strength, reverse=True)
  507. dark.sort(key=lambda b: b.strength, reverse=True)
  508. return bright[:topn], dark[:topn]
  509. def pick_box_and_bed(
  510. bright: Sequence[Band],
  511. dark: Sequence[Band],
  512. frame_h: int,
  513. *,
  514. box_bottom_max_ratio: float = 0.78,
  515. bed_search_px: float = 120.0,
  516. ) -> Tuple[Optional[Band], Optional[Band]]:
  517. """选箱底暗带与它下方最近的车体上缘亮带(与 P0 同口径)。"""
  518. upper = [
  519. b for b in dark
  520. if b.y1 <= box_bottom_max_ratio * frame_h and b.y0 >= 0.02 * frame_h
  521. ]
  522. if not upper:
  523. return None, None
  524. strongest = max(b.strength for b in upper)
  525. strong = [b for b in upper if b.strength >= 0.45 * strongest]
  526. box = min(strong, key=lambda b: b.y0)
  527. below = [b for b in bright if b.y0 >= box.y1 - 1.0 and b.y0 <= box.y1 + bed_search_px]
  528. bed = min(below, key=lambda b: b.y0) if below else None
  529. return box, bed
  530. def ground_like_ratio(
  531. gray: np.ndarray,
  532. roi: Tuple[int, int, int, int],
  533. segments: Sequence[Dict[str, float]],
  534. *,
  535. block_px: int = 32,
  536. density_lo: float = 0.02,
  537. density_hi: float = 0.35,
  538. ) -> Tuple[float, int]:
  539. """分块“地面样”比例:纹理密度在区间内且块内无长直线。
  540. 与 v1 ``edge_evidence.cpp::region_stats`` 的 ``ground_like`` 同口径;
  541. 门板立柱是**竖线**、门板横梁/车面边梁是**横线**,两者都算结构面。
  542. """
  543. if cv2 is None: # pragma: no cover
  544. return 0.0, 0
  545. x0, y0, x1, y1 = [int(v) for v in roi]
  546. crop = gray[y0:y1, x0:x1]
  547. if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
  548. return 0.0, 0
  549. gx = cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3)
  550. gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3)
  551. mag = np.sqrt(gx * gx + gy * gy)
  552. ref = float(np.percentile(mag, 60.0))
  553. hot = mag > ref
  554. b = max(6, int(block_px))
  555. total = 0
  556. ground = 0
  557. for by in range(0, crop.shape[0], b):
  558. for bx in range(0, crop.shape[1], b):
  559. ex = min(crop.shape[1], bx + b)
  560. ey = min(crop.shape[0], by + b)
  561. block = hot[by:ey, bx:ex]
  562. if block.size == 0:
  563. continue
  564. density = float(block.mean())
  565. long_line = any(
  566. float(seg["length"]) >= 0.6 * b
  567. and bx + x0 <= (float(seg["x0"]) + float(seg["x1"])) * 0.5 <= ex + x0
  568. and by + y0 <= (float(seg["y0"]) + float(seg["y1"])) * 0.5 <= ey + y0
  569. for seg in segments
  570. if "x0" in seg and "x1" in seg and "y0" in seg and "y1" in seg
  571. )
  572. total += 1
  573. if not long_line and density_lo <= density <= density_hi:
  574. ground += 1
  575. return (float(ground) / float(total) if total else 0.0), total
  576. def _cluster_positions(values: Sequence[float], gap_px: float) -> List[float]:
  577. ordered = sorted(float(v) for v in values)
  578. if not ordered:
  579. return []
  580. clusters: List[List[float]] = [[ordered[0]]]
  581. for value in ordered[1:]:
  582. if value - clusters[-1][-1] <= gap_px:
  583. clusters[-1].append(value)
  584. else:
  585. clusters.append([value])
  586. return [float(statistics.median(c)) for c in clusters]
  587. def detect_structure_v2(
  588. gray: np.ndarray,
  589. roi: Tuple[int, int, int, int],
  590. *,
  591. min_post_len_ratio: float = 0.30,
  592. cluster_gap_px: float = 9.0,
  593. scale: float = 1.0,
  594. ) -> Dict[str, object]:
  595. """箱底以下 ROI 的门板立柱 / 斜撑 / 矩形门 / 水平边梁。
  596. 只做**证据计数**,不做分类;返回的坐标相对 ROI(线段另带
  597. ``y`` 原图坐标,供 deck_edge 使用)。
  598. """
  599. if cv2 is None: # pragma: no cover
  600. raise RuntimeError("evidence_v2 需要 opencv-python")
  601. x0, y0, x1, y1 = [int(v) for v in roi]
  602. crop = gray[y0:y1, x0:x1]
  603. empty = {
  604. "vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0,
  605. "rect_doors": 0, "post_count": 0, "post_positions": [], "post_spacing_median": None,
  606. "post_spacing_cv": None, "edge_density": 0.0,
  607. "horizontal": [], "lines": [],
  608. }
  609. if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
  610. return empty
  611. crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop)
  612. edges = cv2.Canny(crop, 50, 150)
  613. roi_h = max(1, crop.shape[0])
  614. roi_area = float(crop.shape[0] * crop.shape[1])
  615. lines = cv2.HoughLinesP(
  616. edges, 1, math.pi / 180.0, threshold=24,
  617. minLineLength=max(12, int(round(20 * scale))), maxLineGap=max(4, int(round(8 * scale))),
  618. )
  619. vertical: List[Tuple[float, float, float]] = []
  620. horizontal: List[Dict[str, float]] = []
  621. all_lines: List[Dict[str, float]] = []
  622. diagonal = 0
  623. if lines is not None:
  624. flat = np.asarray(lines).reshape(-1, 4)
  625. for raw in flat:
  626. xa, ya, xb, yb = (float(v) for v in raw)
  627. dx, dy = xb - xa, yb - ya
  628. length = math.hypot(dx, dy)
  629. if length < max(12.0, 20.0 * scale):
  630. continue
  631. all_lines.append({
  632. "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
  633. "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
  634. "length": length,
  635. })
  636. if abs(dy) >= 1.8 * abs(dx):
  637. vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb)))
  638. elif abs(dx) >= 1.8 * abs(dy):
  639. horizontal.append({
  640. "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
  641. "y": y0 + (ya + yb) * 0.5, "length": length,
  642. "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
  643. })
  644. else:
  645. diagonal += 1
  646. posts = [v for v in vertical if (v[2] - v[1]) >= min_post_len_ratio * roi_h]
  647. post_x = _cluster_positions([v[0] for v in posts], max(3.0, cluster_gap_px * scale))
  648. spacings = [post_x[i + 1] - post_x[i] for i in range(len(post_x) - 1)]
  649. spacing_median = float(statistics.median(spacings)) if spacings else None
  650. spacing_cv = None
  651. if len(spacings) >= 2 and spacing_median:
  652. spacing_cv = float(statistics.pstdev(spacings) / spacing_median)
  653. contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  654. rect_doors = 0
  655. for contour in contours:
  656. area = cv2.contourArea(contour)
  657. if area < 180.0 or area > 0.20 * roi_area:
  658. continue
  659. peri = cv2.arcLength(contour, True)
  660. if peri <= 0.0:
  661. continue
  662. approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
  663. if not (4 <= len(approx) <= 6):
  664. continue
  665. _, _, bw, bh = cv2.boundingRect(approx)
  666. if bh <= 0:
  667. continue
  668. aspect = bw / float(bh)
  669. if 0.30 <= aspect <= 3.2:
  670. rect_doors += 1
  671. return {
  672. "vertical_lines": len(posts),
  673. "diagonal_lines": int(diagonal),
  674. "horizontal_lines": len(horizontal),
  675. "rect_doors": int(rect_doors),
  676. "post_count": len(post_x),
  677. "post_positions": [float(x) for x in post_x],
  678. "post_spacing_median": spacing_median,
  679. "post_spacing_cv": spacing_cv,
  680. "edge_density": float(edges.mean() / 255.0),
  681. "horizontal": horizontal,
  682. "lines": all_lines,
  683. }
  684. def detect_spreader_contact(
  685. gray: np.ndarray,
  686. container_bbox: Tuple[float, float, float, float],
  687. *,
  688. dark_max: int = 110,
  689. dark_ratio: float = 0.55,
  690. ) -> Tuple[bool, Dict[str, object]]:
  691. """检测集装箱上沿紧邻的吊具横梁(吊具仍夹着箱)。
  692. 负样本里最典型的误判是:算法把**箱侧壁瓦楞**当成车斗门板,箱底
  693. 又恰好贴到画面上某个横向结构,于是 5 帧后 commit。真正落位时,
  694. 箱顶上方不应存在一条“紧贴箱顶、横跨箱宽、明显更暗”的横梁;吊具
  695. 未松开时这条横梁必然存在。
  696. 只使用检测器给出的 container 框(不是 ``box_top`` 自标尺),因此
  697. 不受箱高估计误差影响。返回值第二项为诊断。
  698. """
  699. empty = {"spreader_contact": False, "dark_run_px": 0, "band_delta": 0.0}
  700. if gray is None or gray.size == 0:
  701. return False, empty
  702. h, w = gray.shape[:2]
  703. x1, y1, x2, y2 = [int(round(v)) for v in container_bbox]
  704. x1, x2 = max(0, min(x1, x2)), min(w, max(x1, x2))
  705. y1, y2 = max(0, min(y1, y2)), min(h, max(y1, y2))
  706. box_h = y2 - y1
  707. box_w = x2 - x1
  708. if box_h < 20 or box_w < 20:
  709. return False, empty
  710. probe = max(4, int(0.30 * box_h))
  711. y0 = max(0, y1 - probe)
  712. roi = gray[y0:y1, x1:x2]
  713. if roi.shape[0] < 3:
  714. return False, empty
  715. dark = roi < int(dark_max)
  716. frac = dark.mean(axis=1)
  717. min_run = max(3, int(0.02 * box_h))
  718. runs = []
  719. run_start = None
  720. for row, value in enumerate(frac):
  721. if value >= dark_ratio:
  722. if run_start is None:
  723. run_start = row
  724. elif run_start is not None:
  725. if (row - run_start) >= min_run:
  726. runs.append((run_start, row - 1))
  727. run_start = None
  728. if run_start is not None and (len(frac) - run_start) >= min_run:
  729. runs.append((run_start, len(frac) - 1))
  730. if not runs:
  731. return False, empty
  732. # 优先选离箱顶最近的一条暗横梁:吊具夹着箱时它紧贴箱顶;更长的
  733. # 远处吊臂不能替代它,否则会把“远处横梁”误当成“已落位”。
  734. best_start, best_end = min(runs, key=lambda item: (len(frac) - 1 - item[1], item[0] - item[1]))
  735. if (len(frac) - 1 - best_end) > max(2, int(0.08 * box_h)):
  736. return False, empty
  737. band = roi[best_start:best_end + 1, :]
  738. below = gray[y1:min(h, y1 + max(6, int(0.06 * box_h))), x1:x2]
  739. if band.size == 0 or below.size == 0:
  740. return False, empty
  741. band_mean = float(band.mean())
  742. below_mean = float(below.mean())
  743. if below_mean < band_mean + 10.0:
  744. return False, empty
  745. return True, {
  746. "spreader_contact": True,
  747. "dark_run_px": int(best_end - best_start + 1),
  748. "band_delta": round(below_mean - band_mean, 2),
  749. }
  750. def detect_hoist_high(
  751. gray: np.ndarray,
  752. box_top_y: float,
  753. *,
  754. dark_max: int = 75,
  755. band_frac: float = 0.035,
  756. line_ratio: float = 0.30,
  757. dark_ratio: float = 0.55,
  758. bright_delta: float = 12.0,
  759. ) -> Tuple[bool, Dict[str, object]]:
  760. """检测箱体上方的吊具/臂架/钢缆高悬特征。
  761. 只看**候选箱体上沿以上**的区域,要求同时满足:
  762. * 至少一条横跨画面中央的长横线(Hough);
  763. * 横线上方是一条暗带(吊具/臂架本体);
  764. * 暗带下方明显更亮(天空、箱顶或车体),说明暗带是遮挡物而不是
  765. 箱体本身的暗边。
  766. 这三个条件是为了避开集装箱侧壁的竖向瓦楞和车体横梁:A/B 正样本的
  767. 箱顶通常已被画幅裁掉(``box_top_y`` 很小),不会进入该区域;负样本
  768. (屏幕录制)上方有明显黑色吊臂/吊具,会被拦下。返回值第二项只用于
  769. 诊断,不参与安全判定。
  770. """
  771. empty = {"hoist_high": False, "horizontal_lines": 0, "cables": 0}
  772. if cv2 is None or gray is None or gray.size == 0:
  773. return False, empty
  774. h, w = gray.shape[:2]
  775. limit = int(min(max(8.0, float(box_top_y) - 2.0), 0.45 * h))
  776. if limit < max(12, int(0.06 * h)) or w < 32:
  777. return False, empty
  778. scale = min(1.0, 480.0 / float(w))
  779. if scale < 1.0:
  780. work = cv2.resize(
  781. gray, (int(round(w * scale)), int(round(h * scale))),
  782. interpolation=cv2.INTER_AREA,
  783. )
  784. else:
  785. work = gray
  786. hh, ww = work.shape[:2]
  787. limit_w = min(hh, max(1, int(round(limit * scale))))
  788. roi = work[:limit_w, :]
  789. if roi.shape[0] < 12 or roi.shape[1] < 32:
  790. return False, empty
  791. blur = cv2.GaussianBlur(roi, (5, 5), 0)
  792. edges = cv2.Canny(blur, 50, 150)
  793. lines = cv2.HoughLinesP(
  794. edges,
  795. 1,
  796. math.pi / 180.0,
  797. threshold=15,
  798. minLineLength=max(10, int(line_ratio * ww)),
  799. maxLineGap=max(4, int(0.03 * ww)),
  800. )
  801. horizontal_hits = 0
  802. cables = 0
  803. x0 = int(0.10 * ww)
  804. x1 = max(x0 + 8, int(0.90 * ww))
  805. band_h = max(3, int(band_frac * hh))
  806. if lines is not None:
  807. for raw in np.asarray(lines).reshape(-1, 4):
  808. xa, ya, xb, yb = (float(v) for v in raw)
  809. dx, dy = abs(xb - xa), abs(yb - ya)
  810. if dx < line_ratio * ww * 0.8:
  811. continue
  812. # 近水平线:吊具横梁/臂架下缘
  813. if dy <= max(3.0, 0.04 * dx):
  814. y = int(round((ya + yb) * 0.5))
  815. if y - band_h < 0 or y + 2 >= limit_w:
  816. continue
  817. band = blur[y - band_h:y, x0:x1]
  818. below = blur[y + 2:min(limit_w, y + 2 + 2 * band_h), x0:x1]
  819. if band.size == 0 or below.size == 0:
  820. continue
  821. dark = float(np.mean(band < int(dark_max)))
  822. if dark >= dark_ratio and float(below.mean()) >= float(band.mean()) + bright_delta:
  823. horizontal_hits += 1
  824. # 近竖直线:钢缆/油管(只作诊断与辅助确认)
  825. elif dy >= max(6.0, 4.0 * dx) and dy >= 0.12 * hh:
  826. xs = np.linspace(xa, xb, num=12)
  827. ys = np.linspace(ya, yb, num=12)
  828. samples = [
  829. blur[int(round(yv)), int(round(xv))]
  830. for xv, yv in zip(xs, ys)
  831. if 0 <= int(round(yv)) < limit_w and 0 <= int(round(xv)) < ww
  832. ]
  833. if samples and float(np.mean(samples)) <= float(dark_max) + 25.0:
  834. cables += 1
  835. hoist = horizontal_hits >= 1
  836. return hoist, {
  837. "hoist_high": bool(hoist),
  838. "horizontal_lines": int(horizontal_hits),
  839. "cables": int(cables),
  840. }
  841. class EvidenceV2:
  842. """前视 v2 证据提取 + 分类 + commit 门(线程内使用)。"""
  843. def __init__(self, params: Optional[EvidenceV2Params] = None,
  844. tracker: Optional[CommitTracker] = None) -> None:
  845. self.p = params or EvidenceV2Params()
  846. self.tracker = tracker or CommitTracker()
  847. self._last = EvidenceV2Result(view=self.p.view)
  848. self._prev_thumb: Optional[np.ndarray] = None
  849. self._prev_mag = 0.0
  850. @classmethod
  851. def from_config(cls, cfg: Config) -> "EvidenceV2":
  852. return cls(EvidenceV2Params.from_config(cfg), CommitTracker.from_config(cfg))
  853. @property
  854. def last(self) -> EvidenceV2Result:
  855. return self._last
  856. def reset(self) -> None:
  857. self.tracker.reset()
  858. self._prev_thumb = None
  859. self._prev_mag = 0.0
  860. self._last = EvidenceV2Result(view=self.p.view)
  861. # ------------------------------------------------------------ 运动门控
  862. def _motion(self, gray: np.ndarray) -> Tuple[bool, float, float]:
  863. if cv2 is None: # pragma: no cover
  864. return True, 0.0, 1.0
  865. thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA)
  866. lap = cv2.Laplacian(thumb, cv2.CV_32F)
  867. mag = float(np.abs(lap).mean())
  868. if self._prev_thumb is None:
  869. self._prev_thumb = thumb
  870. self._prev_mag = mag
  871. return True, 0.0, 1.0
  872. diff = float(np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean())
  873. ratio = (mag / self._prev_mag) if self._prev_mag > 1e-6 else 1.0
  874. ok = diff <= self.p.motion_diff_max and ratio >= self.p.motion_grad_ratio_min
  875. self._prev_thumb = thumb
  876. self._prev_mag = 0.8 * self._prev_mag + 0.2 * mag if self._prev_mag > 0 else mag
  877. return ok, diff, ratio
  878. # ------------------------------------------------------------ 自标尺
  879. def _scale_from_vertical(
  880. self,
  881. gray: np.ndarray,
  882. box: Band,
  883. window: Tuple[int, int, int, int],
  884. scale: float,
  885. ) -> Tuple[Optional[float], Optional[float]]:
  886. """用箱体近端竖棱估 ``px_per_m``;失败返回 ``(None, None)``。"""
  887. if cv2 is None: # pragma: no cover
  888. return None, None
  889. if self.p.px_per_m > 0.0:
  890. px_per_m = float(self.p.px_per_m)
  891. return px_per_m, None
  892. x0, y0, x1, _ = [int(v) for v in window]
  893. y1 = max(1, int(box.y0))
  894. crop = gray[max(0, y0):y1, max(0, x0):min(gray.shape[1], x1)]
  895. if crop.size == 0:
  896. return None, None
  897. edges = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop), 50, 150)
  898. lines = cv2.HoughLinesP(
  899. edges, 1, math.pi / 180.0, threshold=24,
  900. minLineLength=max(12, int(self.p.min_scale_px * scale)),
  901. maxLineGap=max(4, int(10 * scale)),
  902. )
  903. best = 0.0
  904. if lines is not None:
  905. for raw in np.asarray(lines).reshape(-1, 4):
  906. xa, ya, xb, yb = (float(v) for v in raw)
  907. dx, dy = abs(xb - xa), abs(yb - ya)
  908. if dy >= 2.0 * dx and dy > best:
  909. best = dy
  910. if best < self.p.min_scale_px * scale:
  911. return None, None
  912. px_per_m_work = best / self.p.box_height_m
  913. return px_per_m_work / max(scale, 1e-6), best
  914. # ------------------------------------------------------------ 分类
  915. def _classify(
  916. self,
  917. *,
  918. posts: int,
  919. spacing_cv: Optional[float],
  920. opacity: float,
  921. ground: float,
  922. deck: bool,
  923. wheels: int,
  924. gap_px: Optional[float],
  925. motion_ok: bool,
  926. view: ViewMode,
  927. under_deck: bool = False,
  928. post_spacing_px: Optional[float] = None,
  929. diagonal_braces: int = 0,
  930. post_span_ratio: float = 0.0,
  931. below_roi_h_px: float = 0.0,
  932. ) -> Tuple[int, float, float, str]:
  933. """返回 ``(state, confidence, structure_hits, reason)``。
  934. ``under_deck``:车面亮带下方是否找到"车底空隙/阴影"暗带(P0-Q3)。
  935. ``post_spacing_px``:门板立柱间距(**原图像素**);容器瓦楞 10~20 px,
  936. C70 门板 63~185 px。``None``/``<=0`` 表示不可用(不因此拒绝)。
  937. ``below_roi_h_px``:箱底以下动态 ROI 的高度(**原图像素**),用于
  938. ``min_bed_roi_px`` 门 —— 与 C++ ``classify()`` 同口径。
  939. 本函数与 ``cpp/src/edge_v2.cpp`` 的 ``EdgeV2::classify()`` **逐条同构**:
  940. ``post_array_regular`` / ``relaxed_post_array`` / ``prefer_bed_on_conflict``
  941. / ``bed_roi_ok`` 都在这边实现,否则"Python 调好的参数搬到 C++ 结论会变"。
  942. """
  943. if view == ViewMode.UNKNOWN:
  944. return int(SceneState.UNKNOWN), 0.0, 0.0, "view_unknown"
  945. if not motion_ok:
  946. return int(SceneState.UNKNOWN), 0.0, 0.0, "motion"
  947. spacing_ok = (
  948. post_spacing_px is None
  949. or float(post_spacing_px) <= 0.0
  950. or float(post_spacing_px) >= self.p.min_post_spacing_px
  951. )
  952. # P0-Q3:门板阵列必须横跨足够宽;平车的车轮/制动梁伪立柱只在窄区。
  953. span_ok = float(post_span_ratio) >= self.p.min_post_span_ratio
  954. # P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。
  955. # 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权;
  956. # 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。
  957. contact_bed = gap_px is None or float(gap_px) <= 1.0
  958. doors_ok = (not contact_bed) or (
  959. int(diagonal_braces) >= self.p.min_diagonal_braces
  960. )
  961. # ---- 以下三条与 C++ 同口径(Python Hough 会把同一门板两侧描边算 2 根,
  962. # C++ 自定义拟合会合并成 1 根:A 稳定帧 Python 5~8 根 / C++ 4 根)。
  963. # 1) 门板阵列的间距是规则的;≥8 根且 CV>1.5 视为杂波(<8 根样本少,不看 CV)。
  964. post_array_regular = (
  965. posts < 8 or spacing_cv is None or float(spacing_cv) <= 1.5
  966. )
  967. # 2) posts = min_door_posts-1 时若侧墙不透明且间距规则,仍按门板阵列处理。
  968. relaxed_min_posts = max(1, int(self.p.min_door_posts) - 1)
  969. relaxed_post_array = (
  970. posts >= relaxed_min_posts
  971. and opacity >= 0.65
  972. and (spacing_cv is None or float(spacing_cv) <= 1.0)
  973. )
  974. posts_ok = posts >= int(self.p.min_door_posts) or relaxed_post_array
  975. # 3) 冲突(1 与 2 同时成立)时:A 的真实门板阵列可能只剩 min_posts-1 根,
  976. # 同时又误检到车面边梁 → 按"门板阵列"优先。
  977. prefer_bed_on_conflict = (
  978. posts < int(self.p.min_door_posts) and relaxed_post_array
  979. )
  980. bed_evidence = (
  981. posts_ok
  982. and posts <= int(self.p.max_door_posts)
  983. and opacity >= self.p.min_wall_opacity
  984. and post_array_regular
  985. and (gap_px is None or gap_px <= self.p.max_bed_gap_px)
  986. and (spacing_cv is None or spacing_cv <= self.p.max_post_spacing_cv)
  987. and spacing_ok
  988. and doors_ok
  989. and span_ok
  990. )
  991. # 箱底以下动态 ROI 太矮时,立柱只有 20~27 px,与地面/钢轨纹理不可区分
  992. # (B 片段实测 5~16 条伪立柱被投票成"已发布 1",真值 2)。不足门限 → 弃权。
  993. bed_roi_ok = float(below_roi_h_px) >= float(self.p.min_bed_roi_px)
  994. bed_strong = bed_evidence and bed_roi_ok
  995. # 平车:没有门板阵列 + 箱底下有可见车面边梁 + 边梁下方有"车底空隙/阴影"。
  996. # `under_deck` 是 P0-Q3 加的硬门:地面/堆场/下层箱顶只有亮面,
  997. # 找不到这条暗带 → 不判 2(宁可 255,绝不允许把地面堆料当平车)。
  998. # 地面比例只作置信度加分:B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。
  999. flat_strong = (
  1000. posts <= self.p.flat_max_door_posts
  1001. and deck
  1002. and under_deck
  1003. and (gap_px is None or gap_px <= self.p.max_flat_gap_px)
  1004. )
  1005. if bed_strong and flat_strong and not prefer_bed_on_conflict:
  1006. return int(SceneState.UNKNOWN), 0.0, 0.0, "conflict_1_2"
  1007. if bed_evidence and not bed_roi_ok and not flat_strong:
  1008. return int(SceneState.UNKNOWN), 0.0, 0.0, "bed_roi_small"
  1009. if bed_strong:
  1010. conf = 0.55 + 0.25 * min(1.0, posts / 8.0) + 0.15 * opacity
  1011. hits = min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity)
  1012. return int(SceneState.BED), min(1.0, conf), hits, "wall_posts"
  1013. if flat_strong:
  1014. conf = 0.60 + 0.20 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0)
  1015. hits = min(1.0, 0.55 + 0.15 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0))
  1016. return int(SceneState.FLATBED), min(1.0, conf), hits, "deck_edge"
  1017. if posts <= 1 and ground >= self.p.min_zero_ground_ratio and not deck:
  1018. conf = 0.55 + 0.30 * ground
  1019. hits = min(1.0, 0.50 + 0.40 * ground)
  1020. return int(SceneState.NOT_ON_TRAIN), min(1.0, conf), hits, "ground_only"
  1021. return int(SceneState.UNKNOWN), 0.0, 0.0, "weak_evidence"
  1022. # ------------------------------------------------------------ 车轮(辅助)
  1023. @staticmethod
  1024. def _wheel_count(gray: np.ndarray, roi: Tuple[int, int, int, int], scale: float) -> int:
  1025. if cv2 is None: # pragma: no cover
  1026. return 0
  1027. x0, y0, x1, y1 = roi
  1028. crop = gray[y0:y1, x0:x1]
  1029. if crop.size == 0 or min(crop.shape[:2]) < 40:
  1030. return 0
  1031. crop = cv2.medianBlur(crop, 5)
  1032. try:
  1033. circles = cv2.HoughCircles(
  1034. crop, cv2.HOUGH_GRADIENT, dp=1.2,
  1035. minDist=max(20, int(36 * scale)),
  1036. param1=100, param2=26,
  1037. minRadius=max(7, int(12 * scale)), maxRadius=max(20, int(60 * scale)),
  1038. )
  1039. except cv2.error: # pragma: no cover - 某些精简版 OpenCV
  1040. return 0
  1041. if circles is None:
  1042. return 0
  1043. return int(len(np.asarray(circles).reshape(-1, 3)))
  1044. # ------------------------------------------------------------ 车体测量
  1045. def _measure_body(self, gray: np.ndarray, roi: Tuple[int, int, int, int],
  1046. scale: float) -> Dict[str, float]:
  1047. """车体 ROI 的结构证据(与 C++ ``measure_body`` 同口径)。
  1048. 返回 ``posts`` / ``span``(立柱跨度 ÷ ROI 宽)/ ``opacity``(不透明占比)/
  1049. ``diagonal``(斜撑数)/ ``height``(原图像素高度)。
  1050. """
  1051. structure = detect_structure_v2(
  1052. gray, roi, min_post_len_ratio=self.p.min_post_len_ratio,
  1053. cluster_gap_px=9.0, scale=scale,
  1054. )
  1055. positions = structure.get("post_positions") or []
  1056. span = 0.0
  1057. if len(positions) >= 2:
  1058. span = (max(positions) - min(positions)) / max(1.0, float(roi[2] - roi[0]))
  1059. ground, blocks = ground_like_ratio(
  1060. gray, roi, structure.get("lines", []), # type: ignore[arg-type]
  1061. block_px=self.p.ground_block_px,
  1062. density_lo=self.p.ground_density_lo,
  1063. density_hi=self.p.ground_density_hi,
  1064. )
  1065. opacity = 1.0 - ground if blocks > 0 else 0.0
  1066. return {
  1067. "posts": int(structure["post_count"]),
  1068. "span": float(span),
  1069. "opacity": float(opacity),
  1070. "diagonal": int(structure["diagonal_lines"]),
  1071. "height": float(roi[3] - roi[1]) / max(scale, 1e-6),
  1072. }
  1073. # ------------------------------------------------------------ 主入口
  1074. def analyze(
  1075. self,
  1076. image: np.ndarray,
  1077. ts: float = 0.0,
  1078. frame_id: int = 0,
  1079. *,
  1080. plc_arrived: bool = False,
  1081. plc_spreader_released: bool = False,
  1082. detections: Optional[Sequence[Box]] = None,
  1083. hoist_high: Optional[bool] = None,
  1084. ) -> EvidenceV2Result:
  1085. """提取一帧证据并更新 commit 状态。
  1086. ``image`` 可以是灰度或 BGR;坐标一律按**原图**返回。
  1087. ``detections`` 是检测器本帧输出(可选);有 container 框时,用
  1088. 箱顶正上方的暗横梁判断吊具是否仍夹着箱。``hoist_high`` 仅用于
  1089. 离线回放/单测注入;生产路径由图像 + 检测框自动判定。
  1090. """
  1091. gray0 = _to_gray(image)
  1092. if gray0.size == 0:
  1093. self._last = EvidenceV2Result(
  1094. view=self.p.view, abstain_reason="no_image",
  1095. commit_reason="no_image", phase=CommitPhase.T1,
  1096. )
  1097. return self._last
  1098. h, w = gray0.shape[:2]
  1099. scale = min(1.0, float(self.p.work_width) / float(w))
  1100. if scale < 1.0:
  1101. gray = cv2.resize(gray0, (int(round(w * scale)), int(round(h * scale))),
  1102. interpolation=cv2.INTER_AREA)
  1103. else:
  1104. gray = gray0
  1105. motion_ok, motion_diff, motion_ratio = self._motion(gray)
  1106. wh, ww = gray.shape[:2]
  1107. window = (
  1108. int(self.p.window[0] * ww), int(self.p.window[1] * wh),
  1109. int(self.p.window[2] * ww), int(self.p.window[3] * wh),
  1110. )
  1111. max_h = max(6, int(self.p.band_max_h_ratio * wh))
  1112. # P0-Q4:车体顶以上(天空电线/水印)的亮/暗带不参与 box/bed 选择。
  1113. texture_top = find_texture_top(gray, window, self.p)
  1114. bright, dark = horizontal_bands(
  1115. gray, window, min_h=max(1, int(self.p.band_min_h * scale)), max_h=max_h
  1116. )
  1117. if texture_top > 0.0 and texture_top > window[1] + 0.05 * wh:
  1118. margin = self.p.texture_top_margin_ratio * wh
  1119. bright_all, dark_all = list(bright), list(dark)
  1120. bright = [b for b in bright if b.y1 >= texture_top - margin]
  1121. dark = [b for b in dark if b.y1 >= texture_top - margin]
  1122. if not bright:
  1123. bright = bright_all
  1124. if not dark:
  1125. dark = dark_all
  1126. # 先估一个箱高,用于“车体上缘搜索窗”(P0 固定 120 px 的等价物)。
  1127. box_hint = max(80.0, 0.40 * wh)
  1128. box, bed = pick_box_and_bed(
  1129. bright, dark, wh,
  1130. box_bottom_max_ratio=self.p.box_bottom_max_ratio,
  1131. bed_search_px=max(24.0, self.p.bed_search_ratio * box_hint),
  1132. )
  1133. if box is None and dark:
  1134. # 兜底:取上半幅最强的暗带(仍要求离顶部有一点距离)。
  1135. candidates = [b for b in dark if b.y0 >= 0.03 * wh and b.y1 <= 0.90 * wh]
  1136. box = max(candidates, key=lambda b: b.strength) if candidates else None
  1137. if box is None:
  1138. # P0-Q6:没有“箱底暗带”不等于判不了车型。现场目标是判「平车 / 敞车」,
  1139. # 罐箱(`04_container_on_gondola.png`)的箱底常被车帮挡住,但车体结构
  1140. # (门板立柱 + 斜撑 + 不透明侧墙)仍可见。这里退化为“只看车体”:
  1141. # 判得出 → 敞车 1(gap 记 0:箱在车斗内,不存在间隙);
  1142. # 判不出 → 仍按 `no_box` 弃权,**绝不**因此猜成平车。
  1143. if self.p.body_fallback_enable:
  1144. # ROI 用整个搜索窗口:罐箱会把 texture_top 定到车帮上沿,
  1145. # 按 texture_top 取 ROI 只剩几十像素,数不到立柱。
  1146. vy0 = max(0, int(window[1]))
  1147. vy1 = min(wh - 1, int(window[3]))
  1148. if vy1 > vy0:
  1149. vx0 = max(0, int(round(self.p.body_x_margin_ratio * ww)))
  1150. vx1 = min(ww - 1, int(round(
  1151. (1.0 - self.p.body_x_margin_ratio) * ww)))
  1152. body = self._measure_body(gray, (vx0, vy0, vx1, vy1), scale)
  1153. if (body["height"] >= self.p.body_min_roi_px
  1154. and self.p.body_min_posts <= body["posts"]
  1155. <= self.p.vehicle_max_posts
  1156. and body["span"] >= self.p.vehicle_min_span_ratio
  1157. and body["opacity"] >= self.p.body_min_opacity
  1158. and body["diagonal"] >= self.p.min_diagonal_braces):
  1159. conf = min(1.0, 0.55 + 0.25 * min(1.0, body["posts"] / 8.0)
  1160. + 0.15 * body["opacity"])
  1161. hits = min(1.0, 0.40 + 0.05 * body["posts"]
  1162. + 0.20 * body["opacity"])
  1163. commit = self.tracker.update(
  1164. ts,
  1165. state=1,
  1166. gap_m=0.0,
  1167. gap_px=0.0,
  1168. structure_hits=hits,
  1169. motion_ok=motion_ok,
  1170. view_known=self.p.view != ViewMode.UNKNOWN,
  1171. plc_arrived=plc_arrived,
  1172. plc_spreader_released=plc_spreader_released,
  1173. hoist_high=bool(hoist_high),
  1174. )
  1175. self._last = EvidenceV2Result(
  1176. state=1,
  1177. confidence=conf,
  1178. view=self.p.view,
  1179. texture_top_y=(float(texture_top) / max(scale, 1e-6)
  1180. if texture_top > 0.0 else None),
  1181. body_posts=int(body["posts"]),
  1182. body_span=float(body["span"]),
  1183. body_opacity=float(body["opacity"]),
  1184. body_diagonal=int(body["diagonal"]),
  1185. door_posts=int(body["posts"]),
  1186. diagonal_braces=int(body["diagonal"]),
  1187. wall_opacity=float(body["opacity"]),
  1188. ground_ratio=float(1.0 - body["opacity"]),
  1189. gap_px=0.0,
  1190. gap_m=0.0,
  1191. phase=(commit.phase if motion_ok else CommitPhase.T3),
  1192. committed=commit.committed,
  1193. commit_reason=commit.reason,
  1194. stable_frames=commit.stable_frames,
  1195. structure_frames=commit.structure_frames,
  1196. motion_ok=motion_ok,
  1197. hoist_high=bool(hoist_high),
  1198. diagnostics={"vehicle_only": True,
  1199. "reason": "vehicle_wall"},
  1200. )
  1201. return self._last
  1202. self._last = EvidenceV2Result(
  1203. view=self.p.view, motion_ok=motion_ok, abstain_reason="no_box",
  1204. commit_reason="no_box", phase=CommitPhase.T3 if not motion_ok else CommitPhase.T1,
  1205. diagnostics={"motion_diff": round(motion_diff, 2),
  1206. "motion_ratio": round(motion_ratio, 3)},
  1207. )
  1208. return self._last
  1209. if bed is None and bright:
  1210. below = [b for b in bright if b.y0 >= box.y1 - 1.0]
  1211. bed = min(below, key=lambda b: b.y0) if below else None
  1212. # P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/
  1213. # 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里
  1214. # `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。
  1215. est_h = max(60.0, box.y0 - 0.05 * wh)
  1216. thick_contact = False
  1217. if bed is not None and bed.y0 <= box.y1 + 1.0:
  1218. if (bed.y1 - bed.y0) > self.p.contact_max_h_ratio * est_h:
  1219. thick_contact = True
  1220. bed = None
  1221. px_per_m, vertical_run = self._scale_from_vertical(gray, box, window, scale)
  1222. box_h_px = None
  1223. if px_per_m is not None:
  1224. box_h_px = px_per_m * self.p.box_height_m
  1225. elif vertical_run is not None:
  1226. box_h_px = vertical_run / max(scale, 1e-6)
  1227. box_top = None
  1228. if box_h_px is not None:
  1229. box_top = max(0.0, box.y1 / max(scale, 1e-6) - box_h_px)
  1230. # P0-0 安全门:看箱体上沿以上有没有吊具/臂架/钢缆。没有可靠箱高时
  1231. # 用“箱底暗带往上 0.35 画幅”保守估计,宁可多弃权。
  1232. hoist_flag = False
  1233. hoist_cues: Dict[str, object] = {
  1234. "hoist_high": False, "horizontal_lines": 0, "cables": 0,
  1235. }
  1236. if hoist_high is not None:
  1237. hoist_flag = bool(hoist_high)
  1238. hoist_cues = {
  1239. "hoist_high": bool(hoist_flag),
  1240. "horizontal_lines": 0,
  1241. "cables": 0,
  1242. "injected": True,
  1243. }
  1244. elif self.p.reject_hoist_high:
  1245. # 首选:检测器 container 框 + 箱顶正上方的暗横梁。它比
  1246. # “用箱高猜箱顶”稳,因为负样本里箱高估计会被前景集装箱
  1247. # 侧壁带偏(i=668 估到 136 px,真实箱顶在 ~208 px)。
  1248. container = None
  1249. for det in detections or []:
  1250. name = str(getattr(det, "class_name", "") or "").lower()
  1251. if "container" not in name:
  1252. continue
  1253. if container is None or getattr(det, "area", 0.0) > getattr(container, "area", 0.0):
  1254. container = det
  1255. if container is not None:
  1256. contact_flag, contact_cues = detect_spreader_contact(
  1257. gray0,
  1258. (container.x1, container.y1, container.x2, container.y2),
  1259. )
  1260. line_flag, line_cues = detect_hoist_high(
  1261. gray0,
  1262. float(container.y1),
  1263. dark_max=self.p.hoist_dark_max,
  1264. band_frac=self.p.hoist_band_frac,
  1265. line_ratio=self.p.hoist_line_ratio,
  1266. dark_ratio=self.p.hoist_dark_ratio,
  1267. bright_delta=self.p.hoist_bright_delta,
  1268. )
  1269. hoist_flag = bool(contact_flag or line_flag)
  1270. hoist_cues = dict(contact_cues)
  1271. hoist_cues.update({
  1272. "source": "detector_box",
  1273. "spreader_contact": bool(contact_flag),
  1274. "horizontal_lines": int(line_cues.get("horizontal_lines", 0)),
  1275. "cables": int(line_cues.get("cables", 0)),
  1276. })
  1277. else:
  1278. probe_top = (
  1279. float(box_top)
  1280. if box_top is not None
  1281. else max(0.0, box.y0 / max(scale, 1e-6) - 0.35 * h)
  1282. )
  1283. hoist_flag, hoist_cues = detect_hoist_high(
  1284. gray0,
  1285. probe_top,
  1286. dark_max=self.p.hoist_dark_max,
  1287. band_frac=self.p.hoist_band_frac,
  1288. line_ratio=self.p.hoist_line_ratio,
  1289. dark_ratio=self.p.hoist_dark_ratio,
  1290. bright_delta=self.p.hoist_bright_delta,
  1291. )
  1292. hoist_cues = dict(hoist_cues)
  1293. hoist_cues["source"] = "image_rows"
  1294. # 动态 ROI:y 从本帧箱底下沿开始,绝不复用 P0 固定 y=475..619。
  1295. # (est_h 在"贴合亮带厚度门"处已算好,此处复用。)
  1296. # 起点要越过箱体下侧梁/车体上缘的强横线:从箱底下方约 7% 箱高开始。
  1297. # 但若箱底已经贴近画面底边,剩余高度不足以再跳过 7%,就只留 2 px
  1298. # 保护带。否则整段动态 ROI 会落到画面外,平车的车面边梁/地板线
  1299. # 完全看不到(本帧 25 px 车面 → deck=False、gap=None → 不能提交 2)。
  1300. start = max(2.0, self.p.below_start_ratio * est_h)
  1301. min_below_h = self.p.below_min_height_px * max(scale, 1e-6)
  1302. if (wh - 1) - box.y1 <= start + min_below_h:
  1303. start = 2.0
  1304. y0w = min(
  1305. wh - 2,
  1306. int(math.ceil(box.y1 + start)),
  1307. )
  1308. below_h = max(
  1309. min_below_h,
  1310. min(self.p.below_height_ratio * est_h, 0.30 * wh),
  1311. )
  1312. y1w = min(wh - 1, max(y0w + below_h, box.y1 + 0.10 * est_h))
  1313. x0w = max(0, int(0.05 * ww))
  1314. x1w = min(ww - 1, int(0.95 * ww))
  1315. below_work = (x0w, y0w, x1w, max(y0w + 8, int(y1w)))
  1316. structure = detect_structure_v2(
  1317. gray, below_work,
  1318. min_post_len_ratio=self.p.min_post_len_ratio,
  1319. cluster_gap_px=9.0, scale=scale,
  1320. )
  1321. posts = int(structure["post_count"])
  1322. spacing_median = structure["post_spacing_median"]
  1323. spacing_cv = structure["post_spacing_cv"]
  1324. edge_density = float(structure["edge_density"])
  1325. ground, ground_blocks = ground_like_ratio(
  1326. gray, below_work, structure.get("lines", []), # type: ignore[arg-type]
  1327. block_px=self.p.ground_block_px,
  1328. density_lo=self.p.ground_density_lo,
  1329. density_hi=self.p.ground_density_hi,
  1330. )
  1331. if ground_blocks > 0:
  1332. opacity = max(0.0, min(1.0, 1.0 - ground))
  1333. else:
  1334. span = max(1e-6, float(self.p.wall_edge_density_span))
  1335. opacity = max(0.0, min(1.0, (self.p.wall_edge_density_ref - edge_density) / span))
  1336. ground = max(0.0, min(1.0, 1.0 - opacity))
  1337. # 与 C++ `flat_contact` 同口径:侧视平车的箱底与车面直接贴合时,车面边梁
  1338. # 落在动态 ROI 之外(Hough 水平线通道看不到它:实拍图 deck=False、gap 被
  1339. # 错取成 62.9 px → weak_evidence)。这里补一条"贴合薄亮边"证据:
  1340. # 箱底下沿紧邻(±1 px)的亮带,高度 >= 1.5% 画幅(至少 4 px),且不超过
  1341. # `contact_max_h_ratio`×估箱高(排除地面 / 下层箱顶 / 月台等厚亮面)。
  1342. # 命中后把这条亮边当作车面(bed),gap 归 0。
  1343. min_contact_h = max(4.0, 0.015 * wh)
  1344. contact_band: Optional[Band] = None
  1345. for band in bright:
  1346. if not (box.y1 - 1.0 <= band.y0 < box.y1 + 1.0):
  1347. continue
  1348. height = band.y1 - band.y0
  1349. if height >= min_contact_h and (
  1350. contact_band is None
  1351. or height > (contact_band.y1 - contact_band.y0)
  1352. ):
  1353. contact_band = band
  1354. if (contact_band is not None
  1355. and (contact_band.y1 - contact_band.y0)
  1356. > self.p.contact_max_h_ratio * est_h):
  1357. contact_band = None
  1358. flat_contact = (
  1359. not thick_contact
  1360. and contact_band is not None
  1361. and posts <= int(self.p.flat_max_door_posts)
  1362. and opacity >= self.p.min_wall_opacity
  1363. and ground < self.p.min_zero_ground_ratio
  1364. )
  1365. if flat_contact:
  1366. bed = contact_band
  1367. below_h_work = max(1.0, below_work[3] - below_work[1])
  1368. deck_min_len = max(20.0, self.p.deck_min_len_ratio * 0.55 * ww)
  1369. deck_edge = bool(flat_contact) or any(
  1370. box.y1 - 2.0 <= float(seg["y"]) <= box.y1 + 0.35 * below_h_work
  1371. and float(seg["length"]) >= deck_min_len
  1372. for seg in structure.get("horizontal", []) # type: ignore[union-attr]
  1373. )
  1374. wheels = self._wheel_count(gray, below_work, scale)
  1375. # P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。
  1376. # 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。
  1377. # 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。
  1378. under_deck = False
  1379. if bed is not None and (bed.y1 - bed.y0) > 0.0:
  1380. band_mean = _row_mean(gray, window[0], window[2], bed.y0, bed.y1)
  1381. probe_h = max(2, int(round(self.p.under_deck_min_h_ratio * wh)))
  1382. search_h = max(probe_h + 1, int(round(self.p.under_deck_search_h_ratio * wh)))
  1383. probe_y0 = max(0, int(round(bed.y1)))
  1384. probe_y1 = min(wh - 1, probe_y0 + search_h)
  1385. darkest = None
  1386. for y in range(probe_y0, max(probe_y0 + 1, probe_y1 - probe_h + 1)):
  1387. value = _row_mean(gray, window[0], window[2], y, y + probe_h)
  1388. if darkest is None or value < darkest:
  1389. darkest = value
  1390. under_deck = (
  1391. darkest is not None
  1392. and darkest <= band_mean - self.p.under_deck_dark_delta
  1393. )
  1394. deck_edge = bool(deck_edge and under_deck)
  1395. positions = structure.get("post_positions") or []
  1396. post_span_ratio = 0.0
  1397. if len(positions) >= 2:
  1398. post_span_ratio = (max(positions) - min(positions)) / max(1.0, float(ww))
  1399. gap_px = None
  1400. if bed is not None:
  1401. gap_px = max(0.0, (bed.y0 - box.y1) / max(scale, 1e-6))
  1402. state, conf, hits, reason = self._classify(
  1403. posts=posts,
  1404. spacing_cv=spacing_cv,
  1405. opacity=opacity,
  1406. ground=ground,
  1407. deck=deck_edge,
  1408. wheels=wheels,
  1409. gap_px=gap_px,
  1410. motion_ok=motion_ok,
  1411. view=self.p.view,
  1412. under_deck=under_deck,
  1413. post_spacing_px=(
  1414. None if spacing_median is None
  1415. else float(spacing_median) / max(scale, 1e-6)
  1416. ),
  1417. diagonal_braces=int(structure["diagonal_lines"]),
  1418. post_span_ratio=float(post_span_ratio),
  1419. below_roi_h_px=float(below_h_work) / max(scale, 1e-6),
  1420. )
  1421. body = None
  1422. body_stats = None
  1423. body_roi = None
  1424. # P0-Q6:空车/无箱兜底。旧条件还要求“纹理车体顶明显低于窗口顶”(有天空),
  1425. # 于是“车把画面填满”的空敞车(`02_C70E_shigure03.jpg`,texture_top≈窗口顶)
  1426. # 永远进不来,只能弃权。现在只要找到车体顶就试一次;真正的守门是
  1427. # posts ∈ [body_min_posts, max_door_posts] —— 集装箱侧壁波纹(实测 18~31 根)
  1428. # 会被上限挡掉,不会被误判成门板阵列。
  1429. if self.p.body_fallback_enable and texture_top > 0.0 and state != 1:
  1430. by0 = max(int(window[1]), int(round(texture_top)))
  1431. by1 = min(int(window[3]), int(round(
  1432. texture_top + self.p.body_bottom_ratio * (window[3] - texture_top))))
  1433. if by1 > by0:
  1434. bx0 = max(0, int(round(self.p.body_x_margin_ratio * ww)))
  1435. bx1 = min(ww - 1, int(round((1.0 - self.p.body_x_margin_ratio) * ww)))
  1436. body_roi = (bx0, by0, bx1, by1)
  1437. b = self._measure_body(gray, body_roi, scale)
  1438. body_stats = {
  1439. "posts": int(b["posts"]),
  1440. "diagonal": int(b["diagonal"]),
  1441. "opacity": float(b["opacity"]),
  1442. }
  1443. if (b["height"] >= self.p.body_min_roi_px
  1444. and self.p.body_min_posts <= b["posts"] <= self.p.max_door_posts
  1445. and b["span"] >= self.p.min_post_span_ratio
  1446. and b["opacity"] >= self.p.body_min_opacity
  1447. and b["diagonal"] >= self.p.min_diagonal_braces):
  1448. # P0-Q7(2026-11-19 客户口径):**空车(无箱)一律弃权**,不判 1/2。
  1449. # 车体结构说明"这是敞车",但车上没有箱;给 1 会被 PLC 理解成
  1450. # "箱已在车斗内、可以作业",属于危险输出。与
  1451. # `ambiguous_empty_vehicle` 同口径(02/03 两张空车图必须一致)。
  1452. state = 255
  1453. conf = 0.0
  1454. hits = 0.0
  1455. reason = "ambiguous_empty_vehicle"
  1456. gap_px = 0.0
  1457. body = body_stats
  1458. gap_m = (
  1459. None if gap_px is None or px_per_m is None or px_per_m <= 0.0
  1460. else gap_px / px_per_m
  1461. )
  1462. if body is not None:
  1463. gap_m = 0.0
  1464. if (body is None and texture_top > 0.0 and state == 2 and posts == 0
  1465. and box.y1 > texture_top + 0.02 * wh
  1466. and (body_stats is None
  1467. or body_stats["posts"] <= self.p.max_door_posts)):
  1468. state = 255
  1469. conf = 0.0
  1470. hits = 0.0
  1471. reason = "ambiguous_empty_vehicle"
  1472. commit = self.tracker.update(
  1473. ts,
  1474. state=state,
  1475. gap_m=gap_m,
  1476. gap_px=gap_px,
  1477. structure_hits=hits,
  1478. motion_ok=motion_ok,
  1479. view_known=self.p.view != ViewMode.UNKNOWN,
  1480. plc_arrived=plc_arrived,
  1481. plc_spreader_released=plc_spreader_released,
  1482. hoist_high=hoist_flag,
  1483. )
  1484. phase = CommitPhase.T3 if not motion_ok else CommitPhase(commit.phase)
  1485. result = EvidenceV2Result(
  1486. state=int(state),
  1487. confidence=float(conf),
  1488. view=self.p.view,
  1489. box_bottom_y=box.y1 / max(scale, 1e-6),
  1490. box_top_y=box_top,
  1491. texture_top_y=(
  1492. None if texture_top <= 0.0 else texture_top / max(scale, 1e-6)
  1493. ),
  1494. box_h_px=box_h_px,
  1495. px_per_m=px_per_m,
  1496. scale_ok=px_per_m is not None,
  1497. bed_top_y=None if bed is None else bed.y0 / max(scale, 1e-6),
  1498. gap_px=gap_px,
  1499. gap_m=gap_m,
  1500. door_posts=(body["posts"] if body else posts),
  1501. post_spacing_px=(
  1502. None if spacing_median is None else float(spacing_median) / max(scale, 1e-6)
  1503. ),
  1504. post_spacing_cv=None if spacing_cv is None else float(spacing_cv),
  1505. rect_doors=int(structure["rect_doors"]),
  1506. diagonal_braces=(body["diagonal"] if body else int(structure["diagonal_lines"])),
  1507. wall_opacity=(body["opacity"] if body else opacity),
  1508. deck_edge=bool(deck_edge) and body is None,
  1509. under_deck=bool(under_deck) and body is None,
  1510. wheel_count=int(wheels),
  1511. ground_ratio=(1.0 - body["opacity"]) if body else ground,
  1512. phase=phase,
  1513. committed=bool(commit.committed),
  1514. commit_reason=commit.reason,
  1515. stable_frames=int(commit.stable_frames),
  1516. structure_frames=int(commit.structure_frames),
  1517. motion_ok=bool(motion_ok),
  1518. hoist_high=bool(hoist_flag),
  1519. abstain_reason=(
  1520. "hoist_high" if hoist_flag and state in (0, 1, 2)
  1521. else ("" if state in (0, 1, 2) else reason)
  1522. ),
  1523. below_roi=(
  1524. (int(round(body_roi[0] / scale)), int(round(body_roi[1] / scale)),
  1525. int(round(body_roi[2] / scale)), int(round(body_roi[3] / scale)))
  1526. if body else
  1527. (int(round(below_work[0] / scale)), int(round(below_work[1] / scale)),
  1528. int(round(below_work[2] / scale)), int(round(below_work[3] / scale)))
  1529. ),
  1530. diagnostics={
  1531. "class_reason": reason,
  1532. "texture_top": None if texture_top <= 0.0 else round(texture_top / scale, 2),
  1533. "body_fallback": bool(body),
  1534. "box_band": [round(box.y0 / scale, 2), round(box.y1 / scale, 2)],
  1535. "bed_band": None if bed is None else [round(bed.y0 / scale, 2), round(bed.y1 / scale, 2)],
  1536. "under_deck": bool(under_deck),
  1537. "thick_contact": bool(thick_contact),
  1538. "vertical_run_px": None if vertical_run is None else round(vertical_run / scale, 2),
  1539. "motion_diff": round(motion_diff, 2),
  1540. "motion_ratio": round(motion_ratio, 3),
  1541. "edge_density": round(edge_density, 4),
  1542. "ground_blocks": int(ground_blocks),
  1543. "vertical_lines": int(structure["vertical_lines"]),
  1544. "horizontal_lines": int(structure["horizontal_lines"]),
  1545. "hoist_cues": dict(hoist_cues),
  1546. "scale": round(scale, 4),
  1547. },
  1548. )
  1549. self._last = result
  1550. return result
  1551. def classify(self, image: np.ndarray, ts: float = 0.0, frame_id: int = 0,
  1552. **kwargs) -> Observation:
  1553. """``analyze`` + ``to_observation`` 的便捷入口(pipeline 使用)。"""
  1554. result = self.analyze(image, ts=ts, frame_id=frame_id, **kwargs)
  1555. return result.to_observation(
  1556. ts=ts, frame_id=frame_id, require_commit=self.p.require_commit
  1557. )