selftest_edge.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. // portcv 边缘几何证据自检 —— **新增**、独立于既有 161 项自检(不动既有用例,见 README §2)。
  2. //
  3. // 运行:
  4. // ctest --test-dir build -R portcv_edge_selftest --output-on-failure
  5. // ./build/portcv_edge_selftest
  6. //
  7. // 覆盖(与 docs/edge_evidence.md 章节对应):
  8. // [1] 图像算子(§3.1):缩放 / 中值 / 高斯 / 分位数 / Sobel / 盒式模糊 / CLAHE / 多边形填充
  9. // [2] 线段(§3.2 / §3.5):Canny-lite、连通域拟合、共线合并、越界比例、角度工具
  10. // [3] 自标尺与箱体轮廓(§1.3 / §3.2):近端竖棱 ↔ px_per_m,与"解析投影值"对拍
  11. // [4] 合成场景回归(§9.1 ①):敞车 → `1`;平板车 → `2`;箱在地面 → `0`
  12. // [5] 安全铁律(§0 / §2.3 / §5):allow_state2、40 尺近满车、雪 / 夜降质、空车 → **绝不误报 `2`**
  13. // [6] 运动门控(§6):平移 / 模糊 / 静止 / 超时
  14. // [7] 与规范一致性:`EdgeParams` 默认值逐项对拍 §7;诊断字(§10);flags 位(§10)
  15. // [8] `Detector` 适配(§10):`Frame.gray` 为空 / 非空两条路径
  16. //
  17. // 说明:断言描述用 ASCII(GBK 控制台下中文会乱码,影响现场排错),源码注释保持中文。
  18. #include <algorithm>
  19. #include <cmath>
  20. #include <cstdio>
  21. #include <cstdlib>
  22. #include <string>
  23. #include <vector>
  24. #include "portcv/edge_evidence.hpp"
  25. #include "portcv/edge_image.hpp"
  26. #include "portcv/edge_lines.hpp"
  27. #include "portcv/edge_synth.hpp"
  28. #include "portcv/schema.hpp"
  29. namespace {
  30. int g_pass = 0;
  31. int g_fail = 0;
  32. void check(bool ok, const std::string& what) {
  33. if (ok) {
  34. ++g_pass;
  35. std::printf(" [OK] %s\n", what.c_str());
  36. } else {
  37. ++g_fail;
  38. std::printf(" [FAIL] %s\n", what.c_str());
  39. }
  40. }
  41. void check_eq(long long got, long long want, const std::string& what) {
  42. if (got == want) {
  43. ++g_pass;
  44. std::printf(" [OK] %s (=%lld)\n", what.c_str(), got);
  45. } else {
  46. ++g_fail;
  47. std::printf(" [FAIL] %s: got=%lld want=%lld\n", what.c_str(), got, want);
  48. }
  49. }
  50. void check_near(double got, double want, double tol, const std::string& what) {
  51. if (std::fabs(got - want) <= tol) {
  52. ++g_pass;
  53. std::printf(" [OK] %s (%.4f)\n", what.c_str(), got);
  54. } else {
  55. ++g_fail;
  56. std::printf(" [FAIL] %s: got=%.4f want=%.4f tol=%.4f\n", what.c_str(), got, want, tol);
  57. }
  58. }
  59. // ---------------------------------------------------------------- 合成场景预设
  60. portcv::SynthCamera test_camera() {
  61. portcv::SynthCamera cam;
  62. cam.width = 960; // 与 edge.work_width 一致 → 预处理不做缩放,自检更快
  63. cam.height = 540;
  64. cam.f_px = 900.0;
  65. cam.height_m = 5.4; // 相机装在自车车体(≈2 倍箱高)
  66. cam.lateral_m = 1.8; // 在线路中心左侧
  67. cam.forward_m = 16.0; // 与现场取景接近:箱高 ≈170~250 px、箱宽 ≈28% 画面宽;箱底下方留出车底空隙
  68. return cam;
  69. }
  70. /// 敞车(C70):车底板 1.25 m + 围挡 1.80 m(上缘 ≈ 0.70 箱高,与现场口径一致)。
  71. portcv::SynthScene gondola_scene(double lift_m) {
  72. portcv::SynthScene s;
  73. s.wagon = true;
  74. s.gondola = true;
  75. s.has_box = true;
  76. s.box_lift_m = lift_m;
  77. s.deck_height_m = 1.25;
  78. s.wall_height_m = 1.80;
  79. return s;
  80. }
  81. /// 平板车(X70):车底板 1.10 m、无围挡,箱直接坐在车面板上。
  82. portcv::SynthScene flatbed_scene(double box_len_m) {
  83. portcv::SynthScene s;
  84. s.wagon = true;
  85. s.gondola = false;
  86. s.has_box = true;
  87. s.box_len_m = box_len_m;
  88. s.deck_height_m = 1.10;
  89. return s;
  90. }
  91. /// 箱在地面 / 堆场(无车体)。
  92. portcv::SynthScene ground_scene() {
  93. portcv::SynthScene s;
  94. s.wagon = false;
  95. s.gondola = false;
  96. s.has_box = true;
  97. return s;
  98. }
  99. portcv::EdgeResult run_scene(const portcv::SynthCamera& cam, const portcv::SynthScene& scene,
  100. const portcv::EdgeParams& params = portcv::EdgeParams(),
  101. double ts = 1.0) {
  102. portcv::EdgeEvidence evidence(params);
  103. if (std::getenv("PORTCV_EDGE_TRACE") != nullptr) {
  104. std::fprintf(stderr,
  105. "\n=== RUN wagon=%d gondola=%d has_box=%d lift=%.2f len=%.2f rails=%d "
  106. "exp=%.2f contrast=%.2f noise=%.1f ===\n",
  107. scene.wagon ? 1 : 0, scene.gondola ? 1 : 0, scene.has_box ? 1 : 0,
  108. scene.box_lift_m, scene.box_len_m, scene.ground_rails ? 1 : 0,
  109. scene.exposure, scene.contrast, scene.noise);
  110. }
  111. const portcv::GrayImage img = portcv::render_synthetic(cam, scene);
  112. return evidence.analyze(img, ts);
  113. }
  114. /// 打印一帧结论(现场排错用:state / 置信度 / 证据 / 诊断)。
  115. void report(const char* tag, const portcv::EdgeResult& r) {
  116. if (std::getenv("PORTCV_EDGE_TRACE") != nullptr) {
  117. std::fprintf(stderr, "\n=== SCENE %s ===\n", tag);
  118. }
  119. std::printf(" %-26s state=%3d conf=%.2f %s\n", tag, r.state, r.confidence,
  120. r.evidence_summary().c_str());
  121. }
  122. // ---------------------------------------------------------------- [1] 图像算子
  123. void test_image_ops() {
  124. std::printf("[1] image operators (spec 3.1)\n");
  125. portcv::GrayImage img(1280, 720, 100);
  126. double scale = 0.0;
  127. const portcv::GrayImage small = portcv::resize_long_side(img, 960, &scale);
  128. check_eq(small.width, 960, "resize_long_side width");
  129. check_eq(small.height, 540, "resize_long_side height");
  130. check_near(scale, 0.75, 1e-9, "resize scale");
  131. portcv::GrayImage dot(9, 9, 100);
  132. dot.set(4, 4, 255);
  133. portcv::median3x3_inplace(&dot);
  134. check_eq(dot.at(4, 4), 100, "median3x3 removes single hot pixel");
  135. portcv::GrayImage uniform(8, 8, 77);
  136. portcv::gaussian3x3_inplace(&uniform);
  137. check_eq(uniform.at(4, 4), 77, "gaussian3x3 keeps uniform image");
  138. portcv::GrayImage two(10, 1, 0);
  139. for (int x = 5; x < 10; ++x) { two.set(x, 0, 200); }
  140. check_eq(portcv::percentile_u8(two, 0.0), 0, "percentile p0");
  141. check_eq(portcv::percentile_u8(two, 0.9), 200, "percentile p90");
  142. // 竖直台阶边:Sobel 在台阶处给大幅值,且该列 gy ≈ 0(纯竖直边)
  143. portcv::GrayImage edge(32, 8, 40);
  144. for (int y = 0; y < 8; ++y) {
  145. for (int x = 16; x < 32; ++x) { edge.set(x, y, 210); }
  146. }
  147. const portcv::SobelResult grad = portcv::sobel(edge);
  148. double max_mag = 0.0;
  149. for (float m : grad.mag) { max_mag = std::max(max_mag, static_cast<double>(m)); }
  150. check(max_mag > 300.0, "sobel high magnitude on step edge");
  151. check_near(grad.gy[static_cast<std::size_t>(4) * 32 + 15], 0.0, 1e-6,
  152. "sobel gy==0 on vertical edge");
  153. portcv::GrayImage blurred = edge;
  154. portcv::box_blur_inplace(&blurred, 4);
  155. const portcv::SobelResult grad2 = portcv::sobel(blurred);
  156. double max_mag2 = 0.0;
  157. for (float m : grad2.mag) { max_mag2 = std::max(max_mag2, static_cast<double>(m)); }
  158. check(max_mag2 < max_mag, "box blur lowers max gradient");
  159. portcv::GrayImage lowc(64, 64, 120);
  160. for (int y = 0; y < 64; ++y) {
  161. for (int x = 0; x < 64; ++x) { lowc.set(x, y, static_cast<uint8_t>(120 + (x % 4))); }
  162. }
  163. const double spread_before = static_cast<double>(portcv::percentile_u8(lowc, 0.95)) -
  164. static_cast<double>(portcv::percentile_u8(lowc, 0.05));
  165. portcv::clahe_lite_inplace(&lowc, 8, 3.0);
  166. const double spread_after = static_cast<double>(portcv::percentile_u8(lowc, 0.95)) -
  167. static_cast<double>(portcv::percentile_u8(lowc, 0.05));
  168. check(spread_after > spread_before, "clahe increases local contrast spread");
  169. portcv::GrayImage poly(40, 40, 0);
  170. portcv::fill_polygon_aa(&poly, {{5.0, 5.0}, {35.0, 5.0}, {35.0, 35.0}, {5.0, 35.0}}, 200.0);
  171. check_eq(poly.at(20, 20), 200, "fill_polygon_aa fills interior");
  172. check_eq(poly.at(1, 1), 0, "fill_polygon_aa keeps exterior");
  173. }
  174. // ---------------------------------------------------------------- [2] 线段
  175. void test_lines() {
  176. std::printf("[2] line segments (spec 3.2 / 3.5)\n");
  177. const double kPi = 3.14159265358979323846;
  178. portcv::GrayImage img(240, 240, 60);
  179. const double x0 = 40.0;
  180. const double y0 = 200.0;
  181. const double len = 150.0;
  182. const double ang = 30.0 * kPi / 180.0;
  183. const double x1 = x0 + len * std::cos(ang);
  184. const double y1 = y0 - len * std::sin(ang);
  185. portcv::draw_line_aa(&img, x0, y0, x1, y1, 220.0, 3.0);
  186. const portcv::SobelResult grad = portcv::sobel(img);
  187. const std::vector<uint8_t> edges = portcv::canny_lite(img, grad, 0.90, 0.97);
  188. int edge_count = 0;
  189. for (uint8_t e : edges) { edge_count += e ? 1 : 0; }
  190. check(edge_count > 100, "canny_lite finds the drawn line");
  191. portcv::LineParams lp;
  192. float strength = 0.0f;
  193. const std::vector<portcv::Segment> segs =
  194. portcv::extract_segments(img, grad, edges, lp, &strength);
  195. const portcv::Segment* best = nullptr;
  196. for (const portcv::Segment& s : segs) {
  197. if (best == nullptr || s.length > best->length) { best = &s; }
  198. }
  199. check(segs.size() >= 1 && best != nullptr, "segment extracted");
  200. if (best != nullptr) {
  201. // 图像 y 轴向下:这里画的是"向右上"的线 → 方向角应为 **-30°**(不是 +30°)。
  202. check_near(best->angle_deg, -30.0, 4.0, "segment angle ~-30 deg (image y points down)");
  203. check_near(best->length, len, 0.20 * len, "segment length ~ drawn length");
  204. check(best->contrast > 30.0, "segment contrast reflects the bright line");
  205. }
  206. // 角度差 = 无向直线的最小夹角(0..90),折返点在 ±90°(不是 90° 处"归零"!):
  207. // 若把它定义成 mod 90(即"垂直也算同向"),P1(轨向线)与 P2(跨轨向线)就再也分不开了
  208. // → §2.2 的车斗判据直接失效。所以这里显式钉住"垂直 = 90°"的语义。
  209. check_near(portcv::angle_diff_deg(80.0, -80.0), 20.0, 1e-9,
  210. "angle_diff wraps at the +-90 deg boundary");
  211. check_near(portcv::angle_diff_deg(170.0, 10.0), 20.0, 1e-9, "angle_diff wraps across 180 deg");
  212. check_near(portcv::angle_diff_deg(0.0, 90.0), 90.0, 1e-9,
  213. "perpendicular lines stay 90 deg apart (P1/P2 distinguishable)");
  214. check_near(portcv::angle_diff_deg(-85.0, 85.0), 10.0, 1e-9, "angle_diff across -90/90");
  215. portcv::Segment half;
  216. half.x1 = 0.0;
  217. half.y1 = 0.0;
  218. half.x2 = 100.0;
  219. half.y2 = 0.0;
  220. half.length = 100.0;
  221. const std::vector<portcv::PointF> quad = {{0.0, 0.0}, {50.0, 0.0}, {50.0, 50.0}, {0.0, 50.0}};
  222. check_near(portcv::outside_ratio(half, quad), 0.5, 0.05, "outside_ratio ~0.5");
  223. // L 形连通域 → 必须拆成"横向 + 竖向"两条(箱角 / 车帮拐角就是这种形状)
  224. portcv::GrayImage corner(160, 160, 60);
  225. portcv::draw_line_aa(&corner, 40.0, 40.0, 120.0, 40.0, 220.0, 3.0);
  226. portcv::draw_line_aa(&corner, 120.0, 40.0, 120.0, 130.0, 220.0, 3.0);
  227. const portcv::SobelResult g2 = portcv::sobel(corner);
  228. const std::vector<uint8_t> e2 = portcv::canny_lite(corner, g2, 0.90, 0.97);
  229. const std::vector<portcv::Segment> s2 = portcv::extract_segments(corner, g2, e2, lp, nullptr);
  230. bool horiz = false;
  231. bool vert = false;
  232. for (const portcv::Segment& s : s2) {
  233. if (std::fabs(s.angle_deg) < 6.0 && s.length > 60.0) { horiz = true; }
  234. if (std::fabs(s.angle_deg) > 84.0 && s.length > 60.0) { vert = true; }
  235. }
  236. check(horiz && vert, "corner blob split into horizontal + vertical segments");
  237. // 共线断开(间隙 8 px)→ 合并成一条长线
  238. portcv::GrayImage broken(320, 120, 60);
  239. portcv::draw_line_aa(&broken, 30.0, 60.0, 130.0, 60.0, 220.0, 3.0);
  240. portcv::draw_line_aa(&broken, 138.0, 60.0, 290.0, 60.0, 220.0, 3.0);
  241. const portcv::SobelResult g3 = portcv::sobel(broken);
  242. const std::vector<uint8_t> e3 = portcv::canny_lite(broken, g3, 0.90, 0.97);
  243. const std::vector<portcv::Segment> s3 = portcv::extract_segments(broken, g3, e3, lp, nullptr);
  244. double longest = 0.0;
  245. for (const portcv::Segment& s : s3) { longest = std::max(longest, s.length); }
  246. check(longest > 220.0, "collinear gap merged into one long segment");
  247. // ② **专用竖直游程通道**(§3.2 ① 补充)—— 自标尺分母的唯一稳定来源。
  248. // 场景:240 px 竖棱 + 一条贯穿全场的斜线(模拟 30° 钢轨干扰项)。
  249. // 通用通道在"箱体 + 车体 + 地面 + 钢轨连成一块"时会把竖棱切碎;竖直游程按"逐列连续游程"
  250. // 找,斜线天然不响应(单列只有几像素)。
  251. portcv::GrayImage vin(320, 320, 60);
  252. portcv::draw_line_aa(&vin, 160.0, 40.0, 160.0, 280.0, 220.0, 3.0); // 竖棱 240 px
  253. portcv::draw_line_aa(&vin, 10.0, 300.0, 310.0, 120.0, 210.0, 3.0); // 斜线(≈ -31°,干扰项)
  254. const portcv::SobelResult gv = portcv::sobel(vin);
  255. const std::vector<uint8_t> ev = portcv::canny_lite(vin, gv, 0.90, 0.97);
  256. const std::vector<portcv::Segment> vr =
  257. portcv::extract_vertical_runs(vin, gv, ev, lp, 60.0, 4, nullptr);
  258. double vmax = 0.0;
  259. double vcontrast = 0.0;
  260. bool all_vertical = !vr.empty();
  261. for (const portcv::Segment& s : vr) {
  262. vmax = std::max(vmax, s.length);
  263. vcontrast = std::max(vcontrast, s.contrast);
  264. if (std::fabs(s.angle_deg) < 85.0) { all_vertical = false; }
  265. }
  266. check(vmax >= 200.0, "vertical-run channel recovers the near edge (>=200 px)");
  267. check(all_vertical, "vertical-run channel is rail-immune (only ~90 deg runs)");
  268. check(vcontrast > 20.0, "vertical-run channel annotates contrast (usable by evidence)");
  269. // 断口容忍:竖棱被横向结构打断(2 处各 14 px)→ 调大 max_gap 即可接回(现场可整定)。
  270. portcv::draw_line_aa(&vin, 140.0, 110.0, 180.0, 110.0, 60.0, 14.0);
  271. portcv::draw_line_aa(&vin, 140.0, 210.0, 180.0, 210.0, 60.0, 14.0);
  272. const portcv::SobelResult gv2 = portcv::sobel(vin);
  273. const std::vector<uint8_t> ev2 = portcv::canny_lite(vin, gv2, 0.90, 0.97);
  274. const std::vector<portcv::Segment> vr2 =
  275. portcv::extract_vertical_runs(vin, gv2, ev2, lp, 60.0, 20, nullptr);
  276. double vmax2 = 0.0;
  277. for (const portcv::Segment& s : vr2) { vmax2 = std::max(vmax2, s.length); }
  278. check(vmax2 >= 200.0, "vertical-run channel bridges notches when max_gap is tuned");
  279. }
  280. // ---------------------------------------------------------------- [3] 自标尺与箱体轮廓
  281. double analytic_near_edge_px(const portcv::SynthCamera& cam, const portcv::SynthScene& s) {
  282. const portcv::Projector proj = portcv::make_projector(cam, s);
  283. const double y_bottom = s.wagon ? (s.deck_height_m + s.box_lift_m) : 0.02;
  284. const double z_near = s.box_offset_z_m + 0.5 * s.box_len_m;
  285. const double x_face = -0.5 * s.box_width_m;
  286. double ax = 0.0;
  287. double ay = 0.0;
  288. double bx = 0.0;
  289. double by = 0.0;
  290. proj.project(portcv::v3(x_face, y_bottom, z_near), &ax, &ay);
  291. proj.project(portcv::v3(x_face, y_bottom + s.box_height_m, z_near), &bx, &by);
  292. return std::hypot(bx - ax, by - ay);
  293. }
  294. void test_scale(const portcv::SynthCamera& cam) {
  295. std::printf("[3] self-scale and box outline (spec 1.3 / 3.2)\n");
  296. const portcv::SynthScene scene = flatbed_scene(6.06);
  297. portcv::EdgeEvidence evidence;
  298. const portcv::GrayImage img = portcv::render_synthetic(cam, scene);
  299. const portcv::EdgeResult r = evidence.analyze(img, 1.0);
  300. report("flatbed 20ft", r);
  301. check(evidence.last_outline().ok, "box outline built");
  302. check(r.ev.scale_ok, "SCALE_OK=1 when near edge >= near_edge_px (60 px)");
  303. check(r.ev.box_h_px >= 60.0, "box height in pixels >= near_edge_px");
  304. const double expect = analytic_near_edge_px(cam, scene);
  305. check(expect > 150.0, "analytic near edge is long enough for this camera setup");
  306. check_near(r.ev.box_h_px, expect, 0.25 * expect, "box height px vs analytic projection");
  307. check_near(r.ev.px_per_m, expect / 2.591, 0.25 * expect / 2.591, "px_per_m vs analytic value");
  308. const portcv::EdgeResult r40 = run_scene(cam, flatbed_scene(12.19));
  309. report("flatbed 40ft", r40);
  310. check(r40.ev.box_w_px > r.ev.box_w_px, "40ft box projects wider than 20ft box");
  311. // 远距离(箱高 < near_edge_px)→ SCALE_OK=0(§2.3 ④:只允许 1 或 255)
  312. portcv::SynthCamera far_cam = cam;
  313. far_cam.forward_m = 60.0;
  314. const portcv::EdgeResult rfar = run_scene(far_cam, flatbed_scene(6.06));
  315. report("flatbed 20ft far", rfar);
  316. check(!rfar.ev.scale_ok || rfar.ev.box_h_px >= 60.0, "far away: SCALE_OK follows near edge length");
  317. }
  318. // ---------------------------------------------------------------- [4] 合成场景回归(§9.1 ①)
  319. void test_synthetic_regression(const portcv::SynthCamera& cam) {
  320. std::printf("[4] synthetic scene regression (spec 9.1-1)\n");
  321. // 地面 / 堆场用更远的机位:合成场景要给"箱底以下"留出足够像素(真机堆场取景同理)。
  322. portcv::SynthCamera ground_cam = cam;
  323. ground_cam.forward_m = 30.0;
  324. // 敞车 + 20 尺箱(箱底高出车帮 0.70 m,确保车帮上缘亮带在画面里完整可见)
  325. const portcv::EdgeResult g_hover = run_scene(cam, gondola_scene(2.50));
  326. report("gondola 20ft hovering", g_hover);
  327. check_eq(g_hover.state, 1, "gondola -> state 1 (bed)");
  328. check(g_hover.ev[portcv::EvidenceKey::C1], "C1 (bright band below box bottom) detected");
  329. check(!g_hover.ev[portcv::EvidenceKey::F2], "no under-frame gap -> F2 false");
  330. check(g_hover.confidence > 0.45, "confidence above the voter threshold");
  331. // 敞车 + 20 尺箱(已落位:箱底被车帮截断 → 自标尺失效,但**仍不得输出 2**)
  332. const portcv::EdgeResult g_landed = run_scene(cam, gondola_scene(0.0));
  333. report("gondola 20ft landed", g_landed);
  334. check(g_landed.state != 2, "landed gondola never yields state 2 (safety rule)");
  335. check(g_landed.state == 1 || g_landed.state == 255, "landed gondola -> 1 or 255");
  336. // 平板车 + 20 尺箱 → 2(F1 ∧ F2 ∧ F3)
  337. const portcv::EdgeResult f20 = run_scene(cam, flatbed_scene(6.06));
  338. report("flatbed 20ft", f20);
  339. check_eq(f20.state, 2, "flatbed -> state 2");
  340. check(f20.ev[portcv::EvidenceKey::F1], "F1 low seating line detected");
  341. check(f20.ev[portcv::EvidenceKey::F2], "F2 under-frame gap detected");
  342. check(f20.ev[portcv::EvidenceKey::F3], "F3 no high structure");
  343. check(!f20.ev[portcv::EvidenceKey::C1], "C1 false on flatbed (interlock)");
  344. // 箱在地面 / 堆场 → 0(G1 ∧ G2 且 score_A < 1.0)
  345. portcv::SynthScene yard = ground_scene();
  346. yard.ground_rails = false;
  347. const portcv::EdgeResult g0 = run_scene(ground_cam, yard);
  348. report("box on ground (yard)", g0);
  349. check_eq(g0.state, 0, "box on ground -> state 0");
  350. check(g0.ev[portcv::EvidenceKey::G1], "G1 continuous ground");
  351. check(g0.ev[portcv::EvidenceKey::G2], "G2 no crossing line");
  352. // 空敞车 / 空平车(无箱 → 无自标尺 → **不得输出 2**)
  353. portcv::SynthScene empty_g = gondola_scene(0.0);
  354. empty_g.has_box = false;
  355. const portcv::EdgeResult eg = run_scene(cam, empty_g);
  356. report("empty gondola", eg);
  357. check(eg.state != 2, "empty gondola never yields state 2");
  358. portcv::SynthScene empty_f = flatbed_scene(6.06);
  359. empty_f.has_box = false;
  360. const portcv::EdgeResult ef = run_scene(cam, empty_f);
  361. report("empty flatbed", ef);
  362. check(ef.state != 2, "empty flatbed never yields state 2 (no box -> no self scale)");
  363. // 背景杂乱(箱场 / 工地)→ 不得误报 2
  364. portcv::SynthScene clutter = ground_scene();
  365. clutter.background_clutter = true;
  366. const portcv::EdgeResult rc = run_scene(ground_cam, clutter);
  367. report("box on ground + clutter", rc);
  368. check(rc.state != 2, "background clutter never yields state 2");
  369. // ---- 20 尺 / 40 尺**两种箱长都要稳定**(现场两种都会出现;箱高同为 2.591 m,
  370. // 所以自标尺基准不随箱长变,但越界带宽度 / 箱长像素会变 → 每类场景都要覆盖)----
  371. portcv::SynthScene gon40 = gondola_scene(1.95);
  372. gon40.box_len_m = 12.19; // 40 尺近满车(C70 ≈ 13 m 车长)
  373. const portcv::EdgeResult g40 = run_scene(cam, gon40);
  374. report("gondola 40ft hovering", g40);
  375. check(g40.state != 2, "40ft gondola never yields state 2 (safety rule)");
  376. check(g40.ev.box_h_px >= 60.0, "40ft gondola: box height in pixels >= near_edge_px");
  377. const portcv::EdgeResult f40b = run_scene(cam, flatbed_scene(12.19));
  378. report("flatbed 40ft", f40b);
  379. check(f40b.ev.box_h_px >= 60.0, "40ft flatbed: box height in pixels >= near_edge_px");
  380. check(f40b.state != 2 || f40b.ev.out_left_px >= 20.0 || f40b.ev.out_right_px >= 20.0,
  381. "40ft flatbed: state 2 only with a usable out-band");
  382. portcv::SynthScene yard20 = ground_scene();
  383. yard20.ground_rails = false;
  384. yard20.box_len_m = 6.06;
  385. const portcv::EdgeResult g20 = run_scene(ground_cam, yard20);
  386. report("box on ground 20ft", g20);
  387. check_eq(g20.state, 0, "box on ground 20ft -> state 0");
  388. }
  389. // ---------------------------------------------------------------- [5] 安全铁律
  390. void test_safety_rules(const portcv::SynthCamera& cam) {
  391. std::printf("[5] safety rules (spec 0 / 2.2 / 2.3 / 5)\n");
  392. // allow_state2 = false(§7 建议:首次上线先只输出 1 / 0 / 255)
  393. portcv::EdgeParams p;
  394. p.allow_state2 = false;
  395. const portcv::EdgeResult f = run_scene(cam, flatbed_scene(6.06), p);
  396. report("flatbed, allow_state2=false", f);
  397. check(f.state != 2, "allow_state2=false forbids state 2");
  398. // 40 尺近满车(13 m 车 + 12.19 m 箱):只有越界带够宽才允许 2(§5 / §12.8 Q2 ⑤)
  399. const portcv::EdgeResult f40 = run_scene(cam, flatbed_scene(12.19));
  400. report("flatbed 40ft near-full", f40);
  401. check(f40.state != 2 || f40.ev.out_left_px >= 20.0 || f40.ev.out_right_px >= 20.0,
  402. "40ft near-full: state 2 only with a usable out-band");
  403. // 雪天(低对比 + 强噪声)/ 夜间(低照度):优先 255,绝不误报 2(§5 处置表)
  404. portcv::SynthScene snow = flatbed_scene(6.06);
  405. snow.contrast = 0.45;
  406. snow.exposure = 1.15;
  407. snow.noise = 6.0;
  408. const portcv::EdgeResult rs = run_scene(cam, snow);
  409. report("flatbed in snow", rs);
  410. check(rs.state != 2, "snow: never false-positive state 2");
  411. portcv::SynthScene night = flatbed_scene(6.06);
  412. night.exposure = 0.35;
  413. night.noise = 5.0;
  414. const portcv::EdgeResult rn = run_scene(cam, night);
  415. report("flatbed at night", rn);
  416. check(rn.state != 2, "night: never false-positive state 2");
  417. // 弃权是合法输出:低置信度必须被压到 voter 门限附近
  418. if (rs.state == 255) { check(rs.confidence <= 0.25, "abstained frame has low confidence"); }
  419. else { check(true, "plain frame kept a positive verdict (allowed)"); }
  420. }
  421. // ---------------------------------------------------------------- [6] 运动门控(§6)
  422. void test_motion_gate(const portcv::SynthCamera& cam) {
  423. std::printf("[6] motion gate (spec 6)\n");
  424. const portcv::SynthScene scene = flatbed_scene(6.06);
  425. const portcv::GrayImage a = portcv::render_synthetic(cam, scene);
  426. const portcv::GrayImage b = portcv::translate_image(a, 24, 0); // 整幅平移 24 px
  427. portcv::EdgeEvidence ev;
  428. const portcv::EdgeResult r1 = ev.analyze(a, 0.0);
  429. check(!r1.ev.motion, "first frame has no reference -> not motion");
  430. const portcv::EdgeResult r2 = ev.analyze(b, 0.1);
  431. report("frame shifted 24 px", r2);
  432. check(r2.ev.motion, "24 px global shift -> MOTION");
  433. check(r2.ev.hold, "MOTION frame sets hold (verdict must not change)");
  434. check_eq(r2.state, 255, "MOTION frame yields 255 (upper layer keeps previous)");
  435. check_eq(static_cast<int>(r2.ev.diag), 5, "MOTION diag = 5 (spec 10)");
  436. portcv::EdgeEvidence ev2;
  437. ev2.analyze(a, 0.0);
  438. const portcv::EdgeResult r3 = ev2.analyze(a, 0.1);
  439. check(!r3.ev.motion, "identical frames -> no motion");
  440. // 门限的**单位口径**回归:motion_shift_max_px 是原图像素,而互相关在 160×90 缩略图上做。
  441. // 换一档分辨率(640×360 → 缩略倍数 4 而非 8)做同样的 24 px 平移,结论必须不变 ——
  442. // 漏了折算时,1280 宽这一档的 6 px 门限会被缩略 8 倍悄悄放宽成 48 px(= 24 px 漏检根因)。
  443. portcv::SynthCamera small_cam = cam;
  444. small_cam.width = 640;
  445. small_cam.height = 360;
  446. const portcv::GrayImage a_s = portcv::render_synthetic(small_cam, scene);
  447. portcv::EdgeEvidence ev_s;
  448. ev_s.analyze(a_s, 0.0);
  449. const portcv::EdgeResult r_s = ev_s.analyze(portcv::translate_image(a_s, 24, 0), 0.1);
  450. check(r_s.ev.motion, "24 px shift detected at 640x360 too (threshold unit = original px)");
  451. portcv::SynthScene blur = scene;
  452. blur.blur_radius = 8;
  453. const portcv::GrayImage c = portcv::render_synthetic(cam, blur);
  454. portcv::EdgeEvidence ev3;
  455. ev3.analyze(a, 0.0);
  456. const portcv::EdgeResult r4 = ev3.analyze(c, 0.1);
  457. report("frame with motion blur", r4);
  458. check(r4.ev.motion, "heavy motion blur -> MOTION");
  459. portcv::EdgeEvidence ev4;
  460. ev4.analyze(a, 0.0);
  461. ev4.analyze(b, 0.1);
  462. const portcv::EdgeResult r5 = ev4.analyze(portcv::translate_image(a, 30, 0), 2.0);
  463. report("third consecutive moving frame", r5);
  464. check(r5.ev.motion_held_s >= 1.5, "motion held time accumulates");
  465. check(ev4.motion_gate().timeout(), "motion timeout >= motion_hold_s (1.5 s)");
  466. }
  467. // ---------------------------------------------------------------- [7] 与规范一致性
  468. void test_spec_parity() {
  469. std::printf("[7] spec parity (spec 7 / 10)\n");
  470. const portcv::EdgeParams p;
  471. check_near(p.box_height_m, 2.591, 1e-9, "edge.box_height_m = 2.591 (20ft == 40ft)");
  472. check_near(p.band_high_lo, 0.55, 1e-9, "edge.band_high[0] = 0.55");
  473. check_near(p.band_high_hi, 0.85, 1e-9, "edge.band_high[1] = 0.85");
  474. check_near(p.band_low_lo, 0.00, 1e-9, "edge.band_low[0] = 0.00");
  475. check_near(p.band_low_hi, 0.10, 1e-9, "edge.band_low[1] = 0.10");
  476. check_near(p.gap_band_lo, 0.10, 1e-9, "edge.gap_band[0] = 0.10");
  477. check_near(p.gap_band_hi, 0.45, 1e-9, "edge.gap_band[1] = 0.45");
  478. check_near(p.cross_ratio_lo, 0.10, 1e-9, "edge.cross_ratio[0] = 0.10");
  479. check_near(p.cross_ratio_hi, 0.35, 1e-9, "edge.cross_ratio[1] = 0.35");
  480. check_near(p.line_angle_deg, 8.0, 1e-9, "edge.line_angle_deg = 8");
  481. check_near(p.min_len_track, 0.30, 1e-9, "edge.min_len_track = 0.30");
  482. check_near(p.min_len_cross_px, 20.0, 1e-9, "edge.min_len_cross_px = 20");
  483. check_near(p.min_out_ratio, 0.30, 1e-9, "edge.min_out_ratio = 0.30 (safety: do not lower)");
  484. check_near(p.grad_pct, 0.90, 1e-9, "edge.grad_pct = 0.90");
  485. check_near(p.texture_period_lo, 0.03, 1e-9, "edge.texture_period[0] = 0.03");
  486. check_near(p.texture_period_hi, 0.20, 1e-9, "edge.texture_period[1] = 0.20");
  487. check_near(p.near_edge_px, 60.0, 1e-9, "edge.near_edge_px = 60");
  488. check_near(p.motion_hold_s, 1.5, 1e-9, "edge.motion_hold_s = 1.5");
  489. check(p.allow_state2, "edge.allow_state2 default = true");
  490. // 证据编号(改名 / 改序会让现场统计口径断档,故固定断言)
  491. check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::P1)) == "P1", "evidence key P1");
  492. check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::F2)) == "F2", "evidence key F2");
  493. check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::C1)) == "C1", "evidence key C1");
  494. check(std::string(portcv::evidence_key_name(portcv::EvidenceKey::C3)) == "C3", "evidence key C3");
  495. check_eq(static_cast<int>(portcv::EvidenceKey::COUNT), 14, "evidence key count = 14");
  496. check(std::string(portcv::edge_diag_label(portcv::EdgeDiag::CONFLICT)) == "conflict",
  497. "diagnostic label (spec 10)");
  498. // §10 的 flags 位:只占 bit8..bit11,不与既有 StatusBits 冲突
  499. const uint16_t add = static_cast<uint16_t>(
  500. portcv::edge_flags::EDGE_OK | portcv::edge_flags::ABSTAIN | portcv::edge_flags::MOTION |
  501. portcv::edge_flags::SCALE_OK);
  502. check_eq(add, 0x0F00, "edge flags occupy bits 8..11");
  503. check_eq(add & 0x00FF, 0, "edge flags do not collide with existing StatusBits");
  504. }
  505. // ---------------------------------------------------------------- [8] Detector 适配(§10)
  506. void test_detector_adapter(const portcv::SynthCamera& cam) {
  507. std::printf("[8] Detector adapter (spec 10)\n");
  508. portcv::EdgeEvidenceDetector detector;
  509. portcv::Frame frame;
  510. frame.width = cam.width;
  511. frame.height = cam.height;
  512. frame.ts = 1.0;
  513. const std::vector<portcv::Box> none = detector.infer(frame);
  514. check(none.empty(), "Frame.gray == nullptr -> no boxes");
  515. check_eq(detector.last_result().state, 255, "no gray image -> 255 (not ready)");
  516. const portcv::GrayImage img = portcv::render_synthetic(cam, flatbed_scene(6.06));
  517. frame.gray = &img;
  518. const std::vector<portcv::Box> boxes = detector.infer(frame);
  519. check(boxes.size() >= 2, "boxes = container + wagon class");
  520. bool has_container = false;
  521. bool has_flatbed = false;
  522. for (const portcv::Box& b : boxes) {
  523. if (b.class_name == "container") { has_container = true; }
  524. if (b.class_name == "flatbed") { has_flatbed = true; }
  525. }
  526. check(has_container, "container box emitted (spec 10 naming)");
  527. check(has_flatbed, "flatbed box emitted (spec 10 naming)");
  528. check_eq(detector.last_result().state, 2, "adapter verdict = flatbed");
  529. check(std::string(detector.name()) == "edge-2d", "backend name = edge-2d");
  530. const portcv::Observation obs = detector.last_result().to_observation(3.5, 7);
  531. check_eq(obs.state, 2, "to_observation keeps state");
  532. check_near(obs.ts, 3.5, 1e-9, "to_observation keeps timestamp");
  533. check_eq(obs.frame_id, 7, "to_observation keeps frame id");
  534. check(!obs.reason.empty(), "to_observation carries the evidence summary");
  535. }
  536. } // namespace
  537. int main() {
  538. std::printf("portcv edge-evidence selftest (docs/edge_evidence.md)\n");
  539. const portcv::SynthCamera cam = test_camera();
  540. test_image_ops();
  541. test_lines();
  542. test_scale(cam);
  543. test_synthetic_regression(cam);
  544. test_safety_rules(cam);
  545. test_motion_gate(cam);
  546. test_spec_parity();
  547. test_detector_adapter(cam);
  548. std::printf("\n%d passed / %d failed\n", g_pass, g_fail);
  549. return g_fail == 0 ? 0 : 1;
  550. }