evidence_v2.py 75 KB

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