test_evidence_v2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. pick_box_and_bed,
  20. )
  21. from portcv.service.pipeline import VisionPipeline
  22. def bed_scene(*, gap_px: int = 18, box_bottom: int = 392) -> np.ndarray:
  23. """C70 类:箱底暗带 + 间隙 + 亮墙顶 + 门板立柱/斜撑。"""
  24. h, w = 720, 1280
  25. image = np.full((h, w), 120, dtype=np.uint8)
  26. image[40:box_bottom, :] = 185
  27. image[box_bottom:box_bottom + 12, :] = 55
  28. # gap_px 是“箱底下沿(暗带下沿)→ 墙顶亮带”的物理间隙。
  29. wall_top = box_bottom + 12 + gap_px
  30. image[box_bottom + 12:wall_top, :] = 88
  31. image[wall_top:wall_top + 4, :] = 215
  32. image[wall_top + 4:h, :] = 125
  33. for x in range(120, 1180, 110):
  34. image[wall_top + 20:min(h - 20, wall_top + 230), x:x + 5] = 55
  35. for x in range(150, 1050, 220):
  36. cv2.line(image, (x, wall_top + 30), (x + 120, wall_top + 220), 70, 4)
  37. # 门板横梁:让分块“地面样”统计看到结构面,而不是把灰墙当空地。
  38. for dy in range(30, 240, 20):
  39. y = min(h - 8, wall_top + dy)
  40. image[y:y + 2, 60:1220] = 85
  41. return image
  42. def flat_scene(*, gap_px: int = 4) -> np.ndarray:
  43. """X70 类:箱底暗带 + 薄车面边梁 + 车面/地面,无门板阵列。"""
  44. h, w = 720, 1280
  45. image = np.full((h, w), 120, dtype=np.uint8)
  46. image[40:392, :] = 185
  47. image[392:404, :] = 55
  48. deck_top = 404 + gap_px
  49. image[deck_top:deck_top + 5, :] = 225
  50. image[deck_top + 5:520, :] = 145
  51. # 车面横向边梁(动态 ROI 内的一条长直线)
  52. cv2.line(image, (40, deck_top + 24), (1240, deck_top + 24), 70, 5)
  53. rng = np.random.default_rng(20261019)
  54. ground = rng.integers(70, 190, size=(200, w), dtype=np.uint8)
  55. image[520:720, :] = ground
  56. return image
  57. def flat_contact_scene() -> np.ndarray:
  58. """侧视近距:箱体几乎占满画面,箱底与平车车面直接贴合。
  59. 对应实拍 746×192 近景:箱底暗带只有 3 px(y=167..170),下方是
  60. 10 px 车面亮带,再往下是车底/地面。旧版峰值检测会把 3 px 薄带
  61. 压掉,导致 ``no_box``;本场景用于锁住该回归。
  62. """
  63. h, w = 192, 746
  64. image = np.full((h, w), 180, dtype=np.uint8)
  65. image[10:167, :] = 185 # 箱体
  66. image[167:170, :] = 55 # 箱底暗带(仅 3 px)
  67. image[170:179, :] = 145 # 平车车面亮带(与箱底贴合)
  68. image[179:188, :] = 30 # 车底暗部
  69. image[188:h, :] = 80 # 地面
  70. image[173:175, 40:700] = 110 # 车面横向边梁(deck edge)
  71. for x in range(40, w, 40): # 箱体竖棱;不改变行均值
  72. image[20:160, x:x + 2] = 165
  73. return image
  74. def make(params: EvidenceV2Params, tracker: CommitTracker | None = None) -> EvidenceV2:
  75. return EvidenceV2(params, tracker)
  76. class BandSelectionTests(unittest.TestCase):
  77. def test_pick_box_and_bed_uses_nearest_bright_below(self):
  78. box, bed = pick_box_and_bed(
  79. [Band(430, 438, 100), Band(500, 510, 90)],
  80. [Band(407, 419, 100)],
  81. 720,
  82. )
  83. self.assertIsNotNone(box)
  84. self.assertIsNotNone(bed)
  85. self.assertEqual((box.y0, box.y1), (407, 419))
  86. self.assertEqual((bed.y0, bed.y1), (430, 438))
  87. def test_no_dark_band_returns_none(self):
  88. box, bed = pick_box_and_bed([], [], 720)
  89. self.assertIsNone(box)
  90. self.assertIsNone(bed)
  91. class EvidenceClassificationTests(unittest.TestCase):
  92. def test_a_like_wall_is_state1(self):
  93. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  94. result = ev.analyze(bed_scene(), ts=0.0)
  95. self.assertEqual(result.state, 1, result.to_dict())
  96. self.assertGreaterEqual(result.door_posts, 5)
  97. self.assertGreaterEqual(result.wall_opacity, 0.35)
  98. self.assertIsNotNone(result.gap_px)
  99. self.assertGreater(result.gap_px, 8.0)
  100. def test_b_like_deck_is_state2(self):
  101. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  102. result = ev.analyze(flat_scene(), ts=0.0)
  103. self.assertEqual(result.state, 2, result.to_dict())
  104. self.assertLessEqual(result.door_posts, 4)
  105. self.assertTrue(result.deck_edge)
  106. def test_nearly_full_frame_flatbed_contact_is_state2(self):
  107. # 箱底落在 0.885*h(超过 box_bottom_max_ratio=0.78),且箱底下沿
  108. # 与车面亮带贴合(gap=0)。必须仍能识别为 2,并在 5 帧后提交。
  109. tracker = CommitTracker(
  110. CommitParams(
  111. stable_frames=5, structure_frames=5,
  112. gap_px_hard_max=8.0, allow_state2=True,
  113. )
  114. )
  115. ev = make(
  116. EvidenceV2Params(px_per_m=100.0, require_commit=True),
  117. tracker,
  118. )
  119. image = flat_contact_scene()
  120. results = [ev.analyze(image, ts=i / 15.0, frame_id=i) for i in range(5)]
  121. first = results[0]
  122. self.assertEqual(first.state, 2, first.to_dict())
  123. self.assertLessEqual(first.door_posts, 4)
  124. self.assertTrue(first.deck_edge)
  125. self.assertAlmostEqual(
  126. -1.0 if first.gap_px is None else first.gap_px, 0.0, places=3
  127. )
  128. self.assertFalse(first.committed)
  129. self.assertEqual(
  130. first.to_observation(require_commit=True).state, 255,
  131. "commit 未满 5 帧时内部应保持 255",
  132. )
  133. self.assertTrue(results[-1].committed, results[-1].to_dict())
  134. self.assertEqual(
  135. results[-1].to_observation(require_commit=True).state, 2
  136. )
  137. def test_empty_image_is_unknown(self):
  138. ev = make(EvidenceV2Params(require_commit=False))
  139. result = ev.analyze(np.zeros((0, 0), dtype=np.uint8))
  140. self.assertEqual(result.state, 255)
  141. self.assertEqual(result.abstain_reason, "no_image")
  142. def test_blank_image_abstains(self):
  143. ev = make(EvidenceV2Params(require_commit=False))
  144. result = ev.analyze(np.full((720, 1280), 128, dtype=np.uint8))
  145. self.assertEqual(result.state, 255)
  146. self.assertTrue(result.abstain_reason)
  147. def test_dynamic_roi_follows_box_bottom(self):
  148. low = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  149. high = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  150. r_low = low.analyze(bed_scene(box_bottom=392), ts=0.0)
  151. r_high = high.analyze(bed_scene(box_bottom=520), ts=0.0)
  152. self.assertGreater(r_low.below_roi[1], 392)
  153. self.assertGreater(r_high.below_roi[1], 520)
  154. self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1])
  155. class CommitIntegrationTests(unittest.TestCase):
  156. def test_uncommitted_result_maps_to_internal_255(self):
  157. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=True))
  158. result = ev.analyze(bed_scene(gap_px=18), ts=0.0)
  159. self.assertEqual(result.state, 1)
  160. self.assertFalse(result.committed)
  161. obs = result.to_observation(require_commit=True)
  162. self.assertEqual(obs.state, 255)
  163. self.assertEqual(obs.confidence, 0.0)
  164. self.assertIn("abstain", obs.reason)
  165. def test_seated_frames_commit_and_publish_state1(self):
  166. tracker = CommitTracker(
  167. CommitParams(
  168. stable_frames=3, structure_frames=3,
  169. gap_px_hard_max=8.0, allow_state2=False,
  170. )
  171. )
  172. ev = make(
  173. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  174. tracker,
  175. )
  176. image = bed_scene(gap_px=4)
  177. last = None
  178. for i in range(4):
  179. last = ev.analyze(image, ts=i / 30.0)
  180. self.assertIsNotNone(last)
  181. self.assertTrue(last.committed, last.to_dict())
  182. obs = last.to_observation(ts=0.2, require_commit=True)
  183. self.assertEqual(obs.state, 1)
  184. self.assertGreater(obs.confidence, 0.45)
  185. def test_injected_hoist_high_blocks_commit(self):
  186. tracker = CommitTracker(
  187. CommitParams(
  188. stable_frames=3, structure_frames=3,
  189. gap_px_hard_max=8.0, allow_state2=False,
  190. )
  191. )
  192. ev = make(
  193. EvidenceV2Params(px_per_m=115.6, require_commit=True),
  194. tracker,
  195. )
  196. image = bed_scene(gap_px=4)
  197. last = None
  198. for i in range(6):
  199. last = ev.analyze(image, ts=i / 30.0, hoist_high=True)
  200. self.assertIsNotNone(last)
  201. self.assertTrue(last.hoist_high)
  202. self.assertFalse(last.committed)
  203. self.assertEqual(last.commit_reason, "hoist_high")
  204. self.assertEqual(last.abstain_reason, "hoist_high")
  205. obs = last.to_observation(require_commit=True)
  206. self.assertEqual(obs.state, 255)
  207. self.assertIn("hoist_high", obs.reason)
  208. def test_detect_hoist_high_finds_dark_bar_with_bright_sky_below(self):
  209. from portcv.logic.evidence_v2 import detect_hoist_high
  210. image = np.full((720, 1280), 185, dtype=np.uint8)
  211. image[40:140, :] = 25 # 上方吊具/臂架暗带
  212. image[140:300, :] = 185 # 暗带下方天空/箱顶更亮
  213. hoist, cues = detect_hoist_high(image, 300)
  214. self.assertTrue(hoist, cues)
  215. self.assertGreaterEqual(cues["horizontal_lines"], 1)
  216. def test_detect_hoist_high_ignores_uniform_scene(self):
  217. from portcv.logic.evidence_v2 import detect_hoist_high
  218. image = np.full((720, 1280), 150, dtype=np.uint8)
  219. hoist, cues = detect_hoist_high(image, 300)
  220. self.assertFalse(hoist, cues)
  221. self.assertEqual(cues["horizontal_lines"], 0)
  222. def test_spreader_contact_detects_dark_bar_on_container_top(self):
  223. from portcv.logic.evidence_v2 import detect_spreader_contact
  224. image = np.full((500, 600), 180, dtype=np.uint8)
  225. image[100:140, 100:500] = 30 # 吊具横梁紧贴箱顶
  226. image[140:450, 100:500] = 150 # 箱体
  227. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  228. self.assertTrue(hit, cues)
  229. self.assertGreaterEqual(cues["dark_run_px"], 20)
  230. def test_spreader_contact_ignores_plain_container_top(self):
  231. from portcv.logic.evidence_v2 import detect_spreader_contact
  232. image = np.full((500, 600), 180, dtype=np.uint8)
  233. image[140:450, 100:500] = 150
  234. hit, cues = detect_spreader_contact(image, (100, 140, 500, 450))
  235. self.assertFalse(hit, cues)
  236. def test_classify_only_mode_publishes_candidate(self):
  237. ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
  238. obs = ev.classify(bed_scene(), ts=0.0, frame_id=1)
  239. self.assertEqual(obs.state, 1)
  240. self.assertGreater(obs.confidence, 0.45)
  241. class PipelineAndConfigTests(unittest.TestCase):
  242. def test_pipeline_uses_evidence_v2_when_enabled(self):
  243. cfg = Config(
  244. {
  245. "run": {"backend": "mock"},
  246. "evidence_v2": {
  247. "enabled": True,
  248. "px_per_m": 115.6,
  249. "require_commit": False,
  250. },
  251. }
  252. )
  253. pipeline = VisionPipeline(cfg)
  254. self.assertIsNotNone(pipeline.evidence_v2)
  255. observation, _decision = pipeline.step(
  256. Frame(bed_scene(), ts=0.0, frame_id=1)
  257. )
  258. self.assertEqual(observation.state, 1, observation.reason)
  259. def test_pipeline_keeps_legacy_path_by_default(self):
  260. cfg = Config({"run": {"backend": "mock"}})
  261. pipeline = VisionPipeline(cfg)
  262. self.assertIsNone(pipeline.evidence_v2)
  263. def test_site_template_loads_and_backend_alias_resolves(self):
  264. path = os.path.join(
  265. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  266. "configs", "edge-v2-front.json",
  267. )
  268. cfg = load_config(path)
  269. self.assertTrue(bool(cfg.get_path("evidence_v2.enabled")))
  270. self.assertTrue(bool(cfg.get_path("evidence_v2.allow_state2")))
  271. self.assertTrue(bool(cfg.get_path("evidence_v2.commit.allow_state2")))
  272. self.assertEqual(resolve_backend(cfg.get_path("run.backend")), "mock")
  273. if __name__ == "__main__":
  274. unittest.main()