evidence_v2.py 64 KB

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