evidence_v2.py 55 KB

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