evidence_v2.py 86 KB

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