"""P1b evidence_v2 合成场景测试。 不依赖现场素材:用确定性灰度图构造“敞车侧墙门板”与“平车车面边梁”, 断言分类、动态 ROI、commit 门与 Observation 映射。A/B 真帧回放由 ``scripts/replay_evidence_v2.py`` 负责(素材不在仓库时跳过)。 """ from __future__ import annotations import os import unittest import cv2 import numpy as np from portcv.config import Config, load_config from portcv.detect import resolve_backend from portcv.io.capture import Frame from portcv.logic.commit import CommitParams, CommitTracker from portcv.logic.evidence_v2 import ( Band, EvidenceV2, EvidenceV2Params, find_texture_top, pick_box_and_bed, ) from portcv.service.pipeline import VisionPipeline def bed_scene(*, gap_px: int = 18, box_bottom: int = 392) -> np.ndarray: """C70 类:箱底暗带 + 间隙 + 亮墙顶 + 门板立柱/斜撑。""" h, w = 720, 1280 image = np.full((h, w), 120, dtype=np.uint8) image[40:box_bottom, :] = 185 # 箱体竖波纹(真实集装箱有;也让 P0-Q4 顶部纹理门不把箱顶误当天空) for x in range(60, 1240, 48): image[50:box_bottom - 4, x:x + 3] = 176 image[box_bottom:box_bottom + 12, :] = 55 # gap_px 是“箱底下沿(暗带下沿)→ 墙顶亮带”的物理间隙。 wall_top = box_bottom + 12 + gap_px image[box_bottom + 12:wall_top, :] = 88 image[wall_top:wall_top + 4, :] = 215 image[wall_top + 4:h, :] = 125 for x in range(120, 1180, 110): image[wall_top + 20:min(h - 20, wall_top + 230), x:x + 5] = 55 for x in range(150, 1050, 220): cv2.line(image, (x, wall_top + 30), (x + 120, wall_top + 220), 70, 4) # 门板横梁:让分块“地面样”统计看到结构面,而不是把灰墙当空地。 for dy in range(30, 240, 20): y = min(h - 8, wall_top + dy) image[y:y + 2, 60:1220] = 85 return image def flat_scene(*, gap_px: int = 4) -> np.ndarray: """X70 类:箱底暗带 + 薄车面边梁 + 车面/地面,无门板阵列。""" h, w = 720, 1280 image = np.full((h, w), 120, dtype=np.uint8) image[40:392, :] = 185 for x in range(60, 1240, 48): image[50:388, x:x + 3] = 176 image[392:404, :] = 55 deck_top = 404 + gap_px image[deck_top:deck_top + 5, :] = 225 image[deck_top + 5:520, :] = 145 # 车面横向边梁(动态 ROI 内的一条长直线) cv2.line(image, (40, deck_top + 24), (1240, deck_top + 24), 70, 5) rng = np.random.default_rng(20261019) ground = rng.integers(70, 190, size=(200, w), dtype=np.uint8) image[520:720, :] = ground return image def flat_contact_scene() -> np.ndarray: """侧视近距:箱体几乎占满画面,箱底与平车车面直接贴合。 对应实拍 746×192 近景:箱底暗带只有 3 px(y=167..170),下方是 10 px 车面亮带,再往下是车底/地面。旧版峰值检测会把 3 px 薄带 压掉,导致 ``no_box``;本场景用于锁住该回归。 """ h, w = 192, 746 image = np.full((h, w), 180, dtype=np.uint8) image[10:167, :] = 185 # 箱体 image[167:170, :] = 55 # 箱底暗带(仅 3 px) image[170:179, :] = 145 # 平车车面亮带(与箱底贴合) image[179:188, :] = 30 # 车底暗部 image[188:h, :] = 80 # 地面 image[173:175, 40:700] = 110 # 车面横向边梁(deck edge) for x in range(40, w, 40): # 箱体竖棱;不改变行均值 image[20:160, x:x + 2] = 165 return image def empty_flatbed_scene(*, deck_gray: int = 165, sill_gray: int = 228) -> np.ndarray: """P0-Q10:空平车(车底板裸露)—— 薄边梁 + 车底透空 + 光滑亮车面 + 地面。 与 ``flat_scene``(平车+箱)的差别:箱底暗带不再紧贴边梁,中间隔着整片车面。 """ h, w = 720, 1280 image = np.full((h, w), 200, dtype=np.uint8) # 天空/背景 image[60:64, :] = 30 # 车底板远端边缘(细暗线 → 被当成“箱底”) image[64:300, :] = deck_gray # 车底板(光滑亮面) for y in range(120, 300, 120): # 车面板缝(很淡的横缝) image[y:y + 2, :] = deck_gray - 6 image[300:304, :] = sill_gray # 近侧边梁(薄亮边) image[304:334, :] = 40 # 车底透空(暗) image[334:430, :] = 70 # 转向架/车底结构(暗) rng = np.random.default_rng(20261120) ramp = np.linspace(95, 135, h - 430).reshape(-1, 1) jitter = rng.integers(-3, 4, size=(h - 430, w)) image[430:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8) # 沥青地 return image def empty_flatbed_no_void_scene() -> np.ndarray: """负样本:边梁下方**没有**车底透空(直接接地面)→ 不得判空平车。 对应现场"月台边缘/挡墙/道砟堆"这类"薄亮边 + 亮面"的假车面。 """ image = empty_flatbed_scene() image[304:334, :] = 96 # 原车底透空(40)→ 改成与地面同亮度的实体,去掉暗带 image[334:430, :] = 100 return image def make(params: EvidenceV2Params, tracker: CommitTracker | None = None) -> EvidenceV2: return EvidenceV2(params, tracker) def ground_scene(*, low: int = 95, high: int = 115, noise: int = 4) -> np.ndarray: """箱直接坐地:箱底以下是低对比、连续的地面(水泥地/砂石)。 P0-Q3 回归用:这种画面**绝不能**被判成 2(平车)或 1(敞车)。 """ h, w = 720, 1280 image = np.full((h, w), 120, dtype=np.uint8) image[40:392, :] = 185 for x in range(60, 1240, 48): image[50:388, x:x + 3] = 176 image[392:404, :] = 55 # 箱底暗带 rng = np.random.default_rng(20261118) ramp = np.linspace(low, high, h - 404).reshape(-1, 1) jitter = rng.integers(-noise, noise + 1, size=(h - 404, w)) image[404:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8) return image def thick_contact_scene() -> np.ndarray: """箱底紧贴一块**厚亮面**(地面/下层箱顶/月台),下方仍是地面。 旧版 C++ `flat_contact` 会把这块厚亮面当车面 → 2;本用例锁住该回归。 """ image = ground_scene() image[404:450, :] = 165 # 46 px 厚亮面(估箱高 ≈356 px → 0.13 > 0.12) return image def stacked_scene() -> np.ndarray: """上层箱坐在下层箱上:下层箱顶亮面 + 侧壁瓦楞(无斜撑)。 旧版会把瓦楞当门板立柱、把箱顶亮面当车面 → 1;本用例要求 0/255。 """ image = ground_scene() image[404:450, :] = 165 # 下层箱顶面 image[450:, :] = 140 # 下层箱侧壁 for x in range(60, 1280, 118): # 瓦楞竖棱(≈10 根) image[450:700, x:x + 6] = 95 return image class BandSelectionTests(unittest.TestCase): def test_pick_box_and_bed_uses_nearest_bright_below(self): box, bed = pick_box_and_bed( [Band(430, 438, 100), Band(500, 510, 90)], [Band(407, 419, 100)], 720, ) self.assertIsNotNone(box) self.assertIsNotNone(bed) self.assertEqual((box.y0, box.y1), (407, 419)) self.assertEqual((bed.y0, bed.y1), (430, 438)) def test_no_dark_band_returns_none(self): box, bed = pick_box_and_bed([], [], 720) self.assertIsNone(box) self.assertIsNone(bed) class EvidenceClassificationTests(unittest.TestCase): def test_a_like_wall_is_state1(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(bed_scene(), ts=0.0) self.assertEqual(result.state, 1, result.to_dict()) self.assertGreaterEqual(result.door_posts, 5) self.assertGreaterEqual(result.wall_opacity, 0.35) self.assertIsNotNone(result.gap_px) self.assertGreater(result.gap_px, 8.0) def test_b_like_deck_is_state2(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(flat_scene(), ts=0.0) self.assertEqual(result.state, 2, result.to_dict()) self.assertLessEqual(result.door_posts, 4) self.assertTrue(result.deck_edge) def test_nearly_full_frame_flatbed_contact_is_state2(self): # 箱底落在 0.885*h(超过 box_bottom_max_ratio=0.78),且箱底下沿 # 与车面亮带贴合(gap=0)。必须仍能识别为 2,并在 5 帧后提交。 tracker = CommitTracker( CommitParams( stable_frames=5, structure_frames=5, gap_px_hard_max=8.0, allow_state2=True, ) ) ev = make( EvidenceV2Params(px_per_m=100.0, require_commit=True), tracker, ) image = flat_contact_scene() results = [ev.analyze(image, ts=i / 15.0, frame_id=i) for i in range(5)] first = results[0] self.assertEqual(first.state, 2, first.to_dict()) self.assertLessEqual(first.door_posts, 4) self.assertTrue(first.deck_edge) self.assertAlmostEqual( -1.0 if first.gap_px is None else first.gap_px, 0.0, places=3 ) self.assertFalse(first.committed) self.assertEqual( first.to_observation(require_commit=True).state, 255, "commit 未满 5 帧时内部应保持 255", ) self.assertTrue(results[-1].committed, results[-1].to_dict()) self.assertEqual( results[-1].to_observation(require_commit=True).state, 2 ) def test_empty_image_is_unknown(self): ev = make(EvidenceV2Params(require_commit=False)) result = ev.analyze(np.zeros((0, 0), dtype=np.uint8)) self.assertEqual(result.state, 255) self.assertEqual(result.abstain_reason, "no_image") def test_blank_image_abstains(self): ev = make(EvidenceV2Params(require_commit=False)) result = ev.analyze(np.full((720, 1280), 128, dtype=np.uint8)) self.assertEqual(result.state, 255) self.assertTrue(result.abstain_reason) def test_dynamic_roi_follows_box_bottom(self): low = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) high = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) r_low = low.analyze(bed_scene(box_bottom=392), ts=0.0) r_high = high.analyze(bed_scene(box_bottom=520), ts=0.0) self.assertGreater(r_low.below_roi[1], 392) self.assertGreater(r_high.below_roi[1], 520) self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1]) def sky_wire_scene() -> np.ndarray: """P0-Q4:天空电线 + 空 C70 车体(512×512,无下采样)。""" h = w = 512 image = np.full((h, w), 200, dtype=np.uint8) for y in (20, 52, 84, 116): image[y:y + 2, :] = 30 image[165:405, :] = 95 for x in range(30, 480, 18): image[175:400, x:x + 5] = 45 for x in range(30, 480, 50): cv2.rectangle(image, (x, 185), (x + 40, 380), 60, 3) image[188:377, x + 3:x + 37] = 110 for dy in range(5, 235, 8): y = 165 + dy image[y:y + 2, 20:492] = 80 for x in range(40, 470, 70): cv2.line(image, (x, 190), (x + 80, 330), 30, 7) image[405:, :] = 140 return image class TextureTopTests(unittest.TestCase): """P0-Q4:天空电线不能把“车体顶”骗到天上。""" def test_sky_wires_are_above_vehicle_top(self): image = sky_wire_scene() window = (int(0.24 * 512), int(0.02 * 512), int(0.78 * 512), int(0.95 * 512)) top = find_texture_top(image, window, EvidenceV2Params()) self.assertGreater(top, 120, "车体顶应落在电线以下") self.assertLess(top, 220, "车体顶不应落到车体中部") def test_empty_c70_outputs_state3(self): # P0-Q9(2026-11-20 客户要求):空车从 255 里摘出来,单独输出 state=3。 # 判据 = texture_top 以下是一整节空敞车侧墙(门板阵列 + 斜撑 + 不透明 + # 横跨整车 + 墙高足够),且没有集装箱证据。 ev = EvidenceV2(EvidenceV2Params(require_commit=False)) result = ev.analyze(sky_wire_scene(), ts=0.0) self.assertEqual(result.state, 3, result.to_dict()) self.assertTrue(result.empty_vehicle, result.to_dict()) self.assertEqual(result.class_reason, "empty_vehicle", result.to_dict()) self.assertEqual(result.abstain_reason, "", result.to_dict()) self.assertGreater(result.texture_top_y or 0.0, 120.0) self.assertNotIn(result.state, (1, 2), result.to_dict()) def test_plain_sky_has_no_vehicle_top(self): image = np.full((720, 1280), 200, dtype=np.uint8) for y in (40, 90, 140): image[y:y + 2, :] = 30 window = (int(0.24 * 1280), int(0.02 * 720), int(0.78 * 1280), int(0.95 * 720)) self.assertLess(find_texture_top(image, window, EvidenceV2Params()), 0) class EmptyVehicleTests(unittest.TestCase): """P0-Q9:空车(敞车、车斗内无箱)单独输出 state=3,且绝不误伤载车/地面。""" def test_empty_gondola_is_state3_and_commits(self): ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6), CommitTracker(CommitParams(stable_frames=3, structure_frames=3))) last = None for i in range(6): last = ev.analyze(sky_wire_scene(), ts=i * 0.1) self.assertIsNotNone(last) self.assertEqual(last.state, 3, last.to_dict()) self.assertTrue(last.committed, last.to_dict()) self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 3) def test_bed_with_container_stays_state1(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(bed_scene(), ts=0.0) self.assertEqual(result.state, 1, result.to_dict()) self.assertFalse(result.empty_vehicle, result.to_dict()) def test_flatbed_with_container_stays_state2(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(flat_scene(), ts=0.0) self.assertEqual(result.state, 2, result.to_dict()) self.assertFalse(result.empty_vehicle, result.to_dict()) def test_ground_never_state3(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) for image in (ground_scene(), thick_contact_scene(), stacked_scene()): result = ev.analyze(image, ts=0.0) self.assertNotEqual(result.state, 3, result.to_dict()) self.assertFalse(result.empty_vehicle, result.to_dict()) def test_allow_state3_off_recognizes_but_does_not_commit(self): params = EvidenceV2Params(px_per_m=115.6, require_commit=True, allow_state3=False) ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6, require_commit=False), CommitTracker(CommitParams(stable_frames=2, structure_frames=2, allow_state3=False))) last = None for i in range(6): last = ev.analyze(sky_wire_scene(), ts=i * 0.1) self.assertIsNotNone(last) self.assertEqual(last.state, 3, last.to_dict()) self.assertFalse(last.committed, last.to_dict()) self.assertEqual(last.commit_reason, "state3_disabled", last.to_dict()) self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 255) self.assertTrue(params.require_commit) class EmptyFlatbedTests(unittest.TestCase): """P0-Q10:空平车(车面裸露)也输出 3;载车/地面绝不落 3。""" def test_empty_flatbed_is_state3_and_commits(self): ev = EvidenceV2(EvidenceV2Params(px_per_m=115.6), CommitTracker(CommitParams(stable_frames=3, structure_frames=3))) last = None for i in range(6): last = ev.analyze(empty_flatbed_scene(), ts=i * 0.1) self.assertIsNotNone(last) self.assertEqual(last.state, 3, last.to_dict()) self.assertEqual(last.class_reason, "empty_flatbed", last.to_dict()) self.assertTrue(last.committed, last.to_dict()) self.assertEqual(last.to_observation(ts=0.6, require_commit=True).state, 3) def test_flatcar_with_container_is_not_empty(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) for image in (flat_scene(), flat_contact_scene()): result = ev.analyze(image, ts=0.0) self.assertNotEqual(result.state, 3, result.to_dict()) self.assertFalse(result.empty_vehicle, result.to_dict()) def test_ground_and_stack_never_empty_flatbed(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) for image in (ground_scene(), thick_contact_scene(), stacked_scene()): result = ev.analyze(image, ts=0.0) self.assertNotEqual(result.state, 3, result.to_dict()) def test_flatbed_gate_can_be_disabled(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False, empty_flatbed_enable=False)) result = ev.analyze(empty_flatbed_scene(), ts=0.0) self.assertNotEqual(result.state, 3, result.to_dict()) def test_no_under_deck_void_is_not_empty_flatbed(self): # 边梁下方没有车底透空(月台边缘/挡墙/道砟堆)→ 不得判 3 ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(empty_flatbed_no_void_scene(), ts=0.0) self.assertNotEqual(result.state, 3, result.to_dict()) self.assertFalse(result.empty_vehicle, result.to_dict()) def test_flatbed_summary_carries_reason(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(empty_flatbed_scene(), ts=0.0) self.assertEqual(result.class_reason, "empty_flatbed", result.to_dict()) self.assertEqual(result.diagnostics.get("empty_reason"), "empty_flatbed", result.diagnostics) class HoistBlocksTypeTests(unittest.TestCase): """P0-Q11:作业帧(吊具高悬 / 吊具仍夹箱)**绝不判车型**。 实拍根因:`root_test1`(正面吊司机视角,吊具吊着箱悬在平车上方)里 “吊具横梁 + 箱体侧壁”被空车判据当成敞车侧墙(posts=9 span=0.95)→ 误判 3。 """ def test_hoist_high_blocks_empty_vehicle_state3(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(sky_wire_scene(), ts=0.0, hoist_high=True) self.assertNotEqual(result.state, 3, result.to_dict()) self.assertTrue(result.hoist_high, result.to_dict()) self.assertEqual(result.class_reason, "hoist_high", result.to_dict()) def test_hoist_high_blocks_flatbed_state2(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(flat_scene(), ts=0.0, hoist_high=True) self.assertNotEqual(result.state, 2, result.to_dict()) self.assertTrue(result.hoist_high, result.to_dict()) def test_without_hoist_same_scene_still_judges(self): # 同样的画面,没有吊具信号时仍应正常判 3(门只拦作业帧,不误伤空车) ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) result = ev.analyze(sky_wire_scene(), ts=0.0) self.assertEqual(result.state, 3, result.to_dict()) class GroundStackSafetyTests(unittest.TestCase): """P0-Q3:地面/堆料/堆叠箱不得被判成 1(敞车)或 2(平车)。""" def _classify(self, image: np.ndarray): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) return ev.analyze(image, ts=0.0) def test_box_on_ground_is_never_bed_or_flatbed(self): result = self._classify(ground_scene()) self.assertNotIn(result.state, (1, 2), result.to_dict()) def test_thick_contact_plane_is_not_flatbed(self): # 箱底紧贴一块厚亮面(地面/下层箱顶/月台)→ 旧版 flat_contact 会判 2 result = self._classify(thick_contact_scene()) self.assertNotIn(result.state, (1, 2), result.to_dict()) self.assertFalse(result.deck_edge, result.to_dict()) def test_container_stacked_on_container_is_not_bed(self): # 下层箱的瓦楞不是车斗门板;下层箱顶也不是车面 result = self._classify(stacked_scene()) self.assertNotIn(result.state, (1, 2), result.to_dict()) class CommitIntegrationTests(unittest.TestCase): def test_uncommitted_result_maps_to_internal_255(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=True)) result = ev.analyze(bed_scene(gap_px=18), ts=0.0) self.assertEqual(result.state, 1) self.assertFalse(result.committed) obs = result.to_observation(require_commit=True) self.assertEqual(obs.state, 255) self.assertEqual(obs.confidence, 0.0) self.assertIn("abstain", obs.reason) def test_seated_frames_commit_and_publish_state1(self): tracker = CommitTracker( CommitParams( stable_frames=3, structure_frames=3, gap_px_hard_max=8.0, allow_state2=False, ) ) ev = make( EvidenceV2Params(px_per_m=115.6, require_commit=True), tracker, ) image = bed_scene(gap_px=4) last = None for i in range(4): last = ev.analyze(image, ts=i / 30.0) self.assertIsNotNone(last) self.assertTrue(last.committed, last.to_dict()) obs = last.to_observation(ts=0.2, require_commit=True) self.assertEqual(obs.state, 1) self.assertGreater(obs.confidence, 0.45) def test_injected_hoist_high_blocks_commit(self): tracker = CommitTracker( CommitParams( stable_frames=3, structure_frames=3, gap_px_hard_max=8.0, allow_state2=False, ) ) ev = make( EvidenceV2Params(px_per_m=115.6, require_commit=True), tracker, ) image = bed_scene(gap_px=4) last = None for i in range(6): last = ev.analyze(image, ts=i / 30.0, hoist_high=True) self.assertIsNotNone(last) self.assertTrue(last.hoist_high) self.assertFalse(last.committed) self.assertEqual(last.commit_reason, "hoist_high") self.assertEqual(last.abstain_reason, "hoist_high") obs = last.to_observation(require_commit=True) self.assertEqual(obs.state, 255) self.assertIn("hoist_high", obs.reason) def test_detect_hoist_high_finds_dark_bar_with_bright_sky_below(self): from portcv.logic.evidence_v2 import detect_hoist_high image = np.full((720, 1280), 185, dtype=np.uint8) image[40:140, :] = 25 # 上方吊具/臂架暗带 image[140:300, :] = 185 # 暗带下方天空/箱顶更亮 hoist, cues = detect_hoist_high(image, 300) self.assertTrue(hoist, cues) self.assertGreaterEqual(cues["horizontal_lines"], 1) def test_detect_hoist_high_ignores_uniform_scene(self): from portcv.logic.evidence_v2 import detect_hoist_high image = np.full((720, 1280), 150, dtype=np.uint8) hoist, cues = detect_hoist_high(image, 300) self.assertFalse(hoist, cues) self.assertEqual(cues["horizontal_lines"], 0) def test_spreader_contact_detects_dark_bar_on_container_top(self): from portcv.logic.evidence_v2 import detect_spreader_contact image = np.full((500, 600), 180, dtype=np.uint8) image[100:140, 100:500] = 30 # 吊具横梁紧贴箱顶 image[140:450, 100:500] = 150 # 箱体 hit, cues = detect_spreader_contact(image, (100, 140, 500, 450)) self.assertTrue(hit, cues) self.assertGreaterEqual(cues["dark_run_px"], 20) def test_spreader_contact_ignores_plain_container_top(self): from portcv.logic.evidence_v2 import detect_spreader_contact image = np.full((500, 600), 180, dtype=np.uint8) image[140:450, 100:500] = 150 hit, cues = detect_spreader_contact(image, (100, 140, 500, 450)) self.assertFalse(hit, cues) def test_classify_only_mode_publishes_candidate(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) obs = ev.classify(bed_scene(), ts=0.0, frame_id=1) self.assertEqual(obs.state, 1) self.assertGreater(obs.confidence, 0.45) class VehicleOnlyTests(unittest.TestCase): """箱底被车帮挡住(罐箱)时“只看车体”判敞车(P0-Q6)。 现场来源:`04_container_on_gondola.png`(MLGU 350584 罐箱坐在敞车上, 箱底被车帮完全挡住)——旧实现直接 `no_box` 弃权,用户要求“罐箱也要输出”。 C++/Python 判据都是**立柱跨度**(敞车横跨整车 ≥`vehicle_min_span_ratio`, 平车上集装箱波纹只占中间一段)。 注意:**正向用例只能靠现场帧**(`docs/evidence/` 的 4 张图 + A/B 片段), 合成图的大片均匀区会被 `ground_like_ratio` 判成“地面”,`opacity` 上不去, 测不出“检测得到”这件事;这里只锁“没有车体结构时必须弃权、不许猜”。 """ @staticmethod def _no_bands(): from unittest import mock return mock.patch( "portcv.logic.evidence_v2.horizontal_bands", return_value=([], []), ) def test_no_box_without_wall_abstains(self): ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) blank = np.full((720, 1280), 120, dtype=np.uint8) with self._no_bands(): obs = ev.classify(blank, ts=0.0, frame_id=1) self.assertEqual(obs.state, 255, obs.reason) self.assertIn("no_box", obs.reason) def test_no_box_never_guesses_flatbed(self): # 无箱底时只可能给 1 或弃权;**不许**因为“看不清”给平车 2。 ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False)) blank = np.full((720, 1280), 120, dtype=np.uint8) with self._no_bands(): obs = ev.classify(blank, ts=0.0, frame_id=1) self.assertNotEqual(obs.state, 2, obs.reason) class PipelineAndConfigTests(unittest.TestCase): def test_pipeline_uses_evidence_v2_when_enabled(self): cfg = Config( { "run": {"backend": "mock"}, "evidence_v2": { "enabled": True, "px_per_m": 115.6, "require_commit": False, }, } ) pipeline = VisionPipeline(cfg) self.assertIsNotNone(pipeline.evidence_v2) observation, _decision = pipeline.step( Frame(bed_scene(), ts=0.0, frame_id=1) ) self.assertEqual(observation.state, 1, observation.reason) def test_pipeline_keeps_legacy_path_by_default(self): cfg = Config({"run": {"backend": "mock"}}) pipeline = VisionPipeline(cfg) self.assertIsNone(pipeline.evidence_v2) def test_site_template_loads_and_backend_alias_resolves(self): path = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "configs", "edge-v2-front.json", ) cfg = load_config(path) self.assertTrue(bool(cfg.get_path("evidence_v2.enabled"))) self.assertTrue(bool(cfg.get_path("evidence_v2.allow_state2"))) self.assertTrue(bool(cfg.get_path("evidence_v2.commit.allow_state2"))) self.assertEqual(resolve_backend(cfg.get_path("run.backend")), "mock") class ClassifyParityTests(unittest.TestCase): """Python ``_classify`` 与 C++ ``EdgeV2::classify`` 的同构门。 「参考实现调好的参数搬到现场 C++ 结论会变」是最难排查的一类问题, 所以两侧的门必须一一对应(C++ 侧对应断言在 ``cpp/tests/selftest_edge_v2.cpp``): * ``min_bed_roi_px``:箱底以下 ROI 太矮 → 不判 1(``bed_roi_small``); * ``relaxed_post_array``:posts=min-1 但侧墙不透明且间距规则 → 仍判 1; * ``prefer_bed_on_conflict``:上述放宽形态与车面边梁同时成立 → 优先 1; * ``post_array_regular``:≥8 根且间距 CV>1.5 视为杂波 → 不判 1。 """ @staticmethod def _classify(params=None, **kwargs): from portcv.schema import ViewMode ev = make(params or EvidenceV2Params()) base = dict( posts=6, spacing_cv=0.3, opacity=0.6, ground=0.2, deck=False, wheels=0, gap_px=20.0, motion_ok=True, view=ViewMode.FRONT, under_deck=False, post_spacing_px=80.0, diagonal_braces=2, post_span_ratio=0.6, below_roi_h_px=300.0, ) base.update(kwargs) return ev._classify(**base) def test_bed_roi_too_small_abstains(self): state, _, _, reason = self._classify(below_roi_h_px=40.0) self.assertEqual(state, 255) self.assertEqual(reason, "bed_roi_small") def test_relaxed_post_array_is_bed(self): state, _, _, reason = self._classify( posts=4, opacity=0.70, spacing_cv=0.5) self.assertEqual(state, 1, reason) self.assertEqual(reason, "wall_posts") def test_conflict_prefers_bed_when_relaxed(self): # 4 根 + 不透明 + 间距规则 → 既满足放宽门板阵列,又命中车面边梁; # 与 C++ 一致:按门板阵列优先,不因"冲突"弃权。 state, _, _, reason = self._classify( posts=4, opacity=0.70, spacing_cv=0.5, deck=True, under_deck=True) self.assertEqual(state, 1, reason) def test_conflict_abstains_when_not_relaxed(self): # min_door_posts=3 / flat_max_door_posts=4:3 根就走正常门板门, # 与车面边梁同时成立 → conflict_1_2(与 C++ 同分支)。 params = EvidenceV2Params(min_door_posts=3, flat_max_door_posts=4) state, _, _, reason = self._classify( params=params, posts=3, deck=True, under_deck=True) self.assertEqual(state, 255) self.assertEqual(reason, "conflict_1_2") def test_irregular_post_array_is_not_bed(self): state, _, _, reason = self._classify( posts=9, spacing_cv=1.9, opacity=0.8) self.assertNotEqual(state, 1, reason) def test_state2_needs_under_deck(self): state, _, _, reason = self._classify( posts=0, deck=True, under_deck=False, post_span_ratio=0.0) self.assertEqual(state, 255) self.assertEqual(reason, "weak_evidence") state2, _, _, _ = self._classify( posts=0, deck=True, under_deck=True, post_span_ratio=0.0) self.assertEqual(state2, 2) if __name__ == "__main__": unittest.main()