test_evidence_v2.py 31 KB

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