test_evidence_v2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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 empty_flatbed_scene(*, deck_gray: int = 165, sill_gray: int = 228) -> np.ndarray:
  81. """P0-Q10:空平车(车底板裸露)—— 薄边梁 + 车底透空 + 光滑亮车面 + 地面。
  82. 与 ``flat_scene``(平车+箱)的差别:箱底暗带不再紧贴边梁,中间隔着整片车面。
  83. """
  84. h, w = 720, 1280
  85. image = np.full((h, w), 200, dtype=np.uint8) # 天空/背景
  86. image[60:64, :] = 30 # 车底板远端边缘(细暗线 → 被当成“箱底”)
  87. image[64:300, :] = deck_gray # 车底板(光滑亮面)
  88. for y in range(120, 300, 120): # 车面板缝(很淡的横缝)
  89. image[y:y + 2, :] = deck_gray - 6
  90. image[300:304, :] = sill_gray # 近侧边梁(薄亮边)
  91. image[304:334, :] = 40 # 车底透空(暗)
  92. image[334:430, :] = 70 # 转向架/车底结构(暗)
  93. rng = np.random.default_rng(20261120)
  94. ramp = np.linspace(95, 135, h - 430).reshape(-1, 1)
  95. jitter = rng.integers(-3, 4, size=(h - 430, w))
  96. image[430:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8) # 沥青地
  97. return image
  98. def make(params: EvidenceV2Params, tracker: CommitTracker | None = None) -> EvidenceV2:
  99. return EvidenceV2(params, tracker)
  100. def ground_scene(*, low: int = 95, high: int = 115, noise: int = 4) -> np.ndarray:
  101. """箱直接坐地:箱底以下是低对比、连续的地面(水泥地/砂石)。
  102. P0-Q3 回归用:这种画面**绝不能**被判成 2(平车)或 1(敞车)。
  103. """
  104. h, w = 720, 1280
  105. image = np.full((h, w), 120, dtype=np.uint8)
  106. image[40:392, :] = 185
  107. for x in range(60, 1240, 48):
  108. image[50:388, x:x + 3] = 176
  109. image[392:404, :] = 55 # 箱底暗带
  110. rng = np.random.default_rng(20261118)
  111. ramp = np.linspace(low, high, h - 404).reshape(-1, 1)
  112. jitter = rng.integers(-noise, noise + 1, size=(h - 404, w))
  113. image[404:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8)
  114. return image
  115. def thick_contact_scene() -> np.ndarray:
  116. """箱底紧贴一块**厚亮面**(地面/下层箱顶/月台),下方仍是地面。
  117. 旧版 C++ `flat_contact` 会把这块厚亮面当车面 → 2;本用例锁住该回归。
  118. """
  119. image = ground_scene()
  120. image[404:450, :] = 165 # 46 px 厚亮面(估箱高 ≈356 px → 0.13 > 0.12)
  121. return image
  122. def stacked_scene() -> np.ndarray:
  123. """上层箱坐在下层箱上:下层箱顶亮面 + 侧壁瓦楞(无斜撑)。
  124. 旧版会把瓦楞当门板立柱、把箱顶亮面当车面 → 1;本用例要求 0/255。
  125. """
  126. image = ground_scene()
  127. image[404:450, :] = 165 # 下层箱顶面
  128. image[450:, :] = 140 # 下层箱侧壁
  129. for x in range(60, 1280, 118): # 瓦楞竖棱(≈10 根)
  130. image[450:700, x:x + 6] = 95
  131. return image
  132. class BandSelectionTests(unittest.TestCase):
  133. def test_pick_box_and_bed_uses_nearest_bright_below(self):
  134. box, bed = pick_box_and_bed(
  135. [Band(430, 438, 100), Band(500, 510, 90)],
  136. [Band(407, 419, 100)],
  137. 720,
  138. )
  139. self.assertIsNotNone(box)
  140. self.assertIsNotNone(bed)
  141. self.assertEqual((box.y0, box.y1), (407, 419))
  142. self.assertEqual((bed.y0, bed.y1), (430, 438))
  143. def test_no_dark_band_returns_none(self):
  144. box, bed = pick_box_and_bed([], [], 720)
  145. self.assertIsNone(box)
  146. self.assertIsNone(bed)
  147. class EvidenceClassificationTests(unittest.TestCase):
  148. def test_a_like_wall_is_state1(self):
  149. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  150. result = ev.analyze(bed_scene(), ts=0.0)
  151. self.assertEqual(result.state, 1, result.to_dict())
  152. self.assertGreaterEqual(result.door_posts, 5)
  153. self.assertGreaterEqual(result.wall_opacity, 0.35)
  154. self.assertIsNotNone(result.gap_px)
  155. self.assertGreater(result.gap_px, 8.0)
  156. def test_b_like_deck_is_state2(self):
  157. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  158. result = ev.analyze(flat_scene(), ts=0.0)
  159. self.assertEqual(result.state, 2, result.to_dict())
  160. self.assertLessEqual(result.door_posts, 4)
  161. self.assertTrue(result.deck_edge)
  162. def test_nearly_full_frame_flatbed_contact_is_state2(self):
  163. # 箱底落在 0.885*h(超过 box_bottom_max_ratio=0.78),且箱底下沿
  164. # 与车面亮带贴合(gap=0)。必须仍能识别为 2,并在 5 帧后提交。
  165. tracker = CommitTracker(
  166. CommitParams(
  167. stable_frames=5, structure_frames=5,
  168. gap_px_hard_max=8.0, allow_state2=True,
  169. )
  170. )
  171. ev = make(
  172. EvidenceV2Params(px_per_m=100.0, require_commit=True),
  173. tracker,
  174. )
  175. image = flat_contact_scene()
  176. results = [ev.analyze(image, ts=i / 15.0, frame_id=i) for i in range(5)]
  177. first = results[0]
  178. self.assertEqual(first.state, 2, first.to_dict())
  179. self.assertLessEqual(first.door_posts, 4)
  180. self.assertTrue(first.deck_edge)
  181. self.assertAlmostEqual(
  182. -1.0 if first.gap_px is None else first.gap_px, 0.0, places=3
  183. )
  184. self.assertFalse(first.committed)
  185. self.assertEqual(
  186. first.to_observation(require_commit=True).state, 255,
  187. "commit 未满 5 帧时内部应保持 255",
  188. )
  189. self.assertTrue(results[-1].committed, results[-1].to_dict())
  190. self.assertEqual(
  191. results[-1].to_observation(require_commit=True).state, 2
  192. )
  193. def test_empty_image_is_unknown(self):
  194. ev = make(EvidenceV2Params(require_commit=False))
  195. result = ev.analyze(np.zeros((0, 0), dtype=np.uint8))
  196. self.assertEqual(result.state, 255)
  197. self.assertEqual(result.abstain_reason, "no_image")
  198. def test_blank_image_abstains(self):
  199. ev = make(EvidenceV2Params(require_commit=False))
  200. result = ev.analyze(np.full((720, 1280), 128, dtype=np.uint8))
  201. self.assertEqual(result.state, 255)
  202. self.assertTrue(result.abstain_reason)
  203. def test_dynamic_roi_follows_box_bottom(self):
  204. low = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  205. high = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  206. r_low = low.analyze(bed_scene(box_bottom=392), ts=0.0)
  207. r_high = high.analyze(bed_scene(box_bottom=520), ts=0.0)
  208. self.assertGreater(r_low.below_roi[1], 392)
  209. self.assertGreater(r_high.below_roi[1], 520)
  210. self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1])
  211. def sky_wire_scene() -> np.ndarray:
  212. """P0-Q4:天空电线 + 空 C70 车体(512×512,无下采样)。"""
  213. h = w = 512
  214. image = np.full((h, w), 200, dtype=np.uint8)
  215. for y in (20, 52, 84, 116):
  216. image[y:y + 2, :] = 30
  217. image[165:405, :] = 95
  218. for x in range(30, 480, 18):
  219. image[175:400, x:x + 5] = 45
  220. for x in range(30, 480, 50):
  221. cv2.rectangle(image, (x, 185), (x + 40, 380), 60, 3)
  222. image[188:377, x + 3:x + 37] = 110
  223. for dy in range(5, 235, 8):
  224. y = 165 + dy
  225. image[y:y + 2, 20:492] = 80
  226. for x in range(40, 470, 70):
  227. cv2.line(image, (x, 190), (x + 80, 330), 30, 7)
  228. image[405:, :] = 140
  229. return image
  230. class TextureTopTests(unittest.TestCase):
  231. """P0-Q4:天空电线不能把“车体顶”骗到天上。"""
  232. def test_sky_wires_are_above_vehicle_top(self):
  233. image = sky_wire_scene()
  234. window = (int(0.24 * 512), int(0.02 * 512), int(0.78 * 512), int(0.95 * 512))
  235. top = find_texture_top(image, window, EvidenceV2Params())
  236. self.assertGreater(top, 120, "车体顶应落在电线以下")
  237. self.assertLess(top, 220, "车体顶不应落到车体中部")
  238. def test_empty_c70_outputs_state3(self):
  239. # P0-Q9(2026-11-20 客户要求):空车从 255 里摘出来,单独输出 state=3。
  240. # 判据 = texture_top 以下是一整节空敞车侧墙(门板阵列 + 斜撑 + 不透明 +
  241. # 横跨整车 + 墙高足够),且没有集装箱证据。
  242. ev = EvidenceV2(EvidenceV2Params(require_commit=False))
  243. result = ev.analyze(sky_wire_scene(), ts=0.0)
  244. self.assertEqual(result.state, 3, result.to_dict())
  245. self.assertTrue(result.empty_vehicle, result.to_dict())
  246. self.assertEqual(result.class_reason, "empty_vehicle", result.to_dict())
  247. self.assertEqual(result.abstain_reason, "", result.to_dict())
  248. self.assertGreater(result.texture_top_y or 0.0, 120.0)
  249. self.assertNotIn(result.state, (1, 2), result.to_dict())
  250. def test_plain_sky_has_no_vehicle_top(self):
  251. image = np.full((720, 1280), 200, dtype=np.uint8)
  252. for y in (40, 90, 140):
  253. image[y:y + 2, :] = 30
  254. window = (int(0.24 * 1280), int(0.02 * 720), int(0.78 * 1280), int(0.95 * 720))
  255. self.assertLess(find_texture_top(image, window, EvidenceV2Params()), 0)
  256. class EmptyVehicleTests(unittest.TestCase):
  257. """P0-Q9:空车(敞车、车斗内无箱)单独输出 state=3,且绝不误伤载车/地面。"""
  258. def test_empty_gondola_is_state3_and_commits(self):
  259. ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6),
  260. CommitTracker(CommitParams(stable_frames=3, structure_frames=3)))
  261. last = None
  262. for i in range(6):
  263. last = ev.analyze(sky_wire_scene(), ts=i * 0.1)
  264. self.assertIsNotNone(last)
  265. self.assertEqual(last.state, 3, last.to_dict())
  266. self.assertTrue(last.committed, last.to_dict())
  267. self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 3)
  268. def test_bed_with_container_stays_state1(self):
  269. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  270. result = ev.analyze(bed_scene(), ts=0.0)
  271. self.assertEqual(result.state, 1, result.to_dict())
  272. self.assertFalse(result.empty_vehicle, result.to_dict())
  273. def test_flatbed_with_container_stays_state2(self):
  274. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  275. result = ev.analyze(flat_scene(), ts=0.0)
  276. self.assertEqual(result.state, 2, result.to_dict())
  277. self.assertFalse(result.empty_vehicle, result.to_dict())
  278. def test_ground_never_state3(self):
  279. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  280. for image in (ground_scene(), thick_contact_scene(), stacked_scene()):
  281. result = ev.analyze(image, ts=0.0)
  282. self.assertNotEqual(result.state, 3, result.to_dict())
  283. self.assertFalse(result.empty_vehicle, result.to_dict())
  284. def test_allow_state3_off_recognizes_but_does_not_commit(self):
  285. params = EvidenceV2Params(px_per_m=115.6, require_commit=True, allow_state3=False)
  286. ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6, require_commit=False),
  287. CommitTracker(CommitParams(stable_frames=2, structure_frames=2,
  288. allow_state3=False)))
  289. last = None
  290. for i in range(6):
  291. last = ev.analyze(sky_wire_scene(), ts=i * 0.1)
  292. self.assertIsNotNone(last)
  293. self.assertEqual(last.state, 3, last.to_dict())
  294. self.assertFalse(last.committed, last.to_dict())
  295. self.assertEqual(last.commit_reason, "state3_disabled", last.to_dict())
  296. self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 255)
  297. self.assertTrue(params.require_commit)
  298. class EmptyFlatbedTests(unittest.TestCase):
  299. """P0-Q10:空平车(车面裸露)也输出 3;载车/地面绝不落 3。"""
  300. def test_empty_flatbed_is_state3_and_commits(self):
  301. ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6),
  302. CommitTracker(CommitParams(stable_frames=3, structure_frames=3)))
  303. last = None
  304. for i in range(6):
  305. last = ev.analyze(empty_flatbed_scene(), ts=i * 0.1)
  306. self.assertIsNotNone(last)
  307. self.assertEqual(last.state, 3, last.to_dict())
  308. self.assertEqual(last.class_reason, "empty_flatbed", last.to_dict())
  309. self.assertTrue(last.committed, last.to_dict())
  310. self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 3)
  311. def test_flatcar_with_container_is_not_empty(self):
  312. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  313. for image in (flat_scene(), flat_contact_scene()):
  314. result = ev.analyze(image, ts=0.0)
  315. self.assertNotEqual(result.state, 3, result.to_dict())
  316. self.assertFalse(result.empty_vehicle, result.to_dict())
  317. def test_ground_and_stack_never_empty_flatbed(self):
  318. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  319. for image in (ground_scene(), thick_contact_scene(), stacked_scene()):
  320. result = ev.analyze(image, ts=0.0)
  321. self.assertNotEqual(result.state, 3, result.to_dict())
  322. def test_flatbed_gate_can_be_disabled(self):
  323. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False,
  324. empty_flatbed_enable=False))
  325. result = ev.analyze(empty_flatbed_scene(), ts=0.0)
  326. self.assertNotEqual(result.state, 3, result.to_dict())
  327. class GroundStackSafetyTests(unittest.TestCase):
  328. """P0-Q3:地面/堆料/堆叠箱不得被判成 1(敞车)或 2(平车)。"""
  329. def _classify(self, image: np.ndarray):
  330. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  331. return ev.analyze(image, ts=0.0)
  332. def test_box_on_ground_is_never_bed_or_flatbed(self):
  333. result = self._classify(ground_scene())
  334. self.assertNotIn(result.state, (1, 2), result.to_dict())
  335. def test_thick_contact_plane_is_not_flatbed(self):
  336. # 箱底紧贴一块厚亮面(地面/下层箱顶/月台)→ 旧版 flat_contact 会判 2
  337. result = self._classify(thick_contact_scene())
  338. self.assertNotIn(result.state, (1, 2), result.to_dict())
  339. self.assertFalse(result.deck_edge, result.to_dict())
  340. def test_container_stacked_on_container_is_not_bed(self):
  341. # 下层箱的瓦楞不是车斗门板;下层箱顶也不是车面
  342. result = self._classify(stacked_scene())
  343. self.assertNotIn(result.state, (1, 2), result.to_dict())
  344. class CommitIntegrationTests(unittest.TestCase):
  345. def test_uncommitted_result_maps_to_internal_255(self):
  346. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=True))
  347. result = ev.analyze(bed_scene(gap_px=18), ts=0.0)
  348. self.assertEqual(result.state, 1)
  349. self.assertFalse(result.committed)
  350. obs = result.to_observation(require_commit=True)
  351. self.assertEqual(obs.state, 255)
  352. self.assertEqual(obs.confidence, 0.0)
  353. self.assertIn("abstain", obs.reason)
  354. def test_seated_frames_commit_and_publish_state1(self):
  355. tracker = CommitTracker(
  356. CommitParams(
  357. stable_frames=3, structure_frames=3,
  358. gap_px_hard_max=8.0, allow_state2=False,
  359. )
  360. )
  361. ev = make(
  362. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  363. tracker,
  364. )
  365. image = bed_scene(gap_px=4)
  366. last = None
  367. for i in range(4):
  368. last = ev.analyze(image, ts=i / 30.0)
  369. self.assertIsNotNone(last)
  370. self.assertTrue(last.committed, last.to_dict())
  371. obs = last.to_observation(ts=0.2, require_commit=True)
  372. self.assertEqual(obs.state, 1)
  373. self.assertGreater(obs.confidence, 0.45)
  374. def test_injected_hoist_high_blocks_commit(self):
  375. tracker = CommitTracker(
  376. CommitParams(
  377. stable_frames=3, structure_frames=3,
  378. gap_px_hard_max=8.0, allow_state2=False,
  379. )
  380. )
  381. ev = make(
  382. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  383. tracker,
  384. )
  385. image = bed_scene(gap_px=4)
  386. last = None
  387. for i in range(6):
  388. last = ev.analyze(image, ts=i / 30.0, hoist_high=True)
  389. self.assertIsNotNone(last)
  390. self.assertTrue(last.hoist_high)
  391. self.assertFalse(last.committed)
  392. self.assertEqual(last.commit_reason, "hoist_high")
  393. self.assertEqual(last.abstain_reason, "hoist_high")
  394. obs = last.to_observation(require_commit=True)
  395. self.assertEqual(obs.state, 255)
  396. self.assertIn("hoist_high", obs.reason)
  397. def test_detect_hoist_high_finds_dark_bar_with_bright_sky_below(self):
  398. from portcv.logic.evidence_v2 import detect_hoist_high
  399. image = np.full((720, 1280), 185, dtype=np.uint8)
  400. image[40:140, :] = 25 # 上方吊具/臂架暗带
  401. image[140:300, :] = 185 # 暗带下方天空/箱顶更亮
  402. hoist, cues = detect_hoist_high(image, 300)
  403. self.assertTrue(hoist, cues)
  404. self.assertGreaterEqual(cues["horizontal_lines"], 1)
  405. def test_detect_hoist_high_ignores_uniform_scene(self):
  406. from portcv.logic.evidence_v2 import detect_hoist_high
  407. image = np.full((720, 1280), 150, dtype=np.uint8)
  408. hoist, cues = detect_hoist_high(image, 300)
  409. self.assertFalse(hoist, cues)
  410. self.assertEqual(cues["horizontal_lines"], 0)
  411. def test_spreader_contact_detects_dark_bar_on_container_top(self):
  412. from portcv.logic.evidence_v2 import detect_spreader_contact
  413. image = np.full((500, 600), 180, dtype=np.uint8)
  414. image[100:140, 100:500] = 30 # 吊具横梁紧贴箱顶
  415. image[140:450, 100:500] = 150 # 箱体
  416. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  417. self.assertTrue(hit, cues)
  418. self.assertGreaterEqual(cues["dark_run_px"], 20)
  419. def test_spreader_contact_ignores_plain_container_top(self):
  420. from portcv.logic.evidence_v2 import detect_spreader_contact
  421. image = np.full((500, 600), 180, dtype=np.uint8)
  422. image[140:450, 100:500] = 150
  423. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  424. self.assertFalse(hit, cues)
  425. def test_classify_only_mode_publishes_candidate(self):
  426. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  427. obs = ev.classify(bed_scene(), ts=0.0, frame_id=1)
  428. self.assertEqual(obs.state, 1)
  429. self.assertGreater(obs.confidence, 0.45)
  430. class VehicleOnlyTests(unittest.TestCase):
  431. """箱底被车帮挡住(罐箱)时“只看车体”判敞车(P0-Q6)。
  432. 现场来源:`04_container_on_gondola.png`(MLGU 350584 罐箱坐在敞车上,
  433. 箱底被车帮完全挡住)——旧实现直接 `no_box` 弃权,用户要求“罐箱也要输出”。
  434. C++/Python 判据都是**立柱跨度**(敞车横跨整车 ≥`vehicle_min_span_ratio`,
  435. 平车上集装箱波纹只占中间一段)。
  436. 注意:**正向用例只能靠现场帧**(`docs/evidence/` 的 4 张图 + A/B 片段),
  437. 合成图的大片均匀区会被 `ground_like_ratio` 判成“地面”,`opacity` 上不去,
  438. 测不出“检测得到”这件事;这里只锁“没有车体结构时必须弃权、不许猜”。
  439. """
  440. @staticmethod
  441. def _no_bands():
  442. from unittest import mock
  443. return mock.patch(
  444. "portcv.logic.evidence_v2.horizontal_bands",
  445. return_value=([], []),
  446. )
  447. def test_no_box_without_wall_abstains(self):
  448. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  449. blank = np.full((720, 1280), 120, dtype=np.uint8)
  450. with self._no_bands():
  451. obs = ev.classify(blank, ts=0.0, frame_id=1)
  452. self.assertEqual(obs.state, 255, obs.reason)
  453. self.assertIn("no_box", obs.reason)
  454. def test_no_box_never_guesses_flatbed(self):
  455. # 无箱底时只可能给 1 或弃权;**不许**因为“看不清”给平车 2。
  456. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  457. blank = np.full((720, 1280), 120, dtype=np.uint8)
  458. with self._no_bands():
  459. obs = ev.classify(blank, ts=0.0, frame_id=1)
  460. self.assertNotEqual(obs.state, 2, obs.reason)
  461. class PipelineAndConfigTests(unittest.TestCase):
  462. def test_pipeline_uses_evidence_v2_when_enabled(self):
  463. cfg = Config(
  464. {
  465. "run": {"backend": "mock"},
  466. "evidence_v2": {
  467. "enabled": True,
  468. "px_per_m": 115.6,
  469. "require_commit": False,
  470. },
  471. }
  472. )
  473. pipeline = VisionPipeline(cfg)
  474. self.assertIsNotNone(pipeline.evidence_v2)
  475. observation, _decision = pipeline.step(
  476. Frame(bed_scene(), ts=0.0, frame_id=1)
  477. )
  478. self.assertEqual(observation.state, 1, observation.reason)
  479. def test_pipeline_keeps_legacy_path_by_default(self):
  480. cfg = Config({"run": {"backend": "mock"}})
  481. pipeline = VisionPipeline(cfg)
  482. self.assertIsNone(pipeline.evidence_v2)
  483. def test_site_template_loads_and_backend_alias_resolves(self):
  484. path = os.path.join(
  485. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  486. "configs", "edge-v2-front.json",
  487. )
  488. cfg = load_config(path)
  489. self.assertTrue(bool(cfg.get_path("evidence_v2.enabled")))
  490. self.assertTrue(bool(cfg.get_path("evidence_v2.allow_state2")))
  491. self.assertTrue(bool(cfg.get_path("evidence_v2.commit.allow_state2")))
  492. self.assertEqual(resolve_backend(cfg.get_path("run.backend")), "mock")
  493. class ClassifyParityTests(unittest.TestCase):
  494. """Python ``_classify`` 与 C++ ``EdgeV2::classify`` 的同构门。
  495. 「参考实现调好的参数搬到现场 C++ 结论会变」是最难排查的一类问题,
  496. 所以两侧的门必须一一对应(C++ 侧对应断言在
  497. ``cpp/tests/selftest_edge_v2.cpp``):
  498. * ``min_bed_roi_px``:箱底以下 ROI 太矮 → 不判 1(``bed_roi_small``);
  499. * ``relaxed_post_array``:posts=min-1 但侧墙不透明且间距规则 → 仍判 1;
  500. * ``prefer_bed_on_conflict``:上述放宽形态与车面边梁同时成立 → 优先 1;
  501. * ``post_array_regular``:≥8 根且间距 CV>1.5 视为杂波 → 不判 1。
  502. """
  503. @staticmethod
  504. def _classify(params=None, **kwargs):
  505. from portcv.schema import ViewMode
  506. ev = make(params or EvidenceV2Params())
  507. base = dict(
  508. posts=6, spacing_cv=0.3, opacity=0.6, ground=0.2, deck=False,
  509. wheels=0, gap_px=20.0, motion_ok=True, view=ViewMode.FRONT,
  510. under_deck=False, post_spacing_px=80.0, diagonal_braces=2,
  511. post_span_ratio=0.6, below_roi_h_px=300.0,
  512. )
  513. base.update(kwargs)
  514. return ev._classify(**base)
  515. def test_bed_roi_too_small_abstains(self):
  516. state, _, _, reason = self._classify(below_roi_h_px=40.0)
  517. self.assertEqual(state, 255)
  518. self.assertEqual(reason, "bed_roi_small")
  519. def test_relaxed_post_array_is_bed(self):
  520. state, _, _, reason = self._classify(
  521. posts=4, opacity=0.70, spacing_cv=0.5)
  522. self.assertEqual(state, 1, reason)
  523. self.assertEqual(reason, "wall_posts")
  524. def test_conflict_prefers_bed_when_relaxed(self):
  525. # 4 根 + 不透明 + 间距规则 → 既满足放宽门板阵列,又命中车面边梁;
  526. # 与 C++ 一致:按门板阵列优先,不因"冲突"弃权。
  527. state, _, _, reason = self._classify(
  528. posts=4, opacity=0.70, spacing_cv=0.5, deck=True, under_deck=True)
  529. self.assertEqual(state, 1, reason)
  530. def test_conflict_abstains_when_not_relaxed(self):
  531. # min_door_posts=3 / flat_max_door_posts=4:3 根就走正常门板门,
  532. # 与车面边梁同时成立 → conflict_1_2(与 C++ 同分支)。
  533. params = EvidenceV2Params(min_door_posts=3, flat_max_door_posts=4)
  534. state, _, _, reason = self._classify(
  535. params=params, posts=3, deck=True, under_deck=True)
  536. self.assertEqual(state, 255)
  537. self.assertEqual(reason, "conflict_1_2")
  538. def test_irregular_post_array_is_not_bed(self):
  539. state, _, _, reason = self._classify(
  540. posts=9, spacing_cv=1.9, opacity=0.8)
  541. self.assertNotEqual(state, 1, reason)
  542. def test_state2_needs_under_deck(self):
  543. state, _, _, reason = self._classify(
  544. posts=0, deck=True, under_deck=False, post_span_ratio=0.0)
  545. self.assertEqual(state, 255)
  546. self.assertEqual(reason, "weak_evidence")
  547. state2, _, _, _ = self._classify(
  548. posts=0, deck=True, under_deck=True, post_span_ratio=0.0)
  549. self.assertEqual(state2, 2)
  550. if __name__ == "__main__":
  551. unittest.main()