// portcv 边缘几何证据自检 —— **新增**、独立于既有 161 项自检(不动既有用例,见 README §2)。 // // 运行: // ctest --test-dir build -R portcv_edge_selftest --output-on-failure // ./build/portcv_edge_selftest // // 覆盖(与 docs/edge_evidence.md 章节对应): // [1] 图像算子(§3.1):缩放 / 中值 / 高斯 / 分位数 / Sobel / 盒式模糊 / CLAHE / 多边形填充 // [2] 线段(§3.2 / §3.5):Canny-lite、连通域拟合、共线合并、越界比例、角度工具 // [3] 自标尺与箱体轮廓(§1.3 / §3.2):近端竖棱 ↔ px_per_m,与"解析投影值"对拍 // [4] 合成场景回归(§9.1 ①):敞车 → `1`;平板车 → `2`;箱在地面 → `0` // [5] 安全铁律(§0 / §2.3 / §5):allow_state2、40 尺近满车、雪 / 夜降质、空车 → **绝不误报 `2`** // [6] 运动门控(§6):平移 / 模糊 / 静止 / 超时 // [7] 与规范一致性:`EdgeParams` 默认值逐项对拍 §7;诊断字(§10);flags 位(§10) // [8] `Detector` 适配(§10):`Frame.gray` 为空 / 非空两条路径 // // 说明:断言描述用 ASCII(GBK 控制台下中文会乱码,影响现场排错),源码注释保持中文。 #include #include #include #include #include #include #include "portcv/edge_evidence.hpp" #include "portcv/edge_image.hpp" #include "portcv/edge_lines.hpp" #include "portcv/edge_synth.hpp" #include "portcv/schema.hpp" namespace { int g_pass = 0; int g_fail = 0; void check(bool ok, const std::string& what) { if (ok) { ++g_pass; std::printf(" [OK] %s\n", what.c_str()); } else { ++g_fail; std::printf(" [FAIL] %s\n", what.c_str()); } } void check_eq(long long got, long long want, const std::string& what) { if (got == want) { ++g_pass; std::printf(" [OK] %s (=%lld)\n", what.c_str(), got); } else { ++g_fail; std::printf(" [FAIL] %s: got=%lld want=%lld\n", what.c_str(), got, want); } } void check_near(double got, double want, double tol, const std::string& what) { if (std::fabs(got - want) <= tol) { ++g_pass; std::printf(" [OK] %s (%.4f)\n", what.c_str(), got); } else { ++g_fail; std::printf(" [FAIL] %s: got=%.4f want=%.4f tol=%.4f\n", what.c_str(), got, want, tol); } } // ---------------------------------------------------------------- 合成场景预设 portcv::SynthCamera test_camera() { portcv::SynthCamera cam; cam.width = 960; // 与 edge.work_width 一致 → 预处理不做缩放,自检更快 cam.height = 540; cam.f_px = 900.0; cam.height_m = 5.4; // 相机装在自车车体(≈2 倍箱高) cam.lateral_m = 1.8; // 在线路中心左侧 cam.forward_m = 16.0; // 与现场取景接近:箱高 ≈170~250 px、箱宽 ≈28% 画面宽;箱底下方留出车底空隙 return cam; } /// 敞车(C70):车底板 1.25 m + 围挡 1.80 m(上缘 ≈ 0.70 箱高,与现场口径一致)。 portcv::SynthScene gondola_scene(double lift_m) { portcv::SynthScene s; s.wagon = true; s.gondola = true; s.has_box = true; s.box_lift_m = lift_m; s.deck_height_m = 1.25; s.wall_height_m = 1.80; return s; } /// 平板车(X70):车底板 1.10 m、无围挡,箱直接坐在车面板上。 portcv::SynthScene flatbed_scene(double box_len_m) { portcv::SynthScene s; s.wagon = true; s.gondola = false; s.has_box = true; s.box_len_m = box_len_m; s.deck_height_m = 1.10; return s; } /// 箱在地面 / 堆场(无车体)。 portcv::SynthScene ground_scene() { portcv::SynthScene s; s.wagon = false; s.gondola = false; s.has_box = true; return s; } portcv::EdgeResult run_scene(const portcv::SynthCamera& cam, const portcv::SynthScene& scene, const portcv::EdgeParams& params = portcv::EdgeParams(), double ts = 1.0) { portcv::EdgeEvidence evidence(params); if (std::getenv("PORTCV_EDGE_TRACE") != nullptr) { std::fprintf(stderr, "\n=== RUN wagon=%d gondola=%d has_box=%d lift=%.2f len=%.2f rails=%d " "exp=%.2f contrast=%.2f noise=%.1f ===\n", scene.wagon ? 1 : 0, scene.gondola ? 1 : 0, scene.has_box ? 1 : 0, scene.box_lift_m, scene.box_len_m, scene.ground_rails ? 1 : 0, scene.exposure, scene.contrast, scene.noise); } const portcv::GrayImage img = portcv::render_synthetic(cam, scene); return evidence.analyze(img, ts); } /// 打印一帧结论(现场排错用:state / 置信度 / 证据 / 诊断)。 void report(const char* tag, const portcv::EdgeResult& r) { if (std::getenv("PORTCV_EDGE_TRACE") != nullptr) { std::fprintf(stderr, "\n=== SCENE %s ===\n", tag); } std::printf(" %-26s state=%3d conf=%.2f %s\n", tag, r.state, r.confidence, r.evidence_summary().c_str()); } // ---------------------------------------------------------------- [1] 图像算子 void test_image_ops() { std::printf("[1] image operators (spec 3.1)\n"); portcv::GrayImage img(1280, 720, 100); double scale = 0.0; const portcv::GrayImage small = portcv::resize_long_side(img, 960, &scale); check_eq(small.width, 960, "resize_long_side width"); check_eq(small.height, 540, "resize_long_side height"); check_near(scale, 0.75, 1e-9, "resize scale"); portcv::GrayImage dot(9, 9, 100); dot.set(4, 4, 255); portcv::median3x3_inplace(&dot); check_eq(dot.at(4, 4), 100, "median3x3 removes single hot pixel"); portcv::GrayImage uniform(8, 8, 77); portcv::gaussian3x3_inplace(&uniform); check_eq(uniform.at(4, 4), 77, "gaussian3x3 keeps uniform image"); portcv::GrayImage two(10, 1, 0); for (int x = 5; x < 10; ++x) { two.set(x, 0, 200); } check_eq(portcv::percentile_u8(two, 0.0), 0, "percentile p0"); check_eq(portcv::percentile_u8(two, 0.9), 200, "percentile p90"); // 竖直台阶边:Sobel 在台阶处给大幅值,且该列 gy ≈ 0(纯竖直边) portcv::GrayImage edge(32, 8, 40); for (int y = 0; y < 8; ++y) { for (int x = 16; x < 32; ++x) { edge.set(x, y, 210); } } const portcv::SobelResult grad = portcv::sobel(edge); double max_mag = 0.0; for (float m : grad.mag) { max_mag = std::max(max_mag, static_cast(m)); } check(max_mag > 300.0, "sobel high magnitude on step edge"); check_near(grad.gy[static_cast(4) * 32 + 15], 0.0, 1e-6, "sobel gy==0 on vertical edge"); portcv::GrayImage blurred = edge; portcv::box_blur_inplace(&blurred, 4); const portcv::SobelResult grad2 = portcv::sobel(blurred); double max_mag2 = 0.0; for (float m : grad2.mag) { max_mag2 = std::max(max_mag2, static_cast(m)); } check(max_mag2 < max_mag, "box blur lowers max gradient"); portcv::GrayImage lowc(64, 64, 120); for (int y = 0; y < 64; ++y) { for (int x = 0; x < 64; ++x) { lowc.set(x, y, static_cast(120 + (x % 4))); } } const double spread_before = static_cast(portcv::percentile_u8(lowc, 0.95)) - static_cast(portcv::percentile_u8(lowc, 0.05)); portcv::clahe_lite_inplace(&lowc, 8, 3.0); const double spread_after = static_cast(portcv::percentile_u8(lowc, 0.95)) - static_cast(portcv::percentile_u8(lowc, 0.05)); check(spread_after > spread_before, "clahe increases local contrast spread"); portcv::GrayImage poly(40, 40, 0); portcv::fill_polygon_aa(&poly, {{5.0, 5.0}, {35.0, 5.0}, {35.0, 35.0}, {5.0, 35.0}}, 200.0); check_eq(poly.at(20, 20), 200, "fill_polygon_aa fills interior"); check_eq(poly.at(1, 1), 0, "fill_polygon_aa keeps exterior"); } // ---------------------------------------------------------------- [2] 线段 void test_lines() { std::printf("[2] line segments (spec 3.2 / 3.5)\n"); const double kPi = 3.14159265358979323846; portcv::GrayImage img(240, 240, 60); const double x0 = 40.0; const double y0 = 200.0; const double len = 150.0; const double ang = 30.0 * kPi / 180.0; const double x1 = x0 + len * std::cos(ang); const double y1 = y0 - len * std::sin(ang); portcv::draw_line_aa(&img, x0, y0, x1, y1, 220.0, 3.0); const portcv::SobelResult grad = portcv::sobel(img); const std::vector edges = portcv::canny_lite(img, grad, 0.90, 0.97); int edge_count = 0; for (uint8_t e : edges) { edge_count += e ? 1 : 0; } check(edge_count > 100, "canny_lite finds the drawn line"); portcv::LineParams lp; float strength = 0.0f; const std::vector segs = portcv::extract_segments(img, grad, edges, lp, &strength); const portcv::Segment* best = nullptr; for (const portcv::Segment& s : segs) { if (best == nullptr || s.length > best->length) { best = &s; } } check(segs.size() >= 1 && best != nullptr, "segment extracted"); if (best != nullptr) { // 图像 y 轴向下:这里画的是"向右上"的线 → 方向角应为 **-30°**(不是 +30°)。 check_near(best->angle_deg, -30.0, 4.0, "segment angle ~-30 deg (image y points down)"); check_near(best->length, len, 0.20 * len, "segment length ~ drawn length"); check(best->contrast > 30.0, "segment contrast reflects the bright line"); } // 角度差 = 无向直线的最小夹角(0..90),折返点在 ±90°(不是 90° 处"归零"!): // 若把它定义成 mod 90(即"垂直也算同向"),P1(轨向线)与 P2(跨轨向线)就再也分不开了 // → §2.2 的车斗判据直接失效。所以这里显式钉住"垂直 = 90°"的语义。 check_near(portcv::angle_diff_deg(80.0, -80.0), 20.0, 1e-9, "angle_diff wraps at the +-90 deg boundary"); check_near(portcv::angle_diff_deg(170.0, 10.0), 20.0, 1e-9, "angle_diff wraps across 180 deg"); check_near(portcv::angle_diff_deg(0.0, 90.0), 90.0, 1e-9, "perpendicular lines stay 90 deg apart (P1/P2 distinguishable)"); check_near(portcv::angle_diff_deg(-85.0, 85.0), 10.0, 1e-9, "angle_diff across -90/90"); portcv::Segment half; half.x1 = 0.0; half.y1 = 0.0; half.x2 = 100.0; half.y2 = 0.0; half.length = 100.0; const std::vector quad = {{0.0, 0.0}, {50.0, 0.0}, {50.0, 50.0}, {0.0, 50.0}}; check_near(portcv::outside_ratio(half, quad), 0.5, 0.05, "outside_ratio ~0.5"); // L 形连通域 → 必须拆成"横向 + 竖向"两条(箱角 / 车帮拐角就是这种形状) portcv::GrayImage corner(160, 160, 60); portcv::draw_line_aa(&corner, 40.0, 40.0, 120.0, 40.0, 220.0, 3.0); portcv::draw_line_aa(&corner, 120.0, 40.0, 120.0, 130.0, 220.0, 3.0); const portcv::SobelResult g2 = portcv::sobel(corner); const std::vector e2 = portcv::canny_lite(corner, g2, 0.90, 0.97); const std::vector s2 = portcv::extract_segments(corner, g2, e2, lp, nullptr); bool horiz = false; bool vert = false; for (const portcv::Segment& s : s2) { if (std::fabs(s.angle_deg) < 6.0 && s.length > 60.0) { horiz = true; } if (std::fabs(s.angle_deg) > 84.0 && s.length > 60.0) { vert = true; } } check(horiz && vert, "corner blob split into horizontal + vertical segments"); // 共线断开(间隙 8 px)→ 合并成一条长线 portcv::GrayImage broken(320, 120, 60); portcv::draw_line_aa(&broken, 30.0, 60.0, 130.0, 60.0, 220.0, 3.0); portcv::draw_line_aa(&broken, 138.0, 60.0, 290.0, 60.0, 220.0, 3.0); const portcv::SobelResult g3 = portcv::sobel(broken); const std::vector e3 = portcv::canny_lite(broken, g3, 0.90, 0.97); const std::vector s3 = portcv::extract_segments(broken, g3, e3, lp, nullptr); double longest = 0.0; for (const portcv::Segment& s : s3) { longest = std::max(longest, s.length); } check(longest > 220.0, "collinear gap merged into one long segment"); // ② **专用竖直游程通道**(§3.2 ① 补充)—— 自标尺分母的唯一稳定来源。 // 场景:240 px 竖棱 + 一条贯穿全场的斜线(模拟 30° 钢轨干扰项)。 // 通用通道在"箱体 + 车体 + 地面 + 钢轨连成一块"时会把竖棱切碎;竖直游程按"逐列连续游程" // 找,斜线天然不响应(单列只有几像素)。 portcv::GrayImage vin(320, 320, 60); portcv::draw_line_aa(&vin, 160.0, 40.0, 160.0, 280.0, 220.0, 3.0); // 竖棱 240 px portcv::draw_line_aa(&vin, 10.0, 300.0, 310.0, 120.0, 210.0, 3.0); // 斜线(≈ -31°,干扰项) const portcv::SobelResult gv = portcv::sobel(vin); const std::vector ev = portcv::canny_lite(vin, gv, 0.90, 0.97); const std::vector vr = portcv::extract_vertical_runs(vin, gv, ev, lp, 60.0, 4, nullptr); double vmax = 0.0; double vcontrast = 0.0; bool all_vertical = !vr.empty(); for (const portcv::Segment& s : vr) { vmax = std::max(vmax, s.length); vcontrast = std::max(vcontrast, s.contrast); if (std::fabs(s.angle_deg) < 85.0) { all_vertical = false; } } check(vmax >= 200.0, "vertical-run channel recovers the near edge (>=200 px)"); check(all_vertical, "vertical-run channel is rail-immune (only ~90 deg runs)"); check(vcontrast > 20.0, "vertical-run channel annotates contrast (usable by evidence)"); // 断口容忍:竖棱被横向结构打断(2 处各 14 px)→ 调大 max_gap 即可接回(现场可整定)。 portcv::draw_line_aa(&vin, 140.0, 110.0, 180.0, 110.0, 60.0, 14.0); portcv::draw_line_aa(&vin, 140.0, 210.0, 180.0, 210.0, 60.0, 14.0); const portcv::SobelResult gv2 = portcv::sobel(vin); const std::vector ev2 = portcv::canny_lite(vin, gv2, 0.90, 0.97); const std::vector vr2 = portcv::extract_vertical_runs(vin, gv2, ev2, lp, 60.0, 20, nullptr); double vmax2 = 0.0; for (const portcv::Segment& s : vr2) { vmax2 = std::max(vmax2, s.length); } check(vmax2 >= 200.0, "vertical-run channel bridges notches when max_gap is tuned"); } // ---------------------------------------------------------------- [3] 自标尺与箱体轮廓 double analytic_near_edge_px(const portcv::SynthCamera& cam, const portcv::SynthScene& s) { const portcv::Projector proj = portcv::make_projector(cam, s); const double y_bottom = s.wagon ? (s.deck_height_m + s.box_lift_m) : 0.02; const double z_near = s.box_offset_z_m + 0.5 * s.box_len_m; const double x_face = -0.5 * s.box_width_m; double ax = 0.0; double ay = 0.0; double bx = 0.0; double by = 0.0; proj.project(portcv::v3(x_face, y_bottom, z_near), &ax, &ay); proj.project(portcv::v3(x_face, y_bottom + s.box_height_m, z_near), &bx, &by); return std::hypot(bx - ax, by - ay); } void test_scale(const portcv::SynthCamera& cam) { std::printf("[3] self-scale and box outline (spec 1.3 / 3.2)\n"); const portcv::SynthScene scene = flatbed_scene(6.06); portcv::EdgeEvidence evidence; const portcv::GrayImage img = portcv::render_synthetic(cam, scene); const portcv::EdgeResult r = evidence.analyze(img, 1.0); report("flatbed 20ft", r); check(evidence.last_outline().ok, "box outline built"); check(r.ev.scale_ok, "SCALE_OK=1 when near edge >= near_edge_px (60 px)"); check(r.ev.box_h_px >= 60.0, "box height in pixels >= near_edge_px"); const double expect = analytic_near_edge_px(cam, scene); check(expect > 150.0, "analytic near edge is long enough for this camera setup"); check_near(r.ev.box_h_px, expect, 0.25 * expect, "box height px vs analytic projection"); check_near(r.ev.px_per_m, expect / 2.591, 0.25 * expect / 2.591, "px_per_m vs analytic value"); const portcv::EdgeResult r40 = run_scene(cam, flatbed_scene(12.19)); report("flatbed 40ft", r40); check(r40.ev.box_w_px > r.ev.box_w_px, "40ft box projects wider than 20ft box"); // 远距离(箱高 < near_edge_px)→ SCALE_OK=0(§2.3 ④:只允许 1 或 255) portcv::SynthCamera far_cam = cam; far_cam.forward_m = 60.0; const portcv::EdgeResult rfar = run_scene(far_cam, flatbed_scene(6.06)); report("flatbed 20ft far", rfar); check(!rfar.ev.scale_ok || rfar.ev.box_h_px >= 60.0, "far away: SCALE_OK follows near edge length"); } // ---------------------------------------------------------------- [4] 合成场景回归(§9.1 ①) void test_synthetic_regression(const portcv::SynthCamera& cam) { std::printf("[4] synthetic scene regression (spec 9.1-1)\n"); // 地面 / 堆场用更远的机位:合成场景要给"箱底以下"留出足够像素(真机堆场取景同理)。 portcv::SynthCamera ground_cam = cam; ground_cam.forward_m = 30.0; // 敞车 + 20 尺箱(箱底高出车帮 0.70 m,确保车帮上缘亮带在画面里完整可见) const portcv::EdgeResult g_hover = run_scene(cam, gondola_scene(2.50)); report("gondola 20ft hovering", g_hover); check_eq(g_hover.state, 1, "gondola -> state 1 (bed)"); check(g_hover.ev[portcv::EvidenceKey::C1], "C1 (bright band below box bottom) detected"); check(!g_hover.ev[portcv::EvidenceKey::F2], "no under-frame gap -> F2 false"); check(g_hover.confidence > 0.45, "confidence above the voter threshold"); // 敞车 + 20 尺箱(已落位:箱底被车帮截断 → 自标尺失效,但**仍不得输出 2**) const portcv::EdgeResult g_landed = run_scene(cam, gondola_scene(0.0)); report("gondola 20ft landed", g_landed); check(g_landed.state != 2, "landed gondola never yields state 2 (safety rule)"); check(g_landed.state == 1 || g_landed.state == 255, "landed gondola -> 1 or 255"); // 平板车 + 20 尺箱 → 2(F1 ∧ F2 ∧ F3) const portcv::EdgeResult f20 = run_scene(cam, flatbed_scene(6.06)); report("flatbed 20ft", f20); check_eq(f20.state, 2, "flatbed -> state 2"); check(f20.ev[portcv::EvidenceKey::F1], "F1 low seating line detected"); check(f20.ev[portcv::EvidenceKey::F2], "F2 under-frame gap detected"); check(f20.ev[portcv::EvidenceKey::F3], "F3 no high structure"); check(!f20.ev[portcv::EvidenceKey::C1], "C1 false on flatbed (interlock)"); // 箱在地面 / 堆场 → 0(G1 ∧ G2 且 score_A < 1.0) portcv::SynthScene yard = ground_scene(); yard.ground_rails = false; const portcv::EdgeResult g0 = run_scene(ground_cam, yard); report("box on ground (yard)", g0); check_eq(g0.state, 0, "box on ground -> state 0"); check(g0.ev[portcv::EvidenceKey::G1], "G1 continuous ground"); check(g0.ev[portcv::EvidenceKey::G2], "G2 no crossing line"); // 空敞车 / 空平车(无箱 → 无自标尺 → **不得输出 2**) portcv::SynthScene empty_g = gondola_scene(0.0); empty_g.has_box = false; const portcv::EdgeResult eg = run_scene(cam, empty_g); report("empty gondola", eg); check(eg.state != 2, "empty gondola never yields state 2"); portcv::SynthScene empty_f = flatbed_scene(6.06); empty_f.has_box = false; const portcv::EdgeResult ef = run_scene(cam, empty_f); report("empty flatbed", ef); check(ef.state != 2, "empty flatbed never yields state 2 (no box -> no self scale)"); // 背景杂乱(箱场 / 工地)→ 不得误报 2 portcv::SynthScene clutter = ground_scene(); clutter.background_clutter = true; const portcv::EdgeResult rc = run_scene(ground_cam, clutter); report("box on ground + clutter", rc); check(rc.state != 2, "background clutter never yields state 2"); // ---- 20 尺 / 40 尺**两种箱长都要稳定**(现场两种都会出现;箱高同为 2.591 m, // 所以自标尺基准不随箱长变,但越界带宽度 / 箱长像素会变 → 每类场景都要覆盖)---- portcv::SynthScene gon40 = gondola_scene(1.95); gon40.box_len_m = 12.19; // 40 尺近满车(C70 ≈ 13 m 车长) const portcv::EdgeResult g40 = run_scene(cam, gon40); report("gondola 40ft hovering", g40); check(g40.state != 2, "40ft gondola never yields state 2 (safety rule)"); check(g40.ev.box_h_px >= 60.0, "40ft gondola: box height in pixels >= near_edge_px"); const portcv::EdgeResult f40b = run_scene(cam, flatbed_scene(12.19)); report("flatbed 40ft", f40b); check(f40b.ev.box_h_px >= 60.0, "40ft flatbed: box height in pixels >= near_edge_px"); check(f40b.state != 2 || f40b.ev.out_left_px >= 20.0 || f40b.ev.out_right_px >= 20.0, "40ft flatbed: state 2 only with a usable out-band"); portcv::SynthScene yard20 = ground_scene(); yard20.ground_rails = false; yard20.box_len_m = 6.06; const portcv::EdgeResult g20 = run_scene(ground_cam, yard20); report("box on ground 20ft", g20); check_eq(g20.state, 0, "box on ground 20ft -> state 0"); } // ---------------------------------------------------------------- [5] 安全铁律 void test_safety_rules(const portcv::SynthCamera& cam) { std::printf("[5] safety rules (spec 0 / 2.2 / 2.3 / 5)\n"); // allow_state2 = false(§7 建议:首次上线先只输出 1 / 0 / 255) portcv::EdgeParams p; p.allow_state2 = false; const portcv::EdgeResult f = run_scene(cam, flatbed_scene(6.06), p); report("flatbed, allow_state2=false", f); check(f.state != 2, "allow_state2=false forbids state 2"); // 40 尺近满车(13 m 车 + 12.19 m 箱):只有越界带够宽才允许 2(§5 / §12.8 Q2 ⑤) const portcv::EdgeResult f40 = run_scene(cam, flatbed_scene(12.19)); report("flatbed 40ft near-full", f40); check(f40.state != 2 || f40.ev.out_left_px >= 20.0 || f40.ev.out_right_px >= 20.0, "40ft near-full: state 2 only with a usable out-band"); // 雪天(低对比 + 强噪声)/ 夜间(低照度):优先 255,绝不误报 2(§5 处置表) portcv::SynthScene snow = flatbed_scene(6.06); snow.contrast = 0.45; snow.exposure = 1.15; snow.noise = 6.0; const portcv::EdgeResult rs = run_scene(cam, snow); report("flatbed in snow", rs); check(rs.state != 2, "snow: never false-positive state 2"); portcv::SynthScene night = flatbed_scene(6.06); night.exposure = 0.35; night.noise = 5.0; const portcv::EdgeResult rn = run_scene(cam, night); report("flatbed at night", rn); check(rn.state != 2, "night: never false-positive state 2"); // 弃权是合法输出:低置信度必须被压到 voter 门限附近 if (rs.state == 255) { check(rs.confidence <= 0.25, "abstained frame has low confidence"); } else { check(true, "plain frame kept a positive verdict (allowed)"); } } // ---------------------------------------------------------------- [6] 运动门控(§6) void test_motion_gate(const portcv::SynthCamera& cam) { std::printf("[6] motion gate (spec 6)\n"); const portcv::SynthScene scene = flatbed_scene(6.06); const portcv::GrayImage a = portcv::render_synthetic(cam, scene); const portcv::GrayImage b = portcv::translate_image(a, 24, 0); // 整幅平移 24 px portcv::EdgeEvidence ev; const portcv::EdgeResult r1 = ev.analyze(a, 0.0); check(!r1.ev.motion, "first frame has no reference -> not motion"); const portcv::EdgeResult r2 = ev.analyze(b, 0.1); report("frame shifted 24 px", r2); check(r2.ev.motion, "24 px global shift -> MOTION"); check(r2.ev.hold, "MOTION frame sets hold (verdict must not change)"); check_eq(r2.state, 255, "MOTION frame yields 255 (upper layer keeps previous)"); check_eq(static_cast(r2.ev.diag), 5, "MOTION diag = 5 (spec 10)"); portcv::EdgeEvidence ev2; ev2.analyze(a, 0.0); const portcv::EdgeResult r3 = ev2.analyze(a, 0.1); check(!r3.ev.motion, "identical frames -> no motion"); // 门限的**单位口径**回归:motion_shift_max_px 是原图像素,而互相关在 160×90 缩略图上做。 // 换一档分辨率(640×360 → 缩略倍数 4 而非 8)做同样的 24 px 平移,结论必须不变 —— // 漏了折算时,1280 宽这一档的 6 px 门限会被缩略 8 倍悄悄放宽成 48 px(= 24 px 漏检根因)。 portcv::SynthCamera small_cam = cam; small_cam.width = 640; small_cam.height = 360; const portcv::GrayImage a_s = portcv::render_synthetic(small_cam, scene); portcv::EdgeEvidence ev_s; ev_s.analyze(a_s, 0.0); const portcv::EdgeResult r_s = ev_s.analyze(portcv::translate_image(a_s, 24, 0), 0.1); check(r_s.ev.motion, "24 px shift detected at 640x360 too (threshold unit = original px)"); portcv::SynthScene blur = scene; blur.blur_radius = 8; const portcv::GrayImage c = portcv::render_synthetic(cam, blur); portcv::EdgeEvidence ev3; ev3.analyze(a, 0.0); const portcv::EdgeResult r4 = ev3.analyze(c, 0.1); report("frame with motion blur", r4); check(r4.ev.motion, "heavy motion blur -> MOTION"); portcv::EdgeEvidence ev4; ev4.analyze(a, 0.0); ev4.analyze(b, 0.1); const portcv::EdgeResult r5 = ev4.analyze(portcv::translate_image(a, 30, 0), 2.0); report("third consecutive moving frame", r5); check(r5.ev.motion_held_s >= 1.5, "motion held time accumulates"); check(ev4.motion_gate().timeout(), "motion timeout >= motion_hold_s (1.5 s)"); } // ---------------------------------------------------------------- [7] 与规范一致性 void test_spec_parity() { std::printf("[7] spec parity (spec 7 / 10)\n"); const portcv::EdgeParams p; check_near(p.box_height_m, 2.591, 1e-9, "edge.box_height_m = 2.591 (20ft == 40ft)"); check_near(p.band_high_lo, 0.55, 1e-9, "edge.band_high[0] = 0.55"); check_near(p.band_high_hi, 0.85, 1e-9, "edge.band_high[1] = 0.85"); check_near(p.band_low_lo, 0.00, 1e-9, "edge.band_low[0] = 0.00"); check_near(p.band_low_hi, 0.10, 1e-9, "edge.band_low[1] = 0.10"); check_near(p.gap_band_lo, 0.10, 1e-9, "edge.gap_band[0] = 0.10"); check_near(p.gap_band_hi, 0.45, 1e-9, "edge.gap_band[1] = 0.45"); check_near(p.cross_ratio_lo, 0.10, 1e-9, "edge.cross_ratio[0] = 0.10"); check_near(p.cross_ratio_hi, 0.35, 1e-9, "edge.cross_ratio[1] = 0.35"); check_near(p.line_angle_deg, 8.0, 1e-9, "edge.line_angle_deg = 8"); check_near(p.min_len_track, 0.30, 1e-9, "edge.min_len_track = 0.30"); check_near(p.min_len_cross_px, 20.0, 1e-9, "edge.min_len_cross_px = 20"); check_near(p.min_out_ratio, 0.30, 1e-9, "edge.min_out_ratio = 0.30 (safety: do not lower)"); check_near(p.grad_pct, 0.90, 1e-9, "edge.grad_pct = 0.90"); check_near(p.texture_period_lo, 0.03, 1e-9, "edge.texture_period[0] = 0.03"); check_near(p.texture_period_hi, 0.20, 1e-9, "edge.texture_period[1] = 0.20"); check_near(p.near_edge_px, 60.0, 1e-9, "edge.near_edge_px = 60"); check_near(p.motion_hold_s, 1.5, 1e-9, "edge.motion_hold_s = 1.5"); check(p.allow_state2, "edge.allow_state2 default = true"); // 证据编号(改名 / 改序会让现场统计口径断档,故固定断言) check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::P1)) == "P1", "evidence key P1"); check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::F2)) == "F2", "evidence key F2"); check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::C1)) == "C1", "evidence key C1"); check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::C3)) == "C3", "evidence key C3"); check_eq(static_cast(portcv::EvidenceKey::COUNT), 14, "evidence key count = 14"); check(std::string(portcv::edge_diag_label(portcv::EdgeDiag::CONFLICT)) == "conflict", "diagnostic label (spec 10)"); // §10 的 flags 位:只占 bit8..bit11,不与既有 StatusBits 冲突 const uint16_t add = static_cast( portcv::edge_flags::EDGE_OK | portcv::edge_flags::ABSTAIN | portcv::edge_flags::MOTION | portcv::edge_flags::SCALE_OK); check_eq(add, 0x0F00, "edge flags occupy bits 8..11"); check_eq(add & 0x00FF, 0, "edge flags do not collide with existing StatusBits"); } // ---------------------------------------------------------------- [8] Detector 适配(§10) void test_detector_adapter(const portcv::SynthCamera& cam) { std::printf("[8] Detector adapter (spec 10)\n"); portcv::EdgeEvidenceDetector detector; portcv::Frame frame; frame.width = cam.width; frame.height = cam.height; frame.ts = 1.0; const std::vector none = detector.infer(frame); check(none.empty(), "Frame.gray == nullptr -> no boxes"); check_eq(detector.last_result().state, 255, "no gray image -> 255 (not ready)"); const portcv::GrayImage img = portcv::render_synthetic(cam, flatbed_scene(6.06)); frame.gray = &img; const std::vector boxes = detector.infer(frame); check(boxes.size() >= 2, "boxes = container + wagon class"); bool has_container = false; bool has_flatbed = false; for (const portcv::Box& b : boxes) { if (b.class_name == "container") { has_container = true; } if (b.class_name == "flatbed") { has_flatbed = true; } } check(has_container, "container box emitted (spec 10 naming)"); check(has_flatbed, "flatbed box emitted (spec 10 naming)"); check_eq(detector.last_result().state, 2, "adapter verdict = flatbed"); check(std::string(detector.name()) == "edge-2d", "backend name = edge-2d"); const portcv::Observation obs = detector.last_result().to_observation(3.5, 7); check_eq(obs.state, 2, "to_observation keeps state"); check_near(obs.ts, 3.5, 1e-9, "to_observation keeps timestamp"); check_eq(obs.frame_id, 7, "to_observation keeps frame id"); check(!obs.reason.empty(), "to_observation carries the evidence summary"); } } // namespace int main() { std::printf("portcv edge-evidence selftest (docs/edge_evidence.md)\n"); const portcv::SynthCamera cam = test_camera(); test_image_ops(); test_lines(); test_scale(cam); test_synthetic_regression(cam); test_safety_rules(cam); test_motion_gate(cam); test_spec_parity(); test_detector_adapter(cam); std::printf("\n%d passed / %d failed\n", g_pass, g_fail); return g_fail == 0 ? 0 : 1; }