evidence_v2.py 68 KB

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