test_evidence_v2.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. """P1b evidence_v2 合成场景测试。
  2. 不依赖现场素材:用确定性灰度图构造“敞车侧墙门板”与“平车车面边梁”,
  3. 断言分类、动态 ROI、commit 门与 Observation 映射。A/B 真帧回放由
  4. ``scripts/replay_evidence_v2.py`` 负责(素材不在仓库时跳过)。
  5. """
  6. from __future__ import annotations
  7. import os
  8. import unittest
  9. import cv2
  10. import numpy as np
  11. from portcv.config import Config, load_config
  12. from portcv.detect import resolve_backend
  13. from portcv.io.capture import Frame
  14. from portcv.logic.commit import CommitParams, CommitTracker
  15. from portcv.logic.evidence_v2 import (
  16. Band,
  17. EvidenceV2,
  18. EvidenceV2Params,
  19. find_texture_top,
  20. pick_box_and_bed,
  21. )
  22. from portcv.service.pipeline import VisionPipeline
  23. def bed_scene(*, gap_px: int = 18, box_bottom: int = 392) -> np.ndarray:
  24. """C70 类:箱底暗带 + 间隙 + 亮墙顶 + 门板立柱/斜撑。"""
  25. h, w = 720, 1280
  26. image = np.full((h, w), 120, dtype=np.uint8)
  27. image[40:box_bottom, :] = 185
  28. # 箱体竖波纹(真实集装箱有;也让 P0-Q4 顶部纹理门不把箱顶误当天空)
  29. for x in range(60, 1240, 48):
  30. image[50:box_bottom - 4, x:x + 3] = 176
  31. image[box_bottom:box_bottom + 12, :] = 55
  32. # gap_px 是“箱底下沿(暗带下沿)→ 墙顶亮带”的物理间隙。
  33. wall_top = box_bottom + 12 + gap_px
  34. image[box_bottom + 12:wall_top, :] = 88
  35. image[wall_top:wall_top + 4, :] = 215
  36. image[wall_top + 4:h, :] = 125
  37. for x in range(120, 1180, 110):
  38. image[wall_top + 20:min(h - 20, wall_top + 230), x:x + 5] = 55
  39. for x in range(150, 1050, 220):
  40. cv2.line(image, (x, wall_top + 30), (x + 120, wall_top + 220), 70, 4)
  41. # 门板横梁:让分块“地面样”统计看到结构面,而不是把灰墙当空地。
  42. for dy in range(30, 240, 20):
  43. y = min(h - 8, wall_top + dy)
  44. image[y:y + 2, 60:1220] = 85
  45. return image
  46. def flat_scene(*, gap_px: int = 4) -> np.ndarray:
  47. """X70 类:箱底暗带 + 薄车面边梁 + 车面/地面,无门板阵列。"""
  48. h, w = 720, 1280
  49. image = np.full((h, w), 120, dtype=np.uint8)
  50. image[40:392, :] = 185
  51. for x in range(60, 1240, 48):
  52. image[50:388, x:x + 3] = 176
  53. image[392:404, :] = 55
  54. deck_top = 404 + gap_px
  55. image[deck_top:deck_top + 5, :] = 225
  56. image[deck_top + 5:520, :] = 145
  57. # 车面横向边梁(动态 ROI 内的一条长直线)
  58. cv2.line(image, (40, deck_top + 24), (1240, deck_top + 24), 70, 5)
  59. rng = np.random.default_rng(20261019)
  60. ground = rng.integers(70, 190, size=(200, w), dtype=np.uint8)
  61. image[520:720, :] = ground
  62. return image
  63. def flat_contact_scene() -> np.ndarray:
  64. """侧视近距:箱体几乎占满画面,箱底与平车车面直接贴合。
  65. 对应实拍 746×192 近景:箱底暗带只有 3 px(y=167..170),下方是
  66. 10 px 车面亮带,再往下是车底/地面。旧版峰值检测会把 3 px 薄带
  67. 压掉,导致 ``no_box``;本场景用于锁住该回归。
  68. """
  69. h, w = 192, 746
  70. image = np.full((h, w), 180, dtype=np.uint8)
  71. image[10:167, :] = 185 # 箱体
  72. image[167:170, :] = 55 # 箱底暗带(仅 3 px)
  73. image[170:179, :] = 145 # 平车车面亮带(与箱底贴合)
  74. image[179:188, :] = 30 # 车底暗部
  75. image[188:h, :] = 80 # 地面
  76. image[173:175, 40:700] = 110 # 车面横向边梁(deck edge)
  77. for x in range(40, w, 40): # 箱体竖棱;不改变行均值
  78. image[20:160, x:x + 2] = 165
  79. return image
  80. def make(params: EvidenceV2Params, tracker: CommitTracker | None = None) -> EvidenceV2:
  81. return EvidenceV2(params, tracker)
  82. def ground_scene(*, low: int = 95, high: int = 115, noise: int = 4) -> np.ndarray:
  83. """箱直接坐地:箱底以下是低对比、连续的地面(水泥地/砂石)。
  84. P0-Q3 回归用:这种画面**绝不能**被判成 2(平车)或 1(敞车)。
  85. """
  86. h, w = 720, 1280
  87. image = np.full((h, w), 120, dtype=np.uint8)
  88. image[40:392, :] = 185
  89. for x in range(60, 1240, 48):
  90. image[50:388, x:x + 3] = 176
  91. image[392:404, :] = 55 # 箱底暗带
  92. rng = np.random.default_rng(20261118)
  93. ramp = np.linspace(low, high, h - 404).reshape(-1, 1)
  94. jitter = rng.integers(-noise, noise + 1, size=(h - 404, w))
  95. image[404:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8)
  96. return image
  97. def thick_contact_scene() -> np.ndarray:
  98. """箱底紧贴一块**厚亮面**(地面/下层箱顶/月台),下方仍是地面。
  99. 旧版 C++ `flat_contact` 会把这块厚亮面当车面 → 2;本用例锁住该回归。
  100. """
  101. image = ground_scene()
  102. image[404:450, :] = 165 # 46 px 厚亮面(估箱高 ≈356 px → 0.13 > 0.12)
  103. return image
  104. def stacked_scene() -> np.ndarray:
  105. """上层箱坐在下层箱上:下层箱顶亮面 + 侧壁瓦楞(无斜撑)。
  106. 旧版会把瓦楞当门板立柱、把箱顶亮面当车面 → 1;本用例要求 0/255。
  107. """
  108. image = ground_scene()
  109. image[404:450, :] = 165 # 下层箱顶面
  110. image[450:, :] = 140 # 下层箱侧壁
  111. for x in range(60, 1280, 118): # 瓦楞竖棱(≈10 根)
  112. image[450:700, x:x + 6] = 95
  113. return image
  114. class BandSelectionTests(unittest.TestCase):
  115. def test_pick_box_and_bed_uses_nearest_bright_below(self):
  116. box, bed = pick_box_and_bed(
  117. [Band(430, 438, 100), Band(500, 510, 90)],
  118. [Band(407, 419, 100)],
  119. 720,
  120. )
  121. self.assertIsNotNone(box)
  122. self.assertIsNotNone(bed)
  123. self.assertEqual((box.y0, box.y1), (407, 419))
  124. self.assertEqual((bed.y0, bed.y1), (430, 438))
  125. def test_no_dark_band_returns_none(self):
  126. box, bed = pick_box_and_bed([], [], 720)
  127. self.assertIsNone(box)
  128. self.assertIsNone(bed)
  129. class EvidenceClassificationTests(unittest.TestCase):
  130. def test_a_like_wall_is_state1(self):
  131. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  132. result = ev.analyze(bed_scene(), ts=0.0)
  133. self.assertEqual(result.state, 1, result.to_dict())
  134. self.assertGreaterEqual(result.door_posts, 5)
  135. self.assertGreaterEqual(result.wall_opacity, 0.35)
  136. self.assertIsNotNone(result.gap_px)
  137. self.assertGreater(result.gap_px, 8.0)
  138. def test_b_like_deck_is_state2(self):
  139. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  140. result = ev.analyze(flat_scene(), ts=0.0)
  141. self.assertEqual(result.state, 2, result.to_dict())
  142. self.assertLessEqual(result.door_posts, 4)
  143. self.assertTrue(result.deck_edge)
  144. def test_nearly_full_frame_flatbed_contact_is_state2(self):
  145. # 箱底落在 0.885*h(超过 box_bottom_max_ratio=0.78),且箱底下沿
  146. # 与车面亮带贴合(gap=0)。必须仍能识别为 2,并在 5 帧后提交。
  147. tracker = CommitTracker(
  148. CommitParams(
  149. stable_frames=5, structure_frames=5,
  150. gap_px_hard_max=8.0, allow_state2=True,
  151. )
  152. )
  153. ev = make(
  154. EvidenceV2Params(px_per_m=100.0, require_commit=True),
  155. tracker,
  156. )
  157. image = flat_contact_scene()
  158. results = [ev.analyze(image, ts=i / 15.0, frame_id=i) for i in range(5)]
  159. first = results[0]
  160. self.assertEqual(first.state, 2, first.to_dict())
  161. self.assertLessEqual(first.door_posts, 4)
  162. self.assertTrue(first.deck_edge)
  163. self.assertAlmostEqual(
  164. -1.0 if first.gap_px is None else first.gap_px, 0.0, places=3
  165. )
  166. self.assertFalse(first.committed)
  167. self.assertEqual(
  168. first.to_observation(require_commit=True).state, 255,
  169. "commit 未满 5 帧时内部应保持 255",
  170. )
  171. self.assertTrue(results[-1].committed, results[-1].to_dict())
  172. self.assertEqual(
  173. results[-1].to_observation(require_commit=True).state, 2
  174. )
  175. def test_empty_image_is_unknown(self):
  176. ev = make(EvidenceV2Params(require_commit=False))
  177. result = ev.analyze(np.zeros((0, 0), dtype=np.uint8))
  178. self.assertEqual(result.state, 255)
  179. self.assertEqual(result.abstain_reason, "no_image")
  180. def test_blank_image_abstains(self):
  181. ev = make(EvidenceV2Params(require_commit=False))
  182. result = ev.analyze(np.full((720, 1280), 128, dtype=np.uint8))
  183. self.assertEqual(result.state, 255)
  184. self.assertTrue(result.abstain_reason)
  185. def test_dynamic_roi_follows_box_bottom(self):
  186. low = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  187. high = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  188. r_low = low.analyze(bed_scene(box_bottom=392), ts=0.0)
  189. r_high = high.analyze(bed_scene(box_bottom=520), ts=0.0)
  190. self.assertGreater(r_low.below_roi[1], 392)
  191. self.assertGreater(r_high.below_roi[1], 520)
  192. self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1])
  193. def sky_wire_scene() -> np.ndarray:
  194. """P0-Q4:天空电线 + 空 C70 车体(512×512,无下采样)。"""
  195. h = w = 512
  196. image = np.full((h, w), 200, dtype=np.uint8)
  197. for y in (20, 52, 84, 116):
  198. image[y:y + 2, :] = 30
  199. image[165:405, :] = 95
  200. for x in range(30, 480, 18):
  201. image[175:400, x:x + 5] = 45
  202. for x in range(30, 480, 50):
  203. cv2.rectangle(image, (x, 185), (x + 40, 380), 60, 3)
  204. image[188:377, x + 3:x + 37] = 110
  205. for dy in range(5, 235, 8):
  206. y = 165 + dy
  207. image[y:y + 2, 20:492] = 80
  208. for x in range(40, 470, 70):
  209. cv2.line(image, (x, 190), (x + 80, 330), 30, 7)
  210. image[405:, :] = 140
  211. return image
  212. class TextureTopTests(unittest.TestCase):
  213. """P0-Q4:天空电线不能把“车体顶”骗到天上。"""
  214. def test_sky_wires_are_above_vehicle_top(self):
  215. image = sky_wire_scene()
  216. window = (int(0.24 * 512), int(0.02 * 512), int(0.78 * 512), int(0.95 * 512))
  217. top = find_texture_top(image, window, EvidenceV2Params())
  218. self.assertGreater(top, 120, "车体顶应落在电线以下")
  219. self.assertLess(top, 220, "车体顶不应落到车体中部")
  220. def test_empty_c70_body_fallback_abstains(self):
  221. # P0-Q7(2026-11-19 客户口径):空车(无箱)一律 255,不判 1/2。
  222. # 与 `02_C70E`/`03_C70EA` 两张空车图一致;给 1 会被 PLC 当成
  223. # “箱已在车斗内、可以作业”,属危险输出。
  224. ev = EvidenceV2(EvidenceV2Params(require_commit=False))
  225. result = ev.analyze(sky_wire_scene(), ts=0.0)
  226. self.assertEqual(result.state, 255, result.to_dict())
  227. self.assertGreater(result.texture_top_y or 0.0, 120.0)
  228. self.assertEqual(result.abstain_reason, "ambiguous_empty_vehicle",
  229. result.to_dict())
  230. def test_plain_sky_has_no_vehicle_top(self):
  231. image = np.full((720, 1280), 200, dtype=np.uint8)
  232. for y in (40, 90, 140):
  233. image[y:y + 2, :] = 30
  234. window = (int(0.24 * 1280), int(0.02 * 720), int(0.78 * 1280), int(0.95 * 720))
  235. self.assertLess(find_texture_top(image, window, EvidenceV2Params()), 0)
  236. class GroundStackSafetyTests(unittest.TestCase):
  237. """P0-Q3:地面/堆料/堆叠箱不得被判成 1(敞车)或 2(平车)。"""
  238. def _classify(self, image: np.ndarray):
  239. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  240. return ev.analyze(image, ts=0.0)
  241. def test_box_on_ground_is_never_bed_or_flatbed(self):
  242. result = self._classify(ground_scene())
  243. self.assertNotIn(result.state, (1, 2), result.to_dict())
  244. def test_thick_contact_plane_is_not_flatbed(self):
  245. # 箱底紧贴一块厚亮面(地面/下层箱顶/月台)→ 旧版 flat_contact 会判 2
  246. result = self._classify(thick_contact_scene())
  247. self.assertNotIn(result.state, (1, 2), result.to_dict())
  248. self.assertFalse(result.deck_edge, result.to_dict())
  249. def test_container_stacked_on_container_is_not_bed(self):
  250. # 下层箱的瓦楞不是车斗门板;下层箱顶也不是车面
  251. result = self._classify(stacked_scene())
  252. self.assertNotIn(result.state, (1, 2), result.to_dict())
  253. class CommitIntegrationTests(unittest.TestCase):
  254. def test_uncommitted_result_maps_to_internal_255(self):
  255. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=True))
  256. result = ev.analyze(bed_scene(gap_px=18), ts=0.0)
  257. self.assertEqual(result.state, 1)
  258. self.assertFalse(result.committed)
  259. obs = result.to_observation(require_commit=True)
  260. self.assertEqual(obs.state, 255)
  261. self.assertEqual(obs.confidence, 0.0)
  262. self.assertIn("abstain", obs.reason)
  263. def test_seated_frames_commit_and_publish_state1(self):
  264. tracker = CommitTracker(
  265. CommitParams(
  266. stable_frames=3, structure_frames=3,
  267. gap_px_hard_max=8.0, allow_state2=False,
  268. )
  269. )
  270. ev = make(
  271. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  272. tracker,
  273. )
  274. image = bed_scene(gap_px=4)
  275. last = None
  276. for i in range(4):
  277. last = ev.analyze(image, ts=i / 30.0)
  278. self.assertIsNotNone(last)
  279. self.assertTrue(last.committed, last.to_dict())
  280. obs = last.to_observation(ts=0.2, require_commit=True)
  281. self.assertEqual(obs.state, 1)
  282. self.assertGreater(obs.confidence, 0.45)
  283. def test_injected_hoist_high_blocks_commit(self):
  284. tracker = CommitTracker(
  285. CommitParams(
  286. stable_frames=3, structure_frames=3,
  287. gap_px_hard_max=8.0, allow_state2=False,
  288. )
  289. )
  290. ev = make(
  291. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  292. tracker,
  293. )
  294. image = bed_scene(gap_px=4)
  295. last = None
  296. for i in range(6):
  297. last = ev.analyze(image, ts=i / 30.0, hoist_high=True)
  298. self.assertIsNotNone(last)
  299. self.assertTrue(last.hoist_high)
  300. self.assertFalse(last.committed)
  301. self.assertEqual(last.commit_reason, "hoist_high")
  302. self.assertEqual(last.abstain_reason, "hoist_high")
  303. obs = last.to_observation(require_commit=True)
  304. self.assertEqual(obs.state, 255)
  305. self.assertIn("hoist_high", obs.reason)
  306. def test_detect_hoist_high_finds_dark_bar_with_bright_sky_below(self):
  307. from portcv.logic.evidence_v2 import detect_hoist_high
  308. image = np.full((720, 1280), 185, dtype=np.uint8)
  309. image[40:140, :] = 25 # 上方吊具/臂架暗带
  310. image[140:300, :] = 185 # 暗带下方天空/箱顶更亮
  311. hoist, cues = detect_hoist_high(image, 300)
  312. self.assertTrue(hoist, cues)
  313. self.assertGreaterEqual(cues["horizontal_lines"], 1)
  314. def test_detect_hoist_high_ignores_uniform_scene(self):
  315. from portcv.logic.evidence_v2 import detect_hoist_high
  316. image = np.full((720, 1280), 150, dtype=np.uint8)
  317. hoist, cues = detect_hoist_high(image, 300)
  318. self.assertFalse(hoist, cues)
  319. self.assertEqual(cues["horizontal_lines"], 0)
  320. def test_spreader_contact_detects_dark_bar_on_container_top(self):
  321. from portcv.logic.evidence_v2 import detect_spreader_contact
  322. image = np.full((500, 600), 180, dtype=np.uint8)
  323. image[100:140, 100:500] = 30 # 吊具横梁紧贴箱顶
  324. image[140:450, 100:500] = 150 # 箱体
  325. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  326. self.assertTrue(hit, cues)
  327. self.assertGreaterEqual(cues["dark_run_px"], 20)
  328. def test_spreader_contact_ignores_plain_container_top(self):
  329. from portcv.logic.evidence_v2 import detect_spreader_contact
  330. image = np.full((500, 600), 180, dtype=np.uint8)
  331. image[140:450, 100:500] = 150
  332. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  333. self.assertFalse(hit, cues)
  334. def test_classify_only_mode_publishes_candidate(self):
  335. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  336. obs = ev.classify(bed_scene(), ts=0.0, frame_id=1)
  337. self.assertEqual(obs.state, 1)
  338. self.assertGreater(obs.confidence, 0.45)
  339. class VehicleOnlyTests(unittest.TestCase):
  340. """箱底被车帮挡住(罐箱)时“只看车体”判敞车(P0-Q6)。
  341. 现场来源:`04_container_on_gondola.png`(MLGU 350584 罐箱坐在敞车上,
  342. 箱底被车帮完全挡住)——旧实现直接 `no_box` 弃权,用户要求“罐箱也要输出”。
  343. C++/Python 判据都是**立柱跨度**(敞车横跨整车 ≥`vehicle_min_span_ratio`,
  344. 平车上集装箱波纹只占中间一段)。
  345. 注意:**正向用例只能靠现场帧**(`docs/evidence/` 的 4 张图 + A/B 片段),
  346. 合成图的大片均匀区会被 `ground_like_ratio` 判成“地面”,`opacity` 上不去,
  347. 测不出“检测得到”这件事;这里只锁“没有车体结构时必须弃权、不许猜”。
  348. """
  349. @staticmethod
  350. def _no_bands():
  351. from unittest import mock
  352. return mock.patch(
  353. "portcv.logic.evidence_v2.horizontal_bands",
  354. return_value=([], []),
  355. )
  356. def test_no_box_without_wall_abstains(self):
  357. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  358. blank = np.full((720, 1280), 120, dtype=np.uint8)
  359. with self._no_bands():
  360. obs = ev.classify(blank, ts=0.0, frame_id=1)
  361. self.assertEqual(obs.state, 255, obs.reason)
  362. self.assertIn("no_box", obs.reason)
  363. def test_no_box_never_guesses_flatbed(self):
  364. # 无箱底时只可能给 1 或弃权;**不许**因为“看不清”给平车 2。
  365. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  366. blank = np.full((720, 1280), 120, dtype=np.uint8)
  367. with self._no_bands():
  368. obs = ev.classify(blank, ts=0.0, frame_id=1)
  369. self.assertNotEqual(obs.state, 2, obs.reason)
  370. class PipelineAndConfigTests(unittest.TestCase):
  371. def test_pipeline_uses_evidence_v2_when_enabled(self):
  372. cfg = Config(
  373. {
  374. "run": {"backend": "mock"},
  375. "evidence_v2": {
  376. "enabled": True,
  377. "px_per_m": 115.6,
  378. "require_commit": False,
  379. },
  380. }
  381. )
  382. pipeline = VisionPipeline(cfg)
  383. self.assertIsNotNone(pipeline.evidence_v2)
  384. observation, _decision = pipeline.step(
  385. Frame(bed_scene(), ts=0.0, frame_id=1)
  386. )
  387. self.assertEqual(observation.state, 1, observation.reason)
  388. def test_pipeline_keeps_legacy_path_by_default(self):
  389. cfg = Config({"run": {"backend": "mock"}})
  390. pipeline = VisionPipeline(cfg)
  391. self.assertIsNone(pipeline.evidence_v2)
  392. def test_site_template_loads_and_backend_alias_resolves(self):
  393. path = os.path.join(
  394. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  395. "configs", "edge-v2-front.json",
  396. )
  397. cfg = load_config(path)
  398. self.assertTrue(bool(cfg.get_path("evidence_v2.enabled")))
  399. self.assertTrue(bool(cfg.get_path("evidence_v2.allow_state2")))
  400. self.assertTrue(bool(cfg.get_path("evidence_v2.commit.allow_state2")))
  401. self.assertEqual(resolve_backend(cfg.get_path("run.backend")), "mock")
  402. class ClassifyParityTests(unittest.TestCase):
  403. """Python ``_classify`` 与 C++ ``EdgeV2::classify`` 的同构门。
  404. 「参考实现调好的参数搬到现场 C++ 结论会变」是最难排查的一类问题,
  405. 所以两侧的门必须一一对应(C++ 侧对应断言在
  406. ``cpp/tests/selftest_edge_v2.cpp``):
  407. * ``min_bed_roi_px``:箱底以下 ROI 太矮 → 不判 1(``bed_roi_small``);
  408. * ``relaxed_post_array``:posts=min-1 但侧墙不透明且间距规则 → 仍判 1;
  409. * ``prefer_bed_on_conflict``:上述放宽形态与车面边梁同时成立 → 优先 1;
  410. * ``post_array_regular``:≥8 根且间距 CV>1.5 视为杂波 → 不判 1。
  411. """
  412. @staticmethod
  413. def _classify(params=None, **kwargs):
  414. from portcv.schema import ViewMode
  415. ev = make(params or EvidenceV2Params())
  416. base = dict(
  417. posts=6, spacing_cv=0.3, opacity=0.6, ground=0.2, deck=False,
  418. wheels=0, gap_px=20.0, motion_ok=True, view=ViewMode.FRONT,
  419. under_deck=False, post_spacing_px=80.0, diagonal_braces=2,
  420. post_span_ratio=0.6, below_roi_h_px=300.0,
  421. )
  422. base.update(kwargs)
  423. return ev._classify(**base)
  424. def test_bed_roi_too_small_abstains(self):
  425. state, _, _, reason = self._classify(below_roi_h_px=40.0)
  426. self.assertEqual(state, 255)
  427. self.assertEqual(reason, "bed_roi_small")
  428. def test_relaxed_post_array_is_bed(self):
  429. state, _, _, reason = self._classify(
  430. posts=4, opacity=0.70, spacing_cv=0.5)
  431. self.assertEqual(state, 1, reason)
  432. self.assertEqual(reason, "wall_posts")
  433. def test_conflict_prefers_bed_when_relaxed(self):
  434. # 4 根 + 不透明 + 间距规则 → 既满足放宽门板阵列,又命中车面边梁;
  435. # 与 C++ 一致:按门板阵列优先,不因"冲突"弃权。
  436. state, _, _, reason = self._classify(
  437. posts=4, opacity=0.70, spacing_cv=0.5, deck=True, under_deck=True)
  438. self.assertEqual(state, 1, reason)
  439. def test_conflict_abstains_when_not_relaxed(self):
  440. # min_door_posts=3 / flat_max_door_posts=4:3 根就走正常门板门,
  441. # 与车面边梁同时成立 → conflict_1_2(与 C++ 同分支)。
  442. params = EvidenceV2Params(min_door_posts=3, flat_max_door_posts=4)
  443. state, _, _, reason = self._classify(
  444. params=params, posts=3, deck=True, under_deck=True)
  445. self.assertEqual(state, 255)
  446. self.assertEqual(reason, "conflict_1_2")
  447. def test_irregular_post_array_is_not_bed(self):
  448. state, _, _, reason = self._classify(
  449. posts=9, spacing_cv=1.9, opacity=0.8)
  450. self.assertNotEqual(state, 1, reason)
  451. def test_state2_needs_under_deck(self):
  452. state, _, _, reason = self._classify(
  453. posts=0, deck=True, under_deck=False, post_span_ratio=0.0)
  454. self.assertEqual(state, 255)
  455. self.assertEqual(reason, "weak_evidence")
  456. state2, _, _, _ = self._classify(
  457. posts=0, deck=True, under_deck=True, post_span_ratio=0.0)
  458. self.assertEqual(state2, 2)
  459. if __name__ == "__main__":
  460. unittest.main()