evidence_v2.py 96 KB

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