edge_evidence.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. // 二维边缘几何证据 · L3~L11 实现(自标尺 → 轨向 → 证据组 → 硬门槛 → 弃权 → 运动门控)。
  2. //
  3. // 与 docs/edge_evidence.md 的对应关系(评审时逐条可查):
  4. // §1.3 自标尺:近端竖棱像素长 / box_height_m(20/40 尺箱高同为 2.591 m → 现场不整定)
  5. // §2.2 证据:P1~P4(车斗)/ F1~F4(平车)/ G1~G3(无关场景)
  6. // §2.3 优先级:无箱 → 有箱 → A/B 组 → C 组;冲突/证据不足 → 255;运动 → 不改变判定
  7. // §3.5 线段有效性:长度 / 角度 / 越界比例 / 强度分位 / 纹理掩膜
  8. // §3.7 "明→暗→明" 车底空隙带;§3.8 暗腔;§3.9 投票与弃权
  9. // §12.4 C 通道(v1.1 主判据);§12.8 Q4 多目标就近优先
  10. //
  11. // 工程近似(**已明确记录**,现场整定时可逐条替换,不影响其它判据):
  12. // 1) 箱体轮廓用"近端竖棱 + 上/下横棱"构成的平行四边形(§3.2 第 4 步允许不完全平行);
  13. // 2) 高度带用图像 y 换算(近端竖棱与图像竖直夹角 ≤ 25° 时误差 ≤ 10%);
  14. // 3) "地面样"用灰度块统计近似(密度落在 [lo,hi] 且块内无长直线)——真机上若有彩色通道,
  15. // 只需替换 `region_stats()` 一处(Python 取证工具 `scripts/field_clip_probe.py --veg`
  16. // 已用植被比例,两者结论方向一致);
  17. // 4) P1/P2/P3 取"左右越界带**至少一侧**成立"(§12.3 实测:取景太近时越界带宽度不可靠,
  18. // 若按"两侧都必须成立",40 尺近满车会直接从 A 组掉到 C 组)。
  19. #include "portcv/edge_evidence.hpp"
  20. #include <algorithm>
  21. #include <cmath>
  22. #include <cstdio>
  23. #include <cstdlib>
  24. namespace portcv {
  25. namespace {
  26. /// 现场排错开关:`PORTCV_EDGE_TRACE=1` 时把几何中间量打到 stderr(默认关闭,零输出)。
  27. bool edge_trace_on() {
  28. static const bool on = []() {
  29. const char* v = std::getenv("PORTCV_EDGE_TRACE");
  30. return v != nullptr && v[0] != '\0' && v[0] != '0';
  31. }();
  32. return on;
  33. }
  34. /// 相对箱高 → 图像 y 的换算(rel=0 箱底、rel=1 箱顶、rel<0 箱底以下)。
  35. struct HeightMap {
  36. double y_bottom = 0.0; ///< rel = 0 的 y(箱底)
  37. double y_top = 0.0; ///< rel = 1 的 y(箱顶,比 y_bottom 小)
  38. double y_of(double rel) const { return y_bottom + rel * (y_top - y_bottom); }
  39. double rel_of(double y) const {
  40. const double d = y_top - y_bottom;
  41. return (d == 0.0) ? 0.0 : (y - y_bottom) / d;
  42. }
  43. };
  44. /// 帧级"强台阶"参考值:相邻行均值差的分位数(§3.7 说的"强台阶"= 灰度的明暗跳变)。
  45. /// 用整帧做参考而不是固定灰度差,是为了让雨 / 雪 / 夜 / 逆光下同一个阈值语义不变。
  46. double row_step_reference(const GrayImage& img, double pct) {
  47. if (img.empty() || img.height < 2) { return 0.0; }
  48. std::vector<float> diffs;
  49. diffs.reserve(static_cast<std::size_t>(img.height - 1));
  50. for (int y = 0; y + 1 < img.height; ++y) {
  51. double a = 0.0;
  52. double b = 0.0;
  53. for (int x = 0; x < img.width; ++x) {
  54. a += img.at(x, y);
  55. b += img.at(x, y + 1);
  56. }
  57. a /= static_cast<double>(img.width);
  58. b /= static_cast<double>(img.width);
  59. diffs.push_back(static_cast<float>(std::fabs(a - b)));
  60. }
  61. return static_cast<double>(percentile(diffs, pct));
  62. }
  63. /// 一个矩形区域的统计量(P3 / F2 / G1 / C1 / C3 共用)。
  64. struct RegionStats {
  65. double mean = 0.0; ///< 平均灰度
  66. double edge_density = 0.0; ///< 边缘密度:本地 mag > 帧内 60 分位 的像素比例
  67. double ground_like = 0.0; ///< "地面样"块比例:密度在 [lo,hi] 且块内无长直线
  68. double max_step = 0.0; ///< 区域内"相邻行均值差"的最大值(强台阶检测)
  69. int blocks = 0;
  70. };
  71. /// 区域统计。`mag_ref` 传帧内 mag 的 60 分位(调用方算一次,避免逐区域重复排序)。
  72. RegionStats region_stats(const GrayImage& img, const SobelResult& grad,
  73. const std::vector<Segment>& segs, double x0, double y0, double x1, double y1,
  74. const EdgeParams& p, float mag_ref) {
  75. RegionStats st;
  76. const int ix0 = std::max(0, static_cast<int>(std::floor(x0)));
  77. const int ix1 = std::min(img.width - 1, static_cast<int>(std::ceil(x1)));
  78. const int iy0 = std::max(0, static_cast<int>(std::floor(y0)));
  79. const int iy1 = std::min(img.height - 1, static_cast<int>(std::ceil(y1)));
  80. if (ix1 < ix0 || iy1 < iy0) { return st; }
  81. // 均值 + 边缘密度(一次遍历)
  82. double sum = 0.0;
  83. long long n = 0;
  84. long long hot = 0;
  85. for (int y = iy0; y <= iy1; ++y) {
  86. for (int x = ix0; x <= ix1; ++x) {
  87. sum += static_cast<double>(img.at(x, y));
  88. if (grad.mag_at(x, y) > mag_ref) { ++hot; }
  89. ++n;
  90. }
  91. }
  92. if (n == 0) { return st; }
  93. st.mean = sum / static_cast<double>(n);
  94. st.edge_density = static_cast<double>(hot) / static_cast<double>(n);
  95. // 最大行间台阶
  96. for (int y = iy0; y + 1 <= iy1; ++y) {
  97. double a = 0.0;
  98. double b = 0.0;
  99. for (int x = ix0; x <= ix1; ++x) {
  100. a += img.at(x, y);
  101. b += img.at(x, y + 1);
  102. }
  103. const double d = std::fabs(a - b) / static_cast<double>(ix1 - ix0 + 1);
  104. st.max_step = std::max(st.max_step, d);
  105. }
  106. // "地面样"块比例
  107. const int b = std::max(6, static_cast<int>(p.ground_block_px));
  108. long long ground_blocks = 0;
  109. long long total_blocks = 0;
  110. for (int by = iy0; by <= iy1; by += b) {
  111. for (int bx = ix0; bx <= ix1; bx += b) {
  112. const int ex = std::min(ix1, bx + b - 1);
  113. const int ey = std::min(iy1, by + b - 1);
  114. long long bn = 0;
  115. long long bhot = 0;
  116. for (int y = by; y <= ey; ++y) {
  117. for (int x = bx; x <= ex; ++x) {
  118. if (grad.mag_at(x, y) > mag_ref) { ++bhot; }
  119. ++bn;
  120. }
  121. }
  122. if (bn == 0) { continue; }
  123. const double density = static_cast<double>(bhot) / static_cast<double>(bn);
  124. // 块内有"长直线"→ 视为结构面(不是地面纹理)
  125. bool has_long_line = false;
  126. for (const Segment& s : segs) {
  127. if (s.length < 0.6 * static_cast<double>(b)) { continue; }
  128. if (s.cx() < bx || s.cx() > ex || s.cy() < by || s.cy() > ey) { continue; }
  129. has_long_line = true;
  130. break;
  131. }
  132. ++total_blocks;
  133. if (!has_long_line && density >= p.ground_density_lo && density <= p.ground_density_hi) {
  134. ++ground_blocks;
  135. }
  136. }
  137. }
  138. st.blocks = static_cast<int>(total_blocks);
  139. st.ground_like = total_blocks > 0
  140. ? static_cast<double>(ground_blocks) / static_cast<double>(total_blocks)
  141. : 0.0;
  142. return st;
  143. }
  144. } // namespace
  145. // ---------------------------------------------------------------- 帧上下文与预处理
  146. namespace {
  147. /// 一帧的中间结果(只在 analyze() 内部使用;对外暴露的是 Evidence)。
  148. struct FrameContext {
  149. GrayImage work; ///< 预处理后的工作图(长边 ≈ edge.work_width)
  150. SobelResult grad;
  151. std::vector<uint8_t> edges;
  152. std::vector<Segment> segs;
  153. float strong_threshold = 0.0f; ///< 线段 contrast 的 grad_pct 分位(§3.5 ④ 的"强边门")
  154. float mag_ref = 0.0f; ///< mag 的 60 分位(边缘密度参考)
  155. double row_step_ref = 0.0; ///< 强台阶参考(相邻行均值差的分位)
  156. BoxOutline outline;
  157. std::vector<PointF> poly; ///< 箱体轮廓四边形
  158. HeightMap hm; ///< 相对箱高 ↔ 图像 y
  159. double x_min = 0.0; ///< 箱轮廓 x 范围
  160. double x_max = 0.0;
  161. double strip_w = 0.0; ///< 越界带宽度(= cross_ratio_hi × 箱宽)
  162. bool low_light = false; ///< 原始帧过暗/低对比(夜间/逆光);任何状态都不猜
  163. double mean_gray = 0.0; ///< 原始帧均值(诊断用)
  164. double p05_gray = 0.0; ///< 原始帧 5 分位
  165. double p95_gray = 0.0; ///< 原始帧 95 分位
  166. };
  167. /// 预处理(§3.1 的顺序):降采样 → 3×3 中值 → 3×3 高斯 → CLAHE 光照归一。
  168. /// 说明:先降采样后滤波,等价于"在目标分辨率上滤波",且把单帧成本压到 20~40 ms 量级。
  169. GrayImage preprocess(const GrayImage& src, const EdgeParams& p) {
  170. double scale = 1.0;
  171. GrayImage work = resize_long_side(src, p.work_width, &scale);
  172. median3x3_inplace(&work);
  173. gaussian3x3_inplace(&work);
  174. if (p.use_clahe) { clahe_lite_inplace(&work, p.clahe_tiles, p.clahe_clip); }
  175. return work;
  176. }
  177. /// 线段中点所在的高度(相对箱高)。
  178. inline double mid_rel(const Segment& s, const HeightMap& hm) { return hm.rel_of(s.cy()); }
  179. /// 两条线段所在直线的交点(参数方程)。平行 / 退化 → false。
  180. bool line_intersection(const Segment& a, const Segment& b, PointF* out) {
  181. const double ax = a.x2 - a.x1;
  182. const double ay = a.y2 - a.y1;
  183. const double bx = b.x2 - b.x1;
  184. const double by = b.y2 - b.y1;
  185. const double den = ax * by - ay * bx;
  186. if (std::fabs(den) < 1e-9) { return false; }
  187. const double t = ((b.x1 - a.x1) * by - (b.y1 - a.y1) * bx) / den;
  188. if (out != nullptr) {
  189. out->first = a.x1 + t * ax;
  190. out->second = a.y1 + t * ay;
  191. }
  192. return true;
  193. }
  194. /// 某处的"轨向像方向"(度):从该点指向轨向消失点;没有消失点时退化为常量角度。
  195. inline double track_dir_angle_at(const BoxOutline& o, double x, double y) {
  196. if (!o.has_vp) { return o.track_angle_deg; }
  197. const double dx = o.track_vp.first - x;
  198. const double dy = o.track_vp.second - y;
  199. if (std::fabs(dx) < 1e-6 && std::fabs(dy) < 1e-6) { return o.track_angle_deg; }
  200. return normalize_angle_deg(std::atan2(dy, dx) * 180.0 / 3.14159265358979323846);
  201. }
  202. /// 箱体轮廓构建(§3.2):① 竖直候选 → 近端竖棱;② 上/下横棱;③ 轨向;④ 平行四边形。
  203. /// `boxes_seen` 统计"疑似箱体数"(≥ near_edge_px 的长竖棱条数),供 §12.8 Q4 的
  204. /// "多目标就近优先"与置信度折减使用。
  205. BoxOutline build_outline(const std::vector<Segment>& segs, const GrayImage& img, const EdgeParams& p,
  206. int* boxes_seen) {
  207. BoxOutline out;
  208. if (boxes_seen != nullptr) { *boxes_seen = 0; }
  209. // ① 竖直候选:与图像竖直方向夹角 ≤ 25°(即 |angle_deg| ≥ 65°,§3.2 ②)
  210. // ⚠ 不能"只挑最长的那条":贴着相机下方的钢轨在图像里也能到 65~80°,而且往往比
  211. // 真正的箱体竖棱还长 —— 实测 960×540 合成场景里就把一条 67.5° 的轨线当成了近端竖棱,
  212. // 导致 px_per_m 偏小 13%、并把轮廓锚点落到轨线上。
  213. // 这里按"长度 × 竖直度权重"排序(真竖直 = 1.0、65° 处降到 0.55),
  214. // 再依次尝试,优先采用"上 / 下横棱都能找到、且横棱与竖棱近似垂直"的候选。
  215. std::vector<const Segment*> verts;
  216. verts.reserve(segs.size());
  217. for (const Segment& s : segs) {
  218. if (std::fabs(s.angle_deg) >= 65.0 && s.length >= 10.0) { verts.push_back(&s); }
  219. }
  220. if (verts.empty()) { return out; }
  221. auto vertical_weight = [](const Segment* s) {
  222. const double t = std::min(1.0, std::max(0.0, (std::fabs(s->angle_deg) - 65.0) / 25.0));
  223. return 0.55 + 0.45 * t; // 65° → 0.55,85° 以上 → 1.0
  224. };
  225. std::stable_sort(verts.begin(), verts.end(), [&vertical_weight](const Segment* a,
  226. const Segment* b) {
  227. return a->length * vertical_weight(a) > b->length * vertical_weight(b);
  228. });
  229. if (boxes_seen != nullptr) {
  230. int count = 0;
  231. for (const Segment* s : verts) {
  232. if (s->length >= p.near_edge_px) { ++count; }
  233. }
  234. *boxes_seen = count > 0 ? count : 1;
  235. }
  236. // ③ 以竖棱两端为锚,搜索上 / 下横棱(与水平夹角 ≤ 30°,落在锚点邻域内)
  237. auto find_cross = [&](const PointF& anchor) -> const Segment* {
  238. const Segment* best = nullptr;
  239. const double win_x = 0.6 * out.near_len_px;
  240. const double win_y = 0.20 * out.near_len_px;
  241. for (const Segment& s : segs) {
  242. if (std::fabs(s.angle_deg) > 30.0) { continue; } // 只收"横向"边
  243. if (s.length < 0.25 * out.near_len_px) { continue; }
  244. const double dx = std::fabs(s.cx() - anchor.first);
  245. const double dy = std::fabs(s.cy() - anchor.second);
  246. if (dx > win_x + 0.5 * s.length || dy > win_y) { continue; }
  247. if (best == nullptr || s.length > best->length) { best = &s; }
  248. }
  249. return best;
  250. };
  251. /// 横棱应与竖棱近似垂直(±25°):否则会把"另一条平行斜线"当成横棱。
  252. auto perp_ok = [](const Segment* cross, const Segment* vert) {
  253. return std::fabs(angle_diff_deg(cross->angle_deg, vert->angle_deg + 90.0)) <= 25.0;
  254. };
  255. auto top_of = [](const Segment* s) -> PointF {
  256. return (s->y1 <= s->y2) ? PointF{s->x1, s->y1} : PointF{s->x2, s->y2};
  257. };
  258. auto bottom_of = [](const Segment* s) -> PointF {
  259. return (s->y1 <= s->y2) ? PointF{s->x2, s->y2} : PointF{s->x1, s->y1};
  260. };
  261. // ② 候选择优(§1.3):近端竖棱 = **箱底端点最靠下**(离相机最近)的闭合候选,
  262. // 不是"图像里最长的那条"。车厢端柱/背景竖线可能比 2.59 m 箱高还长,
  263. // 按长度选会把它们当箱体竖棱 → 自标尺与所有高度带判据全错。
  264. const Segment* best_strict = nullptr;
  265. double best_bottom_y = -1e18;
  266. for (const Segment* cand : verts) {
  267. const PointF top = top_of(cand);
  268. const PointF bot = bottom_of(cand);
  269. const Segment* t = find_cross(top);
  270. const Segment* b = find_cross(bot);
  271. if (t == nullptr || b == nullptr || !perp_ok(t, cand) || !perp_ok(b, cand)) { continue; }
  272. const double bottom_y = bot.second;
  273. if (best_strict == nullptr || bottom_y > best_bottom_y ||
  274. (bottom_y == best_bottom_y &&
  275. cand->length * vertical_weight(cand) >
  276. best_strict->length * vertical_weight(best_strict))) {
  277. best_strict = cand;
  278. best_bottom_y = bottom_y;
  279. }
  280. }
  281. const Segment* chosen = (best_strict != nullptr) ? best_strict : verts.front();
  282. out.near_len_px = chosen->length;
  283. out.near_top = top_of(chosen);
  284. out.near_bottom = bottom_of(chosen);
  285. const Segment* seg_top = find_cross(out.near_top);
  286. const Segment* seg_bottom = find_cross(out.near_bottom);
  287. out.near_edge_strict = (best_strict != nullptr);
  288. if (!out.near_edge_strict) { out.track_low = true; }
  289. // ④ 轨向(§3.3):箱顶 / 箱底横棱与轨向平行(同灭点 → 图像里同斜率);
  290. // 两者都不可靠 → 退化为图像水平并置 TRACKDIR_LOW。
  291. double width_px = 0.0;
  292. double dir_x = 1.0;
  293. double dir_y = 0.0;
  294. bool have_dir = false;
  295. for (const Segment* s : {seg_top, seg_bottom}) {
  296. if (s == nullptr) { continue; }
  297. width_px = std::max(width_px, s->length);
  298. if (!have_dir) {
  299. const bool from_top = (s == seg_top);
  300. const PointF anchor = from_top ? out.near_top : out.near_bottom;
  301. // 远端端点 = 离锚点更远的那个端点(决定"往画面哪边是纵深方向")
  302. const double d1 = std::hypot(s->x1 - anchor.first, s->y1 - anchor.second);
  303. const double d2 = std::hypot(s->x2 - anchor.first, s->y2 - anchor.second);
  304. const double fx = (d1 >= d2) ? s->x1 : s->x2;
  305. const double fy = (d1 >= d2) ? s->y1 : s->y2;
  306. const double len = std::hypot(fx - anchor.first, fy - anchor.second);
  307. if (len > 1e-6) {
  308. dir_x = (fx - anchor.first) / len;
  309. dir_y = (fy - anchor.second) / len;
  310. have_dir = true;
  311. }
  312. }
  313. }
  314. if (width_px <= 0.0) { width_px = 0.6 * out.near_len_px; }
  315. width_px = std::min(std::max(width_px, 0.30 * out.near_len_px), 3.0 * out.near_len_px);
  316. if (!have_dir) {
  317. // 退化:朝画面外侧(远离主点)的方向当纵深
  318. dir_x = (out.near_top.first < img.width * 0.5) ? 1.0 : -1.0;
  319. dir_y = 0.0;
  320. out.track_low = true;
  321. }
  322. out.track_angle_deg =
  323. normalize_angle_deg(std::atan2(dir_y, dir_x) * 180.0 / 3.14159265358979323846);
  324. out.width_px = width_px;
  325. out.far_top = {out.near_top.first + dir_x * width_px, out.near_top.second + dir_y * width_px};
  326. out.far_bottom = {out.near_bottom.first + dir_x * width_px,
  327. out.near_bottom.second + dir_y * width_px};
  328. // 轨向消失点 = 箱顶棱与箱底棱所在直线的交点(两者都是轨向直线,§3.3)
  329. if (seg_top != nullptr && seg_bottom != nullptr) {
  330. PointF vp;
  331. if (line_intersection(*seg_top, *seg_bottom, &vp)) {
  332. out.track_vp = vp;
  333. out.has_vp = true;
  334. out.track_angle_deg = track_dir_angle_at(out, out.near_top.first, out.near_top.second);
  335. }
  336. }
  337. // 轮廓质量因子(§2.4)= min(1, 近端竖棱 px / 120);若竖棱**没能闭合出平行四边形**
  338. // (near_edge_strict=false —— 可能把钢轨之类的斜线当成了竖棱)再打折 20%:
  339. // 让上层投票(confidence)与现场排错都能看出"这一帧的标尺不太可信"。
  340. out.quality = std::min(1.0, out.near_len_px / 120.0) * (out.near_edge_strict ? 1.0 : 0.8);
  341. out.ok = out.near_len_px >= 10.0;
  342. return out;
  343. }
  344. } // namespace
  345. // ---------------------------------------------------------------- 共用工具(越界性 / 纹理掩膜)
  346. namespace {
  347. /// 线段"越出箱体轮廓"的左右两侧长度(§3.5 ③ 越界性;侧别用采样点 x 与箱轮廓中心比较)。
  348. /// - left_len / right_len:两侧各自的"越出总长";
  349. /// - left_run / right_run:两侧各自的"最长连续越出段"(§2.2 要求"每段 ≥ 20 px");
  350. /// - ratio:越出比例(要求 ≥ edge.min_out_ratio)。
  351. struct OutSpans {
  352. double left_len = 0.0;
  353. double right_len = 0.0;
  354. double left_run = 0.0;
  355. double right_run = 0.0;
  356. double ratio = 0.0;
  357. };
  358. /// 点到凸/凹多边形边界的最短距离(px)。用于排除"贴着箱体轮廓的自身棱线":
  359. /// 箱体竖波纹只比轮廓外 0.006 m(≈0.2~0.6 px),旧实现把它当成"越出箱体"的强证据,
  360. /// 在平车/地面场景里制造 P2/F1 假阳性。真实车体结构边离箱侧 ≥0.28 m(≥10 px)。
  361. double point_polygon_boundary_distance(const PointF& p, const std::vector<PointF>& poly) {
  362. if (poly.size() < 2) { return 0.0; }
  363. double best = 1e18;
  364. for (std::size_t i = 0; i < poly.size(); ++i) {
  365. const PointF& a = poly[i];
  366. const PointF& b = poly[(i + 1) % poly.size()];
  367. const double dx = b.first - a.first;
  368. const double dy = b.second - a.second;
  369. const double len2 = dx * dx + dy * dy;
  370. double t = 0.0;
  371. if (len2 > 1e-12) {
  372. t = ((p.first - a.first) * dx + (p.second - a.second) * dy) / len2;
  373. t = std::min(1.0, std::max(0.0, t));
  374. }
  375. const double qx = a.first + t * dx;
  376. const double qy = a.second + t * dy;
  377. best = std::min(best, std::hypot(p.first - qx, p.second - qy));
  378. }
  379. return best;
  380. }
  381. /// 越出判定必须离开箱体边界 ≥3 px:同一份 960 宽工作图上,箱体自身棱线 ≤1 px、
  382. /// 车体越界带 ≥10 px,因此 3 px 既能滤掉自棱线,又不会吃掉 40 尺近满车只剩 20 px 的边界。
  383. constexpr double kOutBoundaryMarginPx = 3.0;
  384. OutSpans out_spans_by_side(const Segment& s, const std::vector<PointF>& poly, double box_cx,
  385. int samples = 128) {
  386. OutSpans out;
  387. if (poly.size() < 3 || samples <= 0 || s.length <= 0.0) { return out; }
  388. const double step = s.length / static_cast<double>(samples);
  389. int outside = 0;
  390. double run = 0.0;
  391. int side = 0; // -1 左、+1 右、0 未知
  392. for (int k = 0; k < samples; ++k) {
  393. const double t = (static_cast<double>(k) + 0.5) / static_cast<double>(samples);
  394. const PointF p = segment_point(s, t);
  395. if (point_in_polygon_f(p.first, p.second, poly)) {
  396. run = 0.0;
  397. side = 0;
  398. continue;
  399. }
  400. // 贴着轮廓的自棱线(箱体波纹 / 顶底棱)不算"越出":必须离边界 ≥ margin。
  401. if (point_polygon_boundary_distance(p, poly) < kOutBoundaryMarginPx) {
  402. run = 0.0;
  403. side = 0;
  404. continue;
  405. }
  406. ++outside;
  407. const int cur = (p.first < box_cx) ? -1 : 1;
  408. if (cur != side) {
  409. run = 0.0;
  410. side = cur;
  411. }
  412. run += step;
  413. if (cur < 0) {
  414. out.left_len += step;
  415. out.left_run = std::max(out.left_run, run);
  416. } else {
  417. out.right_len += step;
  418. out.right_run = std::max(out.right_run, run);
  419. }
  420. }
  421. out.ratio = static_cast<double>(outside) / static_cast<double>(samples);
  422. return out;
  423. }
  424. /// 纹理掩膜(§3.6):专治"箱体自身线条"——竖向波棱与横线密集。
  425. /// **关键**:掩膜只在箱体轮廓**内部**生效;判据要求"越出箱体轮廓",因此不会误伤真实证据。
  426. struct TextureMask {
  427. bool vertical_ribs = false;
  428. bool horizontal_lines = false;
  429. double box_w_px = 0.0;
  430. bool hit(const Segment& s, const std::vector<PointF>& poly) const {
  431. if (!point_in_polygon_f(s.cx(), s.cy(), poly)) { return false; }
  432. if (vertical_ribs && std::fabs(s.angle_deg) >= 60.0) { return true; }
  433. if (horizontal_lines && std::fabs(s.angle_deg) <= 30.0 && s.length <= 0.60 * box_w_px) {
  434. return true;
  435. }
  436. return false;
  437. }
  438. };
  439. /// 构建纹理掩膜:① 列方向边缘能量的自相关次峰(等距竖棱);② 箱内横向短线群数量(≥5 根)。
  440. TextureMask build_texture_mask(const FrameContext& ctx, const EdgeParams& p) {
  441. TextureMask mask;
  442. mask.box_w_px = ctx.outline.width_px;
  443. if (!ctx.outline.ok || ctx.poly.size() < 3) { return mask; }
  444. // ① 竖向波棱:只看箱体轮廓内部的"列边缘能量"
  445. const int x0 = std::max(0, static_cast<int>(std::floor(ctx.x_min)));
  446. const int x1 = std::min(ctx.work.width - 1, static_cast<int>(std::ceil(ctx.x_max)));
  447. std::vector<double> energy;
  448. for (int x = x0; x <= x1; ++x) {
  449. double e = 0.0;
  450. for (double rel = 0.15; rel <= 1.0; rel += 0.05) { // 避开顶 / 底侧梁
  451. const double y = ctx.hm.y_of(rel);
  452. const int iy = static_cast<int>(y + 0.5);
  453. if (iy < 0 || iy >= ctx.work.height) { continue; }
  454. if (!point_in_polygon_f(x + 0.5, y, ctx.poly)) { continue; }
  455. e += static_cast<double>(ctx.grad.mag_at(x, iy));
  456. }
  457. energy.push_back(e);
  458. }
  459. const double lag_lo = std::max(3.0, p.texture_period_lo * ctx.outline.width_px);
  460. const double lag_hi = std::max(lag_lo + 1.0, p.texture_period_hi * ctx.outline.width_px);
  461. double best = 0.0;
  462. for (int lag = static_cast<int>(lag_lo);
  463. lag <= static_cast<int>(lag_hi) && static_cast<std::size_t>(lag) < energy.size(); ++lag) {
  464. double num = 0.0;
  465. double da = 0.0;
  466. double db = 0.0;
  467. for (std::size_t k = 0; k + static_cast<std::size_t>(lag) < energy.size(); ++k) {
  468. num += energy[k] * energy[k + static_cast<std::size_t>(lag)];
  469. da += energy[k] * energy[k];
  470. db += energy[k + static_cast<std::size_t>(lag)] * energy[k + static_cast<std::size_t>(lag)];
  471. }
  472. const double den = std::sqrt(da * db);
  473. if (den > 1e-9) { best = std::max(best, num / den); }
  474. }
  475. mask.vertical_ribs = best >= 0.5; // 归一化自相关次峰明显 → 等距棱条
  476. // ② 横线密集:箱体轮廓内部的短横线数量(门 / 锁杆横档 / 喷字 / 反光带)
  477. int short_lines = 0;
  478. for (const Segment& s : ctx.segs) {
  479. if (std::fabs(s.angle_deg) > 30.0) { continue; }
  480. if (s.length < 10.0 || s.length > 0.60 * mask.box_w_px) { continue; }
  481. if (!point_in_polygon_f(s.cx(), s.cy(), ctx.poly)) { continue; }
  482. ++short_lines;
  483. }
  484. mask.horizontal_lines = short_lines >= 5;
  485. return mask;
  486. }
  487. } // namespace
  488. // ---------------------------------------------------------------- 高度带剖面 / 墙体验证 / 下身统计
  489. namespace {
  490. /// 越界带的 x 区间(左侧带 = 箱轮廓左边界之外的窄带;右侧带同理)。
  491. void side_strips(const FrameContext& ctx, const EdgeParams& p, double* left_x0, double* left_x1,
  492. double* right_x0, double* right_x1) {
  493. const double w = std::max(ctx.strip_w, p.cross_ratio_lo * ctx.outline.width_px);
  494. const double w_img = static_cast<double>(ctx.work.width - 1);
  495. if (left_x0 != nullptr) { *left_x0 = std::max(0.0, ctx.x_min - w); }
  496. if (left_x1 != nullptr) { *left_x1 = std::max(0.0, ctx.x_min - 1.0); }
  497. if (right_x0 != nullptr) { *right_x0 = std::min(w_img, ctx.x_max + 1.0); }
  498. if (right_x1 != nullptr) { *right_x1 = std::min(w_img, ctx.x_max + w); }
  499. }
  500. /// P3 的"实体墙体"判定(单侧越界带):低梯度大平面 + 明确的金属直线 + 看不到地面(§2.2)。
  501. bool evaluate_wall_strip(const FrameContext& ctx, const EdgeParams& p, double x0, double x1,
  502. double y_top, double y_bot) {
  503. if (x1 - x0 < 3.0 || y_bot - y_top < 3.0) { return false; }
  504. const RegionStats st =
  505. region_stats(ctx.work, ctx.grad, ctx.segs, x0, y_top, x1, y_bot, p, ctx.mag_ref);
  506. if (st.blocks <= 0) { return false; }
  507. if (st.edge_density > p.wall_density_max) { return false; } // ① 低梯度"大平面"
  508. if (st.ground_like >= p.c1_below_ground_max) { return false; } // ② 看不到地面
  509. for (const Segment& s : ctx.segs) { // ③ 明确的结构直线
  510. if (s.length < p.min_len_cross_px || s.contrast < ctx.strong_threshold) { continue; }
  511. if (s.cx() < x0 || s.cx() > x1) { continue; }
  512. if (s.cy() < y_top || s.cy() > y_bot) { continue; }
  513. return true;
  514. }
  515. return false;
  516. }
  517. /// 沿一条竖直线取"平滑后的亮度剖面"(§3.7 的明-暗-明 / 接触阴影都用它)。
  518. /// 相对高度 rel_lo..rel_hi(可为负 = 箱底以下),n 个样本;每个样本横向取 3 列均值抗噪。
  519. struct ColumnProfile {
  520. std::vector<double> v;
  521. double rel_lo = 0.0;
  522. double drel = 0.0;
  523. double range() const {
  524. if (v.empty()) { return 0.0; }
  525. double lo = v[0];
  526. double hi = v[0];
  527. for (double x : v) {
  528. lo = std::min(lo, x);
  529. hi = std::max(hi, x);
  530. }
  531. return hi - lo;
  532. }
  533. };
  534. ColumnProfile sample_column(const GrayImage& img, double x, const HeightMap& hm, double rel_lo,
  535. double rel_hi, int n) {
  536. ColumnProfile prof;
  537. if (n <= 1) { return prof; }
  538. prof.rel_lo = rel_lo;
  539. prof.drel = (rel_hi - rel_lo) / static_cast<double>(n - 1);
  540. prof.v.reserve(static_cast<std::size_t>(n));
  541. for (int k = 0; k < n; ++k) {
  542. const double rel = rel_lo + prof.drel * static_cast<double>(k);
  543. const double y = hm.y_of(rel);
  544. prof.v.push_back((img.sample_bilinear(x - 1.0, y) + img.sample_bilinear(x, y) +
  545. img.sample_bilinear(x + 1.0, y)) /
  546. 3.0);
  547. }
  548. return prof;
  549. }
  550. } // namespace
  551. /// 箱底以下的"下身结构"统计(F2 / G1 / G3 / C1 / C2 共用,只算一次)。
  552. struct BelowMetrics {
  553. double gap_col_ratio = 0.0; ///< 看到"明→暗→明"车底空隙的列比例(F2 / C2)
  554. double contact_ratio = 0.0; ///< 看到"接触阴影"的列比例(G3)
  555. double strong_step_ratio = 0.0; ///< 出现强台阶的列比例(G1 的反向条件)
  556. double thick_dark_ratio = 0.0; ///< 亮带下方出现"厚暗区"(>0.32 箱高)的列比例:不透明车帮
  557. RegionStats region; ///< 箱底以下 0~0.45 箱高的区域统计(G1)
  558. };
  559. /// 逐列剖线分析(§3.7):只有"多数列"都看到同一种结构,才认为该结构成立 —— 抗局部遮挡。
  560. /// 高度约定:rel = 0 箱底、rel < 0 为箱底以下。
  561. ///
  562. /// 采样区间**按图像下边界自适应**:`[-0.80, +0.10]` 只在画面里确实有这么多箱底以下像素时成立;
  563. /// 现场常见"箱底贴近画面下沿",若仍按固定 -0.80 采样,`sample_bilinear` 会把整段钳到最后一
  564. /// 行(所有亮度相同)→ F2 永远 0(2026-10 实测 A/B 片段即如此)。这里把 rel_lo 收到可见下限,
  565. /// 并把暗带宽度门限按实际可见带宽等比缩小;完全看不到箱底以下时如实判 F2=0,不猜。
  566. BelowMetrics analyze_below(const FrameContext& ctx, const EdgeParams& p) {
  567. BelowMetrics m;
  568. const HeightMap& hm = ctx.hm;
  569. const double y_last = static_cast<double>(ctx.work.height - 1);
  570. // 箱底以下实际可采样到的下限(rel 越小 = 越靠画面下方);永久 ≤ +0.10。
  571. const double rel_floor = std::max(-0.80, hm.rel_of(y_last));
  572. // 采样列覆盖"箱体 + 两侧越界带":箱体坐在平车地板上时,**箱底正下方被箱体自己挡住**,
  573. // 真正的"车面板边线 → 车底空隙 → 地面"出现在箱侧越界带里;只采箱体 x 范围会永远
  574. // 看不到暗带(2026-10 B 片与合成平车都是这个原因)。G1 的 ROI 也用同一横向范围。
  575. const double below_x0 = std::max(0.0, ctx.x_min - ctx.strip_w);
  576. const double below_x1 =
  577. std::min(static_cast<double>(ctx.work.width - 1), ctx.x_max + ctx.strip_w);
  578. const double region_y0 = hm.y_of(-0.02);
  579. const double region_y1 = std::min(hm.y_of(-p.gap_band_hi), y_last);
  580. // G1 用**箱体投影正下方**的 ROI(不含两侧越界带):箱在地面时那里是连续地面;
  581. // 平车 40 尺近满车时那里是车面板/结构边,不能因为两侧看到地面就判 0。
  582. m.region = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min, region_y0,
  583. ctx.x_max, region_y1, p, ctx.mag_ref);
  584. // 暗带(-0.45..-0.12)实际可见宽度;箱底贴边时按比例降低"连续暗带 ≥0.12 箱高"的门槛。
  585. const double dark_lo = std::max(rel_floor, -0.45);
  586. const double dark_avail = std::max(0.0, -0.12 - dark_lo);
  587. const double dark_run_min = std::min(0.06, std::max(0.04, 0.55 * dark_avail));
  588. // F2 只在箱底两侧的**近箱带**里找"明→暗→明":箱底正中被箱体挡住,而车面板边线 /
  589. // 车底空隙就在箱侧 0.1~0.3 箱宽内。左右分别统计,取较好一侧(单侧遮挡不判失败)。
  590. const double near_band = 0.30 * ctx.outline.width_px;
  591. const double outer_band = 0.10 * ctx.outline.width_px;
  592. const double x_img_max = static_cast<double>(ctx.work.width - 1);
  593. const double left_x0 = std::max(0.0, ctx.x_min - outer_band);
  594. const double left_x1 = std::max(0.0, ctx.x_min + near_band);
  595. const double right_x0 = std::min(x_img_max, ctx.x_max - near_band);
  596. const double right_x1 = std::min(x_img_max, ctx.x_max + outer_band);
  597. std::vector<double> col_x;
  598. std::vector<int> col_side; // -1 左、+1 右
  599. for (int k = 0; k < 11; ++k) {
  600. if (left_x1 - left_x0 < 1.0) { break; }
  601. const double t = (static_cast<double>(k) + 0.5) / 11.0;
  602. col_x.push_back(left_x0 + (left_x1 - left_x0) * t);
  603. col_side.push_back(-1);
  604. }
  605. for (int k = 0; k < 10; ++k) {
  606. if (right_x1 - right_x0 < 1.0) { break; }
  607. const double t = (static_cast<double>(k) + 0.5) / 10.0;
  608. col_x.push_back(right_x0 + (right_x1 - right_x0) * t);
  609. col_side.push_back(1);
  610. }
  611. const int cols = static_cast<int>(col_x.size());
  612. int used = 0;
  613. int left_used = 0;
  614. int right_used = 0;
  615. int left_candidates = 0;
  616. int right_candidates = 0;
  617. int gap_hits = 0;
  618. int left_gap_hits = 0;
  619. int right_gap_hits = 0;
  620. int contact_hits = 0;
  621. int step_hits = 0;
  622. int thick_hits = 0;
  623. for (int k = 0; k < cols; ++k) {
  624. const double x = col_x[static_cast<std::size_t>(k)];
  625. const int side = col_side[static_cast<std::size_t>(k)];
  626. const ColumnProfile prof = sample_column(ctx.work, x, hm, rel_floor, 0.10, 46);
  627. if (prof.v.size() < 8) { continue; }
  628. ++used;
  629. if (side < 0) { ++left_used; } else { ++right_used; }
  630. double bright1 = -1e9; // 箱底带(≈0 箱高):车面板边线 / 围挡上缘亮带
  631. double dark_min = 1e9; // 车底空隙带(0.12~0.45 箱高)
  632. double bright2 = -1e9; // 暗带**下方**的亮部(地面 / 轮对 / 远处):只要 rel ≤ -0.20 都算
  633. int osc = 0; // 暗带内的方向反转次数(平滑暗带 → 少;条纹 → 多)
  634. double prev_d = 0.0;
  635. bool has_prev_d = false;
  636. for (std::size_t i = 0; i < prof.v.size(); ++i) {
  637. const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
  638. const double val = prof.v[i];
  639. if (rel >= -0.12 && rel <= 0.10) { bright1 = std::max(bright1, val); }
  640. if (rel >= -0.45 && rel < -0.12) { dark_min = std::min(dark_min, val); }
  641. if (rel <= -0.20) { bright2 = std::max(bright2, val); }
  642. if (rel >= -0.45 && rel <= -0.12) {
  643. const double d = (i > 0) ? (prof.v[i] - prof.v[i - 1]) : 0.0;
  644. if (has_prev_d && ((d > 0.0) != (prev_d > 0.0)) &&
  645. std::fabs(d) > 0.05 * prof.range()) {
  646. ++osc;
  647. }
  648. prev_d = d;
  649. has_prev_d = true;
  650. }
  651. }
  652. const double dynamic = prof.range();
  653. const double need = std::max(12.0, p.c2_dark_k * dynamic);
  654. bool gap = false;
  655. double dark_run = 0.0;
  656. // 三带都采到才谈"明→暗→明";贴边帧允许只有上半段,但绝不把钳位像素当成结构。
  657. if (bright1 > -1e8 && dark_min < 1e8 && bright2 > -1e8) {
  658. const bool usable = (bright1 - dark_min) >= 0.5 * need;
  659. if (usable) {
  660. if (side < 0) { ++left_candidates; } else { ++right_candidates; }
  661. }
  662. // "明→暗→明":箱底带亮 → 空隙暗 → 更下方重回亮(§3.7 平车 vs 地面的分水岭)
  663. const bool gap_dir = (bright1 - dark_min) >= need &&
  664. (bright2 - dark_min) >= 0.40 * need && osc <= 10;
  665. // 暗带宽度:连续暗区(排除"一根细横线"造成的假暗带);门限随可见带宽缩放。
  666. double cur_run = 0.0;
  667. for (std::size_t i = 0; i < prof.v.size(); ++i) {
  668. const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
  669. if (rel < -0.45 || rel > -0.12) { continue; }
  670. if (prof.v[i] <= dark_min + 0.30 * need) {
  671. cur_run += std::fabs(prof.drel);
  672. dark_run = std::max(dark_run, cur_run);
  673. } else {
  674. cur_run = 0.0;
  675. }
  676. }
  677. gap = gap_dir && dark_run >= dark_run_min && dark_run <= 0.32;
  678. if (gap) {
  679. ++gap_hits;
  680. if (side < 0) { ++left_gap_hits; } else { ++right_gap_hits; }
  681. }
  682. if (bright1 - dark_min >= need && dark_run > 0.32) { ++thick_hits; }
  683. }
  684. if (edge_trace_on() && (k % 5) == 0) {
  685. std::fprintf(stderr,
  686. " col[%d] x=%.1f rel=[%.2f,0.10] b1=%.1f dark=%.1f b2=%.1f "
  687. "dyn=%.1f need=%.1f run=%.3f min=%.3f gap=%d osc=%d\n",
  688. k, x, rel_floor, bright1, dark_min, bright2, dynamic, need, dark_run,
  689. dark_run_min, gap ? 1 : 0, osc);
  690. }
  691. // ---- G3 接触特征:贴箱底的窄暗带(接触阴影)且其下明显更亮 ----
  692. double contact_mean = 0.0;
  693. double lower_mean = 0.0;
  694. int contact_n = 0;
  695. int lower_n = 0;
  696. for (std::size_t i = 0; i < prof.v.size(); ++i) {
  697. const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
  698. if (rel >= -0.06 && rel <= -0.005) {
  699. contact_mean += prof.v[i];
  700. ++contact_n;
  701. } else if (rel >= -0.45 && rel <= -0.12) {
  702. lower_mean += prof.v[i];
  703. ++lower_n;
  704. }
  705. }
  706. if (contact_n > 0 && lower_n > 0) {
  707. contact_mean /= static_cast<double>(contact_n);
  708. lower_mean /= static_cast<double>(lower_n);
  709. if (lower_mean - contact_mean >= std::max(6.0, p.contact_dark_k * dynamic)) {
  710. ++contact_hits;
  711. }
  712. }
  713. // ---- G1 的反向条件:箱底以下是否出现"强台阶"(金属直边)----
  714. double max_step = 0.0;
  715. for (std::size_t i = 1; i < prof.v.size(); ++i) {
  716. const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
  717. if (rel < -0.45 || rel > -0.10) { continue; }
  718. max_step = std::max(max_step, std::fabs(prof.v[i] - prof.v[i - 1]));
  719. }
  720. if (max_step >= std::max(8.0, 1.5 * ctx.row_step_ref)) { ++step_hits; }
  721. }
  722. if (used > 0) {
  723. const double left_n = static_cast<double>(std::max(1, left_candidates));
  724. const double right_n = static_cast<double>(std::max(1, right_candidates));
  725. const double left_ratio = static_cast<double>(left_gap_hits) / left_n;
  726. const double right_ratio = static_cast<double>(right_gap_hits) / right_n;
  727. m.gap_col_ratio = std::max(left_ratio, right_ratio);
  728. m.contact_ratio = static_cast<double>(contact_hits) / static_cast<double>(used);
  729. m.strong_step_ratio = static_cast<double>(step_hits) / static_cast<double>(used);
  730. m.thick_dark_ratio = static_cast<double>(thick_hits) / static_cast<double>(used);
  731. }
  732. if (edge_trace_on()) {
  733. std::fprintf(stderr,
  734. " below: used=%d gap=%.2f (L=%.2f[%d] R=%.2f[%d]) contact=%.2f step=%.2f "
  735. "thick=%.2f rel_floor=%.2f region(ground=%.2f mean=%.1f dens=%.2f blocks=%d)\n",
  736. used, m.gap_col_ratio,
  737. left_candidates > 0
  738. ? static_cast<double>(left_gap_hits) / left_candidates
  739. : 0.0,
  740. left_candidates,
  741. right_candidates > 0
  742. ? static_cast<double>(right_gap_hits) / right_candidates
  743. : 0.0,
  744. right_candidates, m.contact_ratio, m.strong_step_ratio, m.thick_dark_ratio,
  745. rel_floor, m.region.ground_like, m.region.mean, m.region.edge_density,
  746. m.region.blocks);
  747. }
  748. return m;
  749. }
  750. // ---------------------------------------------------------------- A 组(车斗 / 敞车)
  751. namespace {
  752. /// P1 / P2 / P3 / P4 + C1 / C3(§2.2 + §12.3 + §12.4)。
  753. void evaluate_a_group(const FrameContext& ctx, const EdgeParams& p, const TextureMask& mask,
  754. const BelowMetrics& below, Evidence* ev) {
  755. const HeightMap& hm = ctx.hm;
  756. const std::vector<PointF>& poly = ctx.poly;
  757. const double box_cx = 0.5 * (ctx.x_min + ctx.x_max);
  758. const double track_len = p.min_len_track * ctx.outline.width_px; // §3.5 ① 轨向线最小长
  759. const double img_w = static_cast<double>(ctx.work.width);
  760. double left_run = 0.0;
  761. double right_run = 0.0;
  762. int near_lines = 0; // 贴着箱体轮廓的候选结构线(VIEW_LIMITED 判定用)
  763. double c1_line_y = -1.0; // C1 候选亮带的位置
  764. double c1_line_len = 0.0;
  765. for (const Segment& s : ctx.segs) {
  766. const double rel_top0 = hm.rel_of(std::min(s.y1, s.y2));
  767. const double rel_bottom0 = hm.rel_of(std::max(s.y1, s.y2));
  768. if (edge_trace_on() && rel_bottom0 >= -0.35 && rel_top0 <= 0.15) {
  769. std::fprintf(stderr,
  770. " C1seg pre mask=%d ang=%.1f rel=[%.2f,%.2f] len=%.1f strong=%d\n",
  771. mask.hit(s, poly) ? 1 : 0, s.angle_deg, rel_top0, rel_bottom0, s.length,
  772. (s.contrast >= ctx.strong_threshold) ? 1 : 0);
  773. }
  774. if (mask.hit(s, poly)) { continue; } // §3.6 纹理掩膜(只在箱轮廓内部生效)
  775. const bool strong = s.contrast >= ctx.strong_threshold; // §3.5 ④ 强度分位门
  776. const OutSpans spans = out_spans_by_side(s, poly, box_cx);
  777. const double rel = mid_rel(s, hm);
  778. const bool near_box =
  779. (rel <= 1.10 && rel >= -0.60) &&
  780. ((s.cx() < box_cx && s.cx() >= ctx.x_min - 1.45 * ctx.strip_w) ||
  781. (s.cx() >= box_cx && s.cx() <= ctx.x_max + 1.45 * ctx.strip_w));
  782. if (near_box && strong && std::fabs(s.angle_deg) >= 55.0) { ++near_lines; }
  783. if (spans.ratio >= p.min_out_ratio) {
  784. left_run = std::max(left_run, spans.left_run);
  785. right_run = std::max(right_run, spans.right_run);
  786. }
  787. // C1 候选:箱底 ±0.15 箱高内的"贯穿视场"亮带(§12.4)。
  788. // 不要求 `strong` / 越界比例:车帮上缘是**宽亮带**,Canny 对比可能低于强边门;
  789. // 它的安全性由"其下看不到地面"与 F2 互斥(C1 成立时 F2 被抑制)保证。
  790. if (rel_bottom0 >= -0.15 && rel_top0 <= 0.06 &&
  791. s.length >= std::max(0.5 * ctx.outline.width_px, 0.25 * img_w) &&
  792. // 亮带下方至少还能看到 0.20 箱高:否则那是画面下沿的地面线,不是车帮亮带。
  793. std::max(s.y1, s.y2) <=
  794. static_cast<double>(ctx.work.height - 1) - 0.20 * ctx.outline.near_len_px &&
  795. s.length > c1_line_len) {
  796. c1_line_len = s.length;
  797. c1_line_y = std::max(s.y1, s.y2);
  798. }
  799. if (!strong || spans.ratio < p.min_out_ratio) { continue; }
  800. // 该处的轨向 = 指向轨向消失点的方向(§3.3;平行线在透视下向同一消失点收敛);
  801. // 没有可靠消失点时自动退化为箱顶/底棱的常量角度。
  802. const double track_local = track_dir_angle_at(ctx.outline, s.cx(), s.cy());
  803. const bool track_dir = angle_diff_deg(s.angle_deg, track_local) <= p.line_angle_deg;
  804. const bool cross_dir = angle_diff_deg(s.angle_deg, track_local + 90.0) <= p.line_angle_deg;
  805. const double out_run = std::max(spans.left_run, spans.right_run);
  806. if (edge_trace_on() && spans.ratio >= p.min_out_ratio) {
  807. std::fprintf(stderr,
  808. " Aseg cand ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f "
  809. "track=%d cross=%d strong=%d\n",
  810. s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
  811. spans.right_len, track_dir ? 1 : 0, cross_dir ? 1 : 0,
  812. strong ? 1 : 0);
  813. }
  814. // P1 侧墙上缘纵深线:轨向 + 高位带 + 长度 ≥ 0.30×箱宽 + 越出 ≥ 20 px
  815. if (track_dir && rel >= p.band_high_lo && rel <= p.band_high_hi && s.length >= track_len &&
  816. out_run >= p.min_len_cross_px) {
  817. ev->set(EvidenceKey::P1, true);
  818. }
  819. // P2 端墙上缘横线:**图像里近水平**(跨轨向的端墙线投影后不会竖直)+ 高位带 +
  820. // **两侧都越出** ≥20 px(端墙线横穿箱宽,两侧都伸到车宽外;箱体竖棱/端柱做不到)。
  821. // 旧实现用"与轨向垂直"→ 把箱体竖波纹/车厢端柱当成 P2(合成平车 F3 因此恒假)。
  822. if (std::fabs(s.angle_deg) <= 25.0 && rel >= p.band_high_lo &&
  823. rel <= p.band_high_hi &&
  824. std::min(spans.left_run, spans.right_run) >= p.min_len_cross_px) {
  825. ev->set(EvidenceKey::P2, true);
  826. }
  827. }
  828. // 越界带实测宽度(§9.3 第 3 项 / §12.3:40 尺近满车时只剩几十像素)
  829. ev->out_left_px = left_run > 0.0 ? left_run : std::min(ctx.strip_w, std::max(0.0, ctx.x_min));
  830. ev->out_right_px = right_run > 0.0
  831. ? right_run
  832. : std::min(ctx.strip_w, std::max(0.0,
  833. static_cast<double>(ctx.work.width - 1) -
  834. ctx.x_max));
  835. // P3 越界带实体墙体:低梯度大平面 + 明确直线 + 看不到地面
  836. double lx0 = 0.0;
  837. double lx1 = 0.0;
  838. double rx0 = 0.0;
  839. double rx1 = 0.0;
  840. side_strips(ctx, p, &lx0, &lx1, &rx0, &rx1);
  841. const double y_top = hm.y_of(0.75);
  842. const double y_bot = hm.y_of(0.0);
  843. ev->set(EvidenceKey::P3, evaluate_wall_strip(ctx, p, lx0, lx1, y_top, y_bot) ||
  844. evaluate_wall_strip(ctx, p, rx0, rx1, y_top, y_bot));
  845. // P4 箱–围挡暗腔(§3.8):内侧 0~0.10 箱宽窄带比外侧 0.10~0.35 箱宽明显更暗
  846. const double w_box = ctx.outline.width_px;
  847. const RegionStats in_l = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min - 0.10 * w_box,
  848. hm.y_of(0.70), ctx.x_min, hm.y_of(0.10), p, ctx.mag_ref);
  849. const RegionStats out_l =
  850. region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min - 0.35 * w_box, hm.y_of(0.70),
  851. ctx.x_min - 0.10 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
  852. const RegionStats in_r = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_max, hm.y_of(0.70),
  853. ctx.x_max + 0.10 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
  854. const RegionStats out_r =
  855. region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_max + 0.10 * w_box, hm.y_of(0.70),
  856. ctx.x_max + 0.35 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
  857. const bool p4_left =
  858. in_l.blocks > 0 && out_l.blocks > 0 && in_l.mean <= p.p4_dark_ratio * out_l.mean;
  859. const bool p4_right =
  860. in_r.blocks > 0 && out_r.blocks > 0 && in_r.mean <= p.p4_dark_ratio * out_r.mean;
  861. ev->set(EvidenceKey::P4, p4_left || p4_right);
  862. // §12.3 的 C3:箱底以下 ROI 看不到地面(旧口径"全画面占比"会随车距/构图从 0.24 漂到 0.38,
  863. // 跨在 0.25 阈值两侧 → 同一台车同一机位也抖动)。ROI 口径与 C1 内层的 no_ground_below 同源。
  864. const double full_w = static_cast<double>(ctx.work.width - 1);
  865. const double full_h = static_cast<double>(ctx.work.height - 1);
  866. const RegionStats full =
  867. region_stats(ctx.work, ctx.grad, ctx.segs, 0.0, 0.0, full_w, full_h, p, ctx.mag_ref);
  868. ev->ground_ratio_full = full.ground_like;
  869. ev->ground_ratio_below = below.region.ground_like;
  870. ev->set(EvidenceKey::C3, below.region.blocks > 0 &&
  871. below.region.ground_like < p.c1_below_ground_max);
  872. // §12.4 的 C1:亮带 + 其下看不到地面 + 其下**没有**车底空隙(与平车互斥 → 不会造假冲突)
  873. bool no_ground_below = false;
  874. double below_ground = 0.0;
  875. const bool gap_below = below.gap_col_ratio >= p.c2_col_ratio_min;
  876. if (c1_line_y > 0.0) {
  877. const double y_end = std::min(full_h, hm.y_of(-0.45));
  878. const double y_start = std::max(c1_line_y, hm.y_of(0.06));
  879. // 亮带下方必须确实有 ≥0.25 箱高的可见区域;否则只是画面下沿的一条线(地面/边框)。
  880. if (y_end - y_start >= 0.25 * ctx.outline.near_len_px) {
  881. const RegionStats b = region_stats(ctx.work, ctx.grad, ctx.segs,
  882. std::max(0.0, ctx.x_min - ctx.strip_w), y_start,
  883. std::min(full_w, ctx.x_max + ctx.strip_w), y_end, p,
  884. ctx.mag_ref);
  885. below_ground = b.ground_like;
  886. no_ground_below = b.ground_like < p.c1_below_ground_max;
  887. }
  888. }
  889. if (edge_trace_on()) {
  890. std::fprintf(stderr,
  891. " C1: line_y=%.1f line_len=%.1f no_ground_below=%d below_ground=%.2f "
  892. "gap_below=%d gap_ratio=%.2f full_ground=%.2f thick=%.2f region_mean=%.1f\n",
  893. c1_line_y, c1_line_len, no_ground_below ? 1 : 0, below_ground,
  894. gap_below ? 1 : 0, below.gap_col_ratio, full.ground_like,
  895. below.thick_dark_ratio, below.region.mean);
  896. }
  897. // C1 主路径:亮带 + 其下看不到地面。补充路径:亮带下方是**厚暗区**(>0.32 箱高的连续
  898. // 暗面 = 不透明车帮),即使线段通道没把车帮上缘拼成一条长线(夜/雪/纹理断裂)也能判 1。
  899. const bool opaque_wall = below.thick_dark_ratio >= 0.15 && below.region.blocks > 0 &&
  900. below.region.mean < 110.0;
  901. // 地面 ROI(亮 + 高"地面样"占比)直接否决 C1:箱在地面时 C1 必须是假。
  902. const bool ground_roi = below.region.ground_like >= 0.40 && below.region.mean >= 120.0;
  903. ev->set(EvidenceKey::C1,
  904. (((c1_line_y > 0.0) && no_ground_below) || opaque_wall) && !ground_roi);
  905. ev->view_limited = (ev->out_left_px < p.min_len_cross_px) &&
  906. (ev->out_right_px < p.min_len_cross_px) && (near_lines >= 1);
  907. }
  908. // ---------------------------------------------------------------- B 组(平板车)
  909. /// F1 低位坐板线 / F2 车底空隙带 / F3 无高位结构 / F4 车端低矮结构 + 平车地板俯视面(§12.4 F4')。
  910. void evaluate_b_group(const FrameContext& ctx, const EdgeParams& p, const TextureMask& mask,
  911. const BelowMetrics& below, Evidence* ev) {
  912. const HeightMap& hm = ctx.hm;
  913. const std::vector<PointF>& poly = ctx.poly;
  914. const double box_cx = 0.5 * (ctx.x_min + ctx.x_max);
  915. // band_low 以"箱底 = 0"为中心;斜前视下贴底横线的**中点**会因纵深透视明显偏高,
  916. // 因此用"线的 rel 区间与低带相交"判定,高带放到 +0.35 箱高(实测 A/B 与合成都要)。
  917. const double low_lo = p.band_low_lo - 0.25;
  918. const double low_hi = p.band_low_hi + 0.25;
  919. const double track_len = p.min_len_track * ctx.outline.width_px;
  920. for (const Segment& s : ctx.segs) {
  921. if (mask.hit(s, poly)) { continue; }
  922. if (s.contrast < ctx.strong_threshold) { continue; }
  923. const OutSpans spans = out_spans_by_side(s, poly, box_cx);
  924. const double rel = mid_rel(s, hm);
  925. if (edge_trace_on() && rel >= -0.25 && rel <= 0.35) {
  926. std::fprintf(stderr,
  927. " F1seg pre ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f\n",
  928. s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
  929. spans.right_len);
  930. }
  931. if (spans.ratio < p.min_out_ratio) { continue; }
  932. const double out_run = std::max(spans.left_run, spans.right_run);
  933. if (edge_trace_on()) {
  934. std::fprintf(stderr,
  935. " Bseg ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f strong=%d\n",
  936. s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
  937. spans.right_len, (s.contrast >= ctx.strong_threshold) ? 1 : 0);
  938. }
  939. // F1:贴箱底的强直线,且"左右越出箱体轮廓(每段 ≥ 20 px)或沿轨向长(≥ 0.30×箱长)"。
  940. // 用线的 rel **区间**与低带相交,而不是中点(车面板边线沿纵深是斜的)。
  941. const double f1_rel_top = hm.rel_of(std::min(s.y1, s.y2));
  942. const double f1_rel_bottom = hm.rel_of(std::max(s.y1, s.y2));
  943. if (f1_rel_bottom >= low_lo && f1_rel_top <= low_hi &&
  944. (out_run >= p.min_len_cross_px || s.length >= track_len)) {
  945. ev->set(EvidenceKey::F1, true);
  946. }
  947. }
  948. // F2:车底空隙带(多列剖线的"明→暗→明",§3.7)。
  949. // 还要求箱底以下 ROI 看得到**地面**:敞车围挡下方是一整片不透明墙,也会形成
  950. // "亮墙顶→暗墙→远处亮"的假三带;没有地面的"暗带"不是车底空隙。
  951. ev->set(EvidenceKey::F2, below.gap_col_ratio >= p.c2_col_ratio_min &&
  952. below.region.ground_like >= 0.18 &&
  953. below.thick_dark_ratio < 0.40 &&
  954. !ev->hit[static_cast<int>(EvidenceKey::C1)]);
  955. // F2 的 bright1 本身就是"车面板边线"(箱底坐板线)。合成/现场都可能出现线段通道
  956. // 因箱底被遮挡而漏掉 F1 的情况;F2 成立时把 F1 一并置真(低光帧已在 classify 前置 255)。
  957. if (ev->hit[static_cast<int>(EvidenceKey::F2)]) { ev->set(EvidenceKey::F1, true); }
  958. // F3:无高位结构 —— 直接取 A 组结论的反(§2.2)
  959. ev->set(EvidenceKey::F3, !(ev->hit[static_cast<int>(EvidenceKey::P1)] ||
  960. ev->hit[static_cast<int>(EvidenceKey::P2)] ||
  961. ev->hit[static_cast<int>(EvidenceKey::P3)]));
  962. // F4:① 平车地板"俯视面"(§12.4 F4'):箱底正下方 0.02~0.20 箱高的低梯度平面 + 长边线;
  963. // ② 车端低矮结构(端梁 / 挡块 / 走台):越界带内、略高于箱底(0.05~0.25 箱高)的结构边。
  964. const double d_lo = hm.y_of(-0.20);
  965. const double d_hi = hm.y_of(-0.02);
  966. const RegionStats deck =
  967. region_stats(ctx.work, ctx.grad, ctx.segs, std::max(0.0, ctx.x_min - ctx.strip_w), d_lo,
  968. std::min(static_cast<double>(ctx.work.width - 1), ctx.x_max + ctx.strip_w), d_hi,
  969. p, ctx.mag_ref);
  970. const bool deck_flat = deck.blocks > 0 && deck.edge_density <= p.wall_density_max &&
  971. deck.ground_like < 0.50;
  972. bool deck_long_edge = false;
  973. for (const Segment& s : ctx.segs) {
  974. if (s.length < 2.0 * p.min_len_cross_px || s.contrast < ctx.strong_threshold) { continue; }
  975. if (s.cy() < d_lo || s.cy() > d_hi) { continue; }
  976. deck_long_edge = true;
  977. break;
  978. }
  979. bool bump = false;
  980. for (const Segment& s : ctx.segs) {
  981. if (s.contrast < ctx.strong_threshold || s.length < p.min_len_cross_px) { continue; }
  982. const OutSpans spans = out_spans_by_side(s, poly, box_cx);
  983. if (spans.ratio < p.min_out_ratio) { continue; }
  984. const double rel = mid_rel(s, hm);
  985. if (rel >= 0.05 && rel <= 0.25) {
  986. bump = true;
  987. break;
  988. }
  989. }
  990. ev->set(EvidenceKey::F4, (deck_flat && deck_long_edge) || bump);
  991. }
  992. // ---------------------------------------------------------------- C 组(无关场景)
  993. /// G1 地面连续 / G2 无越界线 / G3 接触特征(§2.2)。
  994. void evaluate_c_group(const FrameContext& ctx, const EdgeParams& p, const BelowMetrics& below,
  995. Evidence* ev) {
  996. // G1:箱底以下 0~0.45 箱高内为连续地面纹理(多数块"地面样" + 无强台阶)
  997. const bool ground_continuous =
  998. below.region.blocks > 0 && below.region.ground_like >= 0.40 &&
  999. below.region.max_step <= std::max(10.0, 2.0 * ctx.row_step_ref);
  1000. ev->set(EvidenceKey::G1, ground_continuous);
  1001. // G2:无越界线 —— P1 / P2 不成立,且 F1 必须与 F2(车底空隙)同时成立。
  1002. // F1 单独出现时可能只是箱体自己的底棱 / 地面纹理(箱坐在地面上与坐在车面上,
  1003. // 单看一条贴底线分不开);F2 才是"车体"的判别证据。B 片 F1∧F2 成立 → G2=0。
  1004. ev->set(EvidenceKey::G2,
  1005. !(ev->hit[static_cast<int>(EvidenceKey::P1)] ||
  1006. ev->hit[static_cast<int>(EvidenceKey::P2)] ||
  1007. (ev->hit[static_cast<int>(EvidenceKey::F1)] &&
  1008. ev->hit[static_cast<int>(EvidenceKey::F2)])));
  1009. // G3:接触特征(接触阴影 / 垫木 / 托盘)
  1010. ev->set(EvidenceKey::G3, below.contact_ratio >= 0.50);
  1011. (void)ctx;
  1012. (void)p;
  1013. }
  1014. /// §3.9 的分数公式(**原样照抄文档**,任何权重调整都要先改文档再改代码):
  1015. /// score_A = 1.0·P1 + 0.9·P2 + 0.8·P3 + 0.6·P4
  1016. /// score_B = 1.0·F1 + 1.0·F2 + 0.7·F3 + 0.5·F4
  1017. /// score_C = 1.0·G1 + 1.0·G2 + 0.5·G3
  1018. void compute_scores(Evidence* ev) {
  1019. const auto h = [ev](EvidenceKey k) { return ev->hit[static_cast<int>(k)] ? 1.0 : 0.0; };
  1020. ev->score_a = 1.0 * h(EvidenceKey::P1) + 0.9 * h(EvidenceKey::P2) + 0.8 * h(EvidenceKey::P3) +
  1021. 0.6 * h(EvidenceKey::P4);
  1022. ev->score_b = 1.0 * h(EvidenceKey::F1) + 1.0 * h(EvidenceKey::F2) + 0.7 * h(EvidenceKey::F3) +
  1023. 0.5 * h(EvidenceKey::F4);
  1024. ev->score_c = 1.0 * h(EvidenceKey::G1) + 1.0 * h(EvidenceKey::G2) + 0.5 * h(EvidenceKey::G3);
  1025. // C2 与 F2 是同一件事实(§12.4 的编号),单独记一份便于现场统计
  1026. ev->set(EvidenceKey::C2, ev->hit[static_cast<int>(EvidenceKey::F2)]);
  1027. }
  1028. } // namespace
  1029. // ---------------------------------------------------------------- 判定(§2.2 硬门槛 / §2.3 优先级 / §2.4 置信度)
  1030. namespace {
  1031. /// 判定结果(内部用)。
  1032. struct Verdict {
  1033. int state = static_cast<int>(SceneState::UNKNOWN);
  1034. double confidence = 0.0;
  1035. EdgeDiag diag = EdgeDiag::NONE;
  1036. bool abstain = false;
  1037. bool conflict = false;
  1038. std::string reason;
  1039. };
  1040. std::string fmt2(const char* pattern, double a, double b) {
  1041. char buf[192];
  1042. std::snprintf(buf, sizeof(buf), pattern, a, b);
  1043. return std::string(buf);
  1044. }
  1045. /// §2.3 的判定优先级 + §2.2 的硬门槛 + §3.9 的弃权 + §2.4 的置信度。
  1046. Verdict classify(const FrameContext& ctx, const EdgeParams& p, Evidence* ev) {
  1047. Verdict v;
  1048. if (ctx.low_light) {
  1049. v.state = static_cast<int>(SceneState::UNKNOWN);
  1050. v.confidence = 0.0;
  1051. v.diag = EdgeDiag::SCALE_FAIL;
  1052. v.reason = "low light / low contrast -> 255 (safety)";
  1053. return v;
  1054. }
  1055. const auto h = [ev](EvidenceKey k) { return ev->hit[static_cast<int>(k)]; };
  1056. constexpr double kTotalA = 3.3; // 1.0+0.9+0.8+0.6
  1057. constexpr double kTotalB = 3.2; // 1.0+1.0+0.7+0.5
  1058. constexpr double kTotalC = 2.5; // 1.0+1.0+0.5
  1059. int a_hits = 0;
  1060. for (EvidenceKey k : {EvidenceKey::P1, EvidenceKey::P2, EvidenceKey::P3, EvidenceKey::P4}) {
  1061. if (h(k)) { ++a_hits; }
  1062. }
  1063. // ---------- ① 箱体轮廓未建立(§2.3 ①)----------
  1064. if (!ctx.outline.ok) {
  1065. bool structure = false;
  1066. for (const Segment& s : ctx.segs) {
  1067. if (s.length >= 40.0 && s.contrast >= ctx.strong_threshold) {
  1068. structure = true;
  1069. break;
  1070. }
  1071. }
  1072. if (ev->segments_total >= 3 && structure) {
  1073. v.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  1074. v.confidence = 0.50;
  1075. v.diag = EdgeDiag::NO_BOX;
  1076. v.reason = "no box outline but wagon structure seen -> 0 (spec 2.3-1)";
  1077. } else {
  1078. v.state = static_cast<int>(SceneState::UNKNOWN);
  1079. v.confidence = 0.0;
  1080. v.diag = EdgeDiag::NO_BOX;
  1081. v.reason = "no structure at all -> 255 (spec 2.3-1)";
  1082. }
  1083. return v;
  1084. }
  1085. // ---------- ② 硬门槛(§2.2 / §12.4)----------
  1086. const bool gate_a_doc = (h(EvidenceKey::P1) || h(EvidenceKey::P2)) && h(EvidenceKey::P3);
  1087. // §12.4(v1.1 主判据):C 通道的 C1 本身就是"箱底以下 ≤0.15 箱高的贯穿亮带 + 其下看不到地面",
  1088. // 已隐含"围挡挡住地面"这一条,因此 C1 单独成立即可判 `1`(与 §2.2 的 A 组硬门槛并存,
  1089. // 任一成立 → `1`)。安全性由 C1 内置的 `!gap_below`(没有车底空隙)保证 —— 平车不可能满足它。
  1090. const bool gate_a = gate_a_doc || h(EvidenceKey::C1);
  1091. const bool gate_b_doc = h(EvidenceKey::F1) && h(EvidenceKey::F2) && h(EvidenceKey::F3);
  1092. const bool gate_b = gate_b_doc && p.allow_state2;
  1093. // `0` 还必须 score_A < 1.0(防止"雪盖围挡"被误判为 0 —— §3.9)
  1094. const bool gate_0 = h(EvidenceKey::G1) && h(EvidenceKey::G2) && ev->score_a < 1.0 && !h(EvidenceKey::C1);
  1095. if (gate_a && gate_b_doc) {
  1096. // ---------- 冲突:A 组与 B 组同时成立(§2.3 ②)----------
  1097. v.state = static_cast<int>(SceneState::UNKNOWN);
  1098. v.confidence = std::min(0.30, (ev->score_a + ev->score_b) / (kTotalA + kTotalB));
  1099. v.diag = EdgeDiag::CONFLICT;
  1100. v.conflict = true;
  1101. ev->conflict = true;
  1102. v.reason = fmt2("conflict A=%.1f B=%.1f -> 255 (spec 2.3-2)", ev->score_a, ev->score_b);
  1103. } else if (gate_a) {
  1104. v.state = static_cast<int>(SceneState::BED);
  1105. v.confidence = ev->score_a / kTotalA;
  1106. // §12.4 C1 是 1 的**主判据**,但 score_A 只含 P1~P4 → C1-only 帧置信度为 0,
  1107. // 会被 TemporalVoter 的 min_confidence 挡掉(实测 A 片 C1=25/50 却全 255)。
  1108. // 给 C1 支撑的 1 一个明确下限;随后仍乘轮廓质量与多目标折减,低质量/多目标会自然压低。
  1109. if (h(EvidenceKey::C1)) { v.confidence = std::max(v.confidence, 0.75); }
  1110. v.reason = fmt2("bed: scoreA=%.1f/3.3 (spec 2.2 A)", ev->score_a, 0.0);
  1111. if (h(EvidenceKey::C1)) { v.reason += " | C1"; }
  1112. } else if (gate_b) {
  1113. v.state = static_cast<int>(SceneState::FLATBED);
  1114. v.confidence = ev->score_b / kTotalB;
  1115. v.reason = fmt2("flatbed: scoreB=%.1f/3.2 (spec 2.2 B)", ev->score_b, 0.0);
  1116. } else if (gate_0) {
  1117. v.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  1118. v.confidence = ev->score_c / kTotalC;
  1119. v.reason = fmt2("not on train: scoreC=%.1f/2.5 (spec 2.2 C)", ev->score_c, 0.0);
  1120. } else {
  1121. v.state = static_cast<int>(SceneState::UNKNOWN);
  1122. v.confidence = std::max({ev->score_a / kTotalA, ev->score_b / kTotalB, ev->score_c / kTotalC});
  1123. v.reason = fmt2("no gate satisfied: A=%.1f B=%.1f -> 255", ev->score_a, ev->score_b);
  1124. }
  1125. // ---------- ④ 自标尺失效 → 禁止输出 2(§2.3 ④ / §0 安全铁律)----------
  1126. if (!ev->scale_ok && v.state == static_cast<int>(SceneState::FLATBED)) {
  1127. v.state = static_cast<int>(SceneState::UNKNOWN);
  1128. v.diag = EdgeDiag::SCALE_FAIL;
  1129. v.reason += " | SCALE_OK=0 -> state 2 forbidden";
  1130. }
  1131. // ---------- 40 尺近满车:越界带不足时不允许 `2`(§5 / §12.8 Q2 ⑤)----------
  1132. if (ev->view_limited && v.state == static_cast<int>(SceneState::FLATBED)) {
  1133. v.state = static_cast<int>(SceneState::UNKNOWN);
  1134. v.diag = EdgeDiag::VIEW_LIMITED;
  1135. v.reason += " | VIEW_LIMITED (out-band too small) -> 255";
  1136. }
  1137. if (ev->view_limited && v.diag == EdgeDiag::NONE) { v.diag = EdgeDiag::VIEW_LIMITED; }
  1138. // ---------- ⑤ 证据项数不足 / 弃权(§2.3 ⑤ / §3.9)----------
  1139. if (v.state == static_cast<int>(SceneState::UNKNOWN) && !v.conflict) {
  1140. const bool insufficient = (a_hits < 2) ||
  1141. (!h(EvidenceKey::F2) && (h(EvidenceKey::F1) || h(EvidenceKey::F3)));
  1142. const bool low_scores = (ev->score_a < 1.8) && (ev->score_b < 1.7) && (ev->score_c < 2.0);
  1143. if (insufficient || low_scores) {
  1144. ev->abstain = true;
  1145. v.reason += " | ABSTAIN (spec 3.9)";
  1146. }
  1147. }
  1148. // ---------- 置信度(§2.4):× 轮廓质量因子;多目标只降置信度(§12.8 Q4)----------
  1149. v.confidence *= ctx.outline.quality;
  1150. if (ev->boxes_seen > 1) { v.confidence *= 0.80; }
  1151. if (v.state == static_cast<int>(SceneState::UNKNOWN)) {
  1152. v.confidence = std::min(v.confidence, 0.25);
  1153. }
  1154. if (v.confidence < 0.0) { v.confidence = 0.0; }
  1155. if (v.confidence > 1.0) { v.confidence = 1.0; }
  1156. return v;
  1157. }
  1158. } // namespace
  1159. // ---------------------------------------------------------------- 对外接口实现
  1160. EdgeEvidence::EdgeEvidence(const EdgeParams& params, const LineParams& lines)
  1161. : p_(params), l_(lines), gate_(params) {
  1162. l_.grad_pct = p_.grad_pct; // §7 的 edge.grad_pct 同时是"线段强度分位门"
  1163. }
  1164. EdgeResult EdgeEvidence::analyze(const GrayImage& gray, double ts) {
  1165. EdgeResult result;
  1166. result.ev.reason = "no frame";
  1167. result.ev.diag = EdgeDiag::NO_BOX;
  1168. // 0) 运动门控(§6):用**原始**灰度(位移与模糊是成像特性,与预处理无关)
  1169. const bool motion = gate_.update(gray, ts);
  1170. result.ev.motion = motion;
  1171. result.ev.motion_held_s = gate_.held_s();
  1172. if (gray.empty()) { return result; }
  1173. // 1) L0~L2:预处理 + 梯度 + 边缘 + 线段
  1174. FrameContext ctx;
  1175. {
  1176. long long sum = 0;
  1177. for (uint8_t v : gray.data) { sum += v; }
  1178. ctx.mean_gray = gray.data.empty() ? 0.0 : static_cast<double>(sum) / gray.data.size();
  1179. ctx.p05_gray = percentile_u8(gray, 0.05);
  1180. ctx.p95_gray = percentile_u8(gray, 0.95);
  1181. // 夜间(均值低)/ 雪天或逆光(灰度动态范围被压缩):都不冒险输出 1/2/0。
  1182. // 实测合成 night mean=67,snow p05..p95 = 140..177(spread 37),正常帧 spread≈73。
  1183. ctx.low_light = ctx.mean_gray < 80.0 || (ctx.p95_gray - ctx.p05_gray) < 50.0;
  1184. }
  1185. ctx.work = preprocess(gray, p_);
  1186. if (edge_trace_on()) {
  1187. std::fprintf(stderr, "frame mean=%.1f p05=%.1f p95=%.1f low_light=%d\n",
  1188. ctx.mean_gray, ctx.p05_gray, ctx.p95_gray, ctx.low_light ? 1 : 0);
  1189. }
  1190. ctx.grad = sobel(ctx.work);
  1191. ctx.edges = canny_lite(ctx.work, ctx.grad, l_.canny_lo_pct, l_.canny_hi_pct);
  1192. ctx.mag_ref = percentile(ctx.grad.mag, 0.60);
  1193. ctx.row_step_ref = row_step_reference(ctx.work, p_.strong_step_pct);
  1194. ctx.segs = extract_segments(ctx.work, ctx.grad, ctx.edges, l_, &ctx.strong_threshold);
  1195. // §3.2 ① 的**补充通道:专用竖直游程**(逐列近箱高的连续游程)。
  1196. // 为什么单开:通用通道在"箱体 + 车体 + 地面 + 钢轨连成一个巨连通域"时会先被水平结构耗尽
  1197. // 迭代预算、并把竖棱切碎 → 自标尺(= 全部高度带判据的**分母**)丢失或错位。
  1198. // 本通道对斜线天然免疫(单列只有 2~3 px),且只读未改动的 `edges`,把竖棱稳定拿回来。
  1199. {
  1200. const std::vector<Segment> vsegs = extract_vertical_runs(ctx.work, ctx.grad, ctx.edges, l_,
  1201. 0.5 * p_.near_edge_px, 4, &ctx.segs);
  1202. ctx.segs.insert(ctx.segs.end(), vsegs.begin(), vsegs.end());
  1203. }
  1204. result.ev.segments_total = static_cast<int>(ctx.segs.size());
  1205. result.ev.strong_threshold = ctx.strong_threshold;
  1206. // 2) L3:箱体轮廓 + 自标尺(§1.3 / §3.2)
  1207. ctx.outline = build_outline(ctx.segs, ctx.work, p_, &result.ev.boxes_seen);
  1208. result.ev.box_h_px = ctx.outline.near_len_px;
  1209. result.ev.box_w_px = ctx.outline.width_px;
  1210. result.ev.outline_quality = ctx.outline.quality;
  1211. result.ev.scale_ok = ctx.outline.ok && (ctx.outline.near_len_px >= p_.near_edge_px);
  1212. result.ev.px_per_m =
  1213. ctx.outline.near_len_px > 0.0 ? ctx.outline.near_len_px / p_.box_height_m : 0.0;
  1214. if (ctx.outline.ok) {
  1215. ctx.poly = ctx.outline.polygon();
  1216. ctx.x_min = ctx.poly[0].first;
  1217. ctx.x_max = ctx.poly[0].first;
  1218. for (const PointF& pt : ctx.poly) {
  1219. ctx.x_min = std::min(ctx.x_min, pt.first);
  1220. ctx.x_max = std::max(ctx.x_max, pt.first);
  1221. }
  1222. ctx.hm.y_bottom = ctx.outline.near_bottom.second;
  1223. ctx.hm.y_top = ctx.outline.near_top.second;
  1224. ctx.strip_w = p_.cross_ratio_hi * ctx.outline.width_px;
  1225. if (edge_trace_on()) {
  1226. std::fprintf(stderr,
  1227. "outline: near_top=(%.1f,%.1f) near_bot=(%.1f,%.1f) "
  1228. "far_top=(%.1f,%.1f) far_bot=(%.1f,%.1f) w=%.1f h=%.1f q=%.2f "
  1229. "x=[%.1f,%.1f] hm=[%.1f,%.1f]\n",
  1230. ctx.outline.near_top.first, ctx.outline.near_top.second,
  1231. ctx.outline.near_bottom.first, ctx.outline.near_bottom.second,
  1232. ctx.outline.far_top.first, ctx.outline.far_top.second,
  1233. ctx.outline.far_bottom.first, ctx.outline.far_bottom.second,
  1234. ctx.outline.width_px, ctx.outline.near_len_px, ctx.outline.quality,
  1235. ctx.x_min, ctx.x_max, ctx.hm.y_top, ctx.hm.y_bottom);
  1236. }
  1237. // 3) L5/L6:纹理掩膜 → 下身统计 → 三组证据(A / B / C)
  1238. const TextureMask mask = build_texture_mask(ctx, p_);
  1239. const BelowMetrics below = analyze_below(ctx, p_);
  1240. evaluate_a_group(ctx, p_, mask, below, &result.ev);
  1241. evaluate_b_group(ctx, p_, mask, below, &result.ev);
  1242. evaluate_c_group(ctx, p_, below, &result.ev);
  1243. }
  1244. // 4) L8:分数 → 硬门槛 → 优先级 → 置信度
  1245. compute_scores(&result.ev);
  1246. const Verdict v = classify(ctx, p_, &result.ev);
  1247. result.state = v.state;
  1248. result.confidence = v.confidence;
  1249. result.ev.diag = v.diag;
  1250. result.ev.reason = v.reason;
  1251. if (edge_trace_on()) {
  1252. std::fprintf(stderr, "verdict: state=%d conf=%.3f reason=%s\n", result.state,
  1253. result.confidence, result.ev.reason.c_str());
  1254. }
  1255. // 5) L9:运动门控 —— 本帧**不改变判定**(§2.3 ③)。
  1256. // 输出 state=255 + hold=true:上层 TemporalVoter 会走"保持上一状态"分支;
  1257. // 连续超时由 decision.hold_s / lost_timeout_s(0.6 s / 1.5 s)兜底,
  1258. // 与 edge.motion_hold_s(1.5 s)取值一致,可直接对照(§6)。
  1259. if (motion) {
  1260. result.ev.hold = true;
  1261. result.state = static_cast<int>(SceneState::UNKNOWN);
  1262. result.confidence = std::min(result.confidence, 0.20);
  1263. result.ev.diag = EdgeDiag::MOTION;
  1264. char buf[160];
  1265. std::snprintf(buf, sizeof(buf),
  1266. "MOTION=1: frame ignored (hold), moving for %.2fs (spec 6)", gate_.held_s());
  1267. result.ev.reason = std::string(buf) + " | " + result.ev.reason;
  1268. }
  1269. // 6) 缓存(日志 / 现场整定 / 调试 dump 用)
  1270. last_ = result.ev;
  1271. segments_ = ctx.segs;
  1272. outline_ = ctx.outline;
  1273. return result;
  1274. }
  1275. // ---------------------------------------------------------------- 运动门控(§6)
  1276. MotionGate::MotionGate(const EdgeParams& params) : p_(params) {}
  1277. void MotionGate::reset() {
  1278. prev_ = GrayImage();
  1279. last_ = GrayImage();
  1280. prev_mean_mag_ = -1.0;
  1281. still_run_ = 0;
  1282. motion_ = false;
  1283. motion_since_ = -1.0;
  1284. held_s_ = 0.0;
  1285. }
  1286. bool MotionGate::update(const GrayImage& gray, double ts) {
  1287. if (!p_.motion_gate || gray.empty()) {
  1288. motion_ = false;
  1289. held_s_ = 0.0;
  1290. motion_since_ = -1.0;
  1291. return false;
  1292. }
  1293. const double mean_mag = sobel(gray).mean_mag();
  1294. // 位移估计统一在 160×90 缩略图上做:与参考帧的缩略图同尺寸才能算投影互相关
  1295. const GrayImage cur = box_downscale(gray, 160, 90);
  1296. bool far = false; ///< 相对**参考帧**(最近静止帧)的累计位移超门限
  1297. bool blurred = false; ///< 相对参考帧的模糊指标超限(§6 ③)
  1298. bool step_still = false; ///< 与上一帧几乎完全一样(帧间无变化)→ 运动结束 / 允许重同步
  1299. constexpr double kStepStillEps = 0.25; // 灰阶:低于它="这一帧与上一帧没有变化"
  1300. constexpr int kStillFrames = 3; // 连续多少帧"无变化"才重同步参考帧(滞回)
  1301. // 帧间变化量 = 行 / 列投影的平均绝对差(灰阶)。只用来判断"画面是否已经不再变化"。
  1302. auto profile_diff = [](const GrayImage& a, const GrayImage& b) -> double {
  1303. double acc = 0.0;
  1304. int n = 0;
  1305. for (int x = 0; x < a.width; ++x) {
  1306. double sa = 0.0;
  1307. double sb = 0.0;
  1308. for (int y = 0; y < a.height; ++y) {
  1309. sa += static_cast<double>(a.at(x, y));
  1310. sb += static_cast<double>(b.at(x, y));
  1311. }
  1312. acc += std::fabs(sa - sb) / static_cast<double>(a.height);
  1313. ++n;
  1314. }
  1315. for (int y = 0; y < a.height; ++y) {
  1316. double sa = 0.0;
  1317. double sb = 0.0;
  1318. for (int x = 0; x < a.width; ++x) {
  1319. sa += static_cast<double>(a.at(x, y));
  1320. sb += static_cast<double>(b.at(x, y));
  1321. }
  1322. acc += std::fabs(sa - sb) / static_cast<double>(a.width);
  1323. ++n;
  1324. }
  1325. return n > 0 ? acc / static_cast<double>(n) : 0.0;
  1326. };
  1327. if (!prev_.empty() && prev_.width == cur.width && prev_.height == cur.height) {
  1328. // ② **累计位移**(当前帧 vs 参考帧 = 最近静止帧):行 / 列投影的一维互相关(SAD 最小)。
  1329. // 为什么是累计而不是"帧间":单帧位移会被缩略图量化抹平(8× 缩略时 6 px 恰好落在
  1330. // 一个像素格内)→ 慢速漂移(3~5 px/帧)永远不报警,而"车辆行走 / 箱体下放"正是慢速
  1331. // 持续位移;按累计口径,位移只要持续累积就必然超门限。
  1332. // 为什么用投影而不是稀疏光流:确定性、无第三方库、对"整幅平移"最敏感。
  1333. const int max_shift = static_cast<int>(p_.motion_shift_max_px * 2.0) + 2;
  1334. // 缩略图 → 原图的换算系数。门限 motion_shift_max_px 是**原图像素**(现场标定口径),
  1335. // 而互相关在 160×90 缩略图上做、估出来的是缩略图像素 → 必须先折算回原图再比较;
  1336. // 否则门限会随缩略倍数漂移(1280×720 是 8 倍 → 6 px 被悄悄放宽成 48 px,整幅平移反而漏检)。
  1337. const double px_per_thumb_x =
  1338. cur.width > 0 ? static_cast<double>(gray.width) / cur.width : 1.0;
  1339. const double px_per_thumb_y =
  1340. cur.height > 0 ? static_cast<double>(gray.height) / cur.height : 1.0;
  1341. // hit_limit = 最优位移落在搜索窗口边界 → 真实位移比窗口还大(必然超门限)。
  1342. auto axis_shift = [&](bool vertical, bool* hit_limit) -> int {
  1343. *hit_limit = false;
  1344. const int len = vertical ? cur.height : cur.width;
  1345. const int cross = vertical ? cur.width : cur.height;
  1346. std::vector<double> a(static_cast<std::size_t>(len), 0.0);
  1347. std::vector<double> b(static_cast<std::size_t>(len), 0.0);
  1348. for (int i = 0; i < len; ++i) {
  1349. double sa = 0.0;
  1350. double sb = 0.0;
  1351. for (int j = 0; j < cross; ++j) {
  1352. const int x = vertical ? j : i;
  1353. const int y = vertical ? i : j;
  1354. sa += static_cast<double>(prev_.at(x, y));
  1355. sb += static_cast<double>(cur.at(x, y));
  1356. }
  1357. a[static_cast<std::size_t>(i)] = sa / static_cast<double>(cross);
  1358. b[static_cast<std::size_t>(i)] = sb / static_cast<double>(cross);
  1359. }
  1360. double sad0 = 0.0;
  1361. for (int i = 0; i < len; ++i) {
  1362. sad0 += std::fabs(a[static_cast<std::size_t>(i)] - b[static_cast<std::size_t>(i)]);
  1363. }
  1364. sad0 /= static_cast<double>(len);
  1365. int best = 0;
  1366. double best_sad = sad0;
  1367. for (int s = -max_shift; s <= max_shift; ++s) {
  1368. if (s == 0) { continue; }
  1369. double sad = 0.0;
  1370. int n = 0;
  1371. for (int i = 0; i < len; ++i) {
  1372. const int k = i + s;
  1373. if (k < 0 || k >= len) { continue; }
  1374. sad += std::fabs(a[static_cast<std::size_t>(i)] -
  1375. b[static_cast<std::size_t>(k)]);
  1376. ++n;
  1377. }
  1378. if (n == 0) { continue; }
  1379. sad /= static_cast<double>(n);
  1380. if (sad < best_sad) {
  1381. best_sad = sad;
  1382. best = s;
  1383. }
  1384. }
  1385. // 只有"明显更优"才认这个位移(否则算噪声抖动 → 视为静止)。三条同时成立才算"真位移":
  1386. // ① 剖面本身有对比(sad0 ≥ 0.10 灰阶)—— 全平剖面(纯天空 / 全黑)不做位移搜索;
  1387. // ② 绝对增益 ≥ 0.10 灰阶 —— 压住"在 28 个候选位移里取最小"带来的噪声假阳性:静止场景的
  1388. // 相邻帧只差噪声,SAD 最小值天然比 s=0 低一点点,只看相对比例会把抖动误判成运动;
  1389. // ③ 相对增益 < 0.90 —— 与规范 §6 ② "明显更优" 同义。
  1390. const double gain = sad0 - best_sad;
  1391. if (sad0 >= 0.10 && gain >= 0.10 && best_sad < 0.90 * sad0) {
  1392. *hit_limit = std::fabs(static_cast<double>(best)) >= max_shift;
  1393. } else {
  1394. best = 0;
  1395. }
  1396. return best;
  1397. };
  1398. bool dx_hit = false;
  1399. bool dy_hit = false;
  1400. const int dx = axis_shift(false, &dx_hit);
  1401. const int dy = axis_shift(true, &dy_hit);
  1402. // 折算回**原图像素**再与门限比较;撞窗口边界同样按"超门限"处理。
  1403. far = dx_hit || dy_hit ||
  1404. std::fabs(static_cast<double>(dx) * px_per_thumb_x) > p_.motion_shift_max_px ||
  1405. std::fabs(static_cast<double>(dy) * px_per_thumb_y) > p_.motion_shift_max_px;
  1406. // ③ 运动模糊:梯度均值相对参考帧基线明显下降(§6 ③)
  1407. if (prev_mean_mag_ > 1e-6) { blurred = mean_mag < p_.motion_blur_ratio * prev_mean_mag_; }
  1408. // ④ 帧间已无变化?—— 运动**结束**的出口。若运动结束后仍拿旧参考帧比对,累计位移会永远
  1409. // 超门限 → 永久锁死在 MOTION;所以另设"连续 kStillFrames 帧帧间无变化 → 重同步参考帧"。
  1410. if (!last_.empty() && last_.width == cur.width && last_.height == cur.height) {
  1411. step_still = profile_diff(last_, cur) < kStepStillEps;
  1412. }
  1413. }
  1414. motion_ = far || blurred;
  1415. if (motion_) {
  1416. if (motion_since_ < 0.0) { motion_since_ = ts; }
  1417. held_s_ = (ts > motion_since_) ? (ts - motion_since_) : 0.0;
  1418. still_run_ = 0; // 运动中不重同步:位移要继续累积(慢速漂移迟早超门限)
  1419. } else {
  1420. motion_since_ = -1.0;
  1421. held_s_ = 0.0;
  1422. still_run_ = step_still ? (still_run_ + 1) : 0;
  1423. if (prev_.empty() || still_run_ >= kStillFrames) {
  1424. prev_ = cur; // 画面确实不再变化 → 参考帧挪过来(此后每帧都重同步,回到"逐帧"灵敏度)
  1425. prev_mean_mag_ = mean_mag;
  1426. }
  1427. }
  1428. // 只保留一张 160×90 参考帧 + 一张上一帧:投影统计够用,内存占用可忽略
  1429. last_ = cur;
  1430. return motion_;
  1431. }
  1432. // ---------------------------------------------------------------- 公共小函数
  1433. const char* edge_diag_label(EdgeDiag diag) {
  1434. switch (diag) {
  1435. case EdgeDiag::NONE: return "none";
  1436. case EdgeDiag::NO_BOX: return "no_box";
  1437. case EdgeDiag::VIEW_LIMITED: return "view_limited";
  1438. case EdgeDiag::SCALE_FAIL: return "scale_fail";
  1439. case EdgeDiag::CONFLICT: return "conflict";
  1440. case EdgeDiag::MOTION: return "motion";
  1441. }
  1442. return "none";
  1443. }
  1444. const char* evidence_key_name(EvidenceKey key) {
  1445. switch (key) {
  1446. case EvidenceKey::P1: return "P1";
  1447. case EvidenceKey::P2: return "P2";
  1448. case EvidenceKey::P3: return "P3";
  1449. case EvidenceKey::P4: return "P4";
  1450. case EvidenceKey::F1: return "F1";
  1451. case EvidenceKey::F2: return "F2";
  1452. case EvidenceKey::F3: return "F3";
  1453. case EvidenceKey::F4: return "F4";
  1454. case EvidenceKey::G1: return "G1";
  1455. case EvidenceKey::G2: return "G2";
  1456. case EvidenceKey::G3: return "G3";
  1457. case EvidenceKey::C1: return "C1";
  1458. case EvidenceKey::C2: return "C2";
  1459. case EvidenceKey::C3: return "C3";
  1460. case EvidenceKey::COUNT: break;
  1461. }
  1462. return "?";
  1463. }
  1464. std::vector<PointF> BoxOutline::polygon() const {
  1465. // 顺序:近端上角 → 远端上角 → 远端下角 → 近端下角(凸四边形,射线法判内外即可)
  1466. return {near_top, far_top, far_bottom, near_bottom};
  1467. }
  1468. std::string EdgeResult::evidence_summary() const {
  1469. std::string hits;
  1470. for (int i = 0; i < static_cast<int>(EvidenceKey::COUNT); ++i) {
  1471. if (ev.hit[i]) {
  1472. hits += evidence_key_name(static_cast<EvidenceKey>(i));
  1473. hits += " ";
  1474. }
  1475. }
  1476. if (hits.empty()) { hits = "- "; }
  1477. char buf[320];
  1478. std::snprintf(buf, sizeof(buf),
  1479. "[%s] sA=%.1f sB=%.1f sC=%.1f q=%.2f near=%.0fpx %.1fpx/m out=%.0f/%.0f "
  1480. "segs=%d ground=%.2f held=%.2fs diag=%s",
  1481. hits.c_str(), ev.score_a, ev.score_b, ev.score_c, ev.outline_quality, ev.box_h_px,
  1482. ev.px_per_m, ev.out_left_px, ev.out_right_px, ev.segments_total,
  1483. ev.ground_ratio_full, ev.motion_held_s, edge_diag_label(ev.diag));
  1484. return std::string(buf);
  1485. }
  1486. Observation EdgeResult::to_observation(double ts, long frame_id) const {
  1487. Observation obs;
  1488. obs.ts = ts;
  1489. obs.state = state;
  1490. obs.confidence = confidence;
  1491. obs.reason = evidence_summary();
  1492. obs.frame_id = frame_id;
  1493. return obs;
  1494. }
  1495. // ---------------------------------------------------------------- 证据 → 检测框(接口适配)
  1496. std::vector<Box> EdgeEvidence::to_boxes(const EdgeResult& result) const {
  1497. std::vector<Box> boxes;
  1498. if (!outline_.ok) { return boxes; }
  1499. const std::vector<PointF> poly = outline_.polygon();
  1500. double x1 = poly[0].first;
  1501. double x2 = poly[0].first;
  1502. double y1 = poly[0].second;
  1503. double y2 = poly[0].second;
  1504. for (const PointF& p : poly) {
  1505. x1 = std::min(x1, p.first);
  1506. x2 = std::max(x2, p.first);
  1507. y1 = std::min(y1, p.second);
  1508. y2 = std::max(y2, p.second);
  1509. }
  1510. // ① 箱体框(class = container):供 scene.py 的几何关联(support_overlap 等)继续使用
  1511. boxes.push_back(Box(static_cast<float>(x1), static_cast<float>(y1), static_cast<float>(x2),
  1512. static_cast<float>(y2), static_cast<float>(outline_.quality), 0, "container"));
  1513. // ② 车型框(class = bed / flatbed):框住"箱底以下 + 两侧越界带"的车体区域。
  1514. // 注意:这里给出的是**证据结论**(硬门槛 + 弃权之后),而不是模型的类别概率;
  1515. // score 直接取归一化证据分,便于上层日志与人工复核对齐。
  1516. if (result.state == static_cast<int>(SceneState::BED) ||
  1517. result.state == static_cast<int>(SceneState::FLATBED)) {
  1518. const double box_h = outline_.near_bottom.second - outline_.near_top.second; // >0
  1519. const double wide = 0.35 * (x2 - x1);
  1520. const double body_x1 = std::max(0.0, x1 - wide);
  1521. const double body_x2 = x2 + wide;
  1522. const double body_y1 = outline_.near_bottom.second;
  1523. const double body_y2 = body_y1 + 1.40 * box_h;
  1524. const char* name = result.state == static_cast<int>(SceneState::BED) ? "bed" : "flatbed";
  1525. const double raw = result.state == static_cast<int>(SceneState::BED)
  1526. ? result.ev.score_a / 3.3
  1527. : result.ev.score_b / 3.2;
  1528. boxes.push_back(Box(static_cast<float>(body_x1), static_cast<float>(body_y1),
  1529. static_cast<float>(body_x2), static_cast<float>(body_y2),
  1530. static_cast<float>(raw * outline_.quality), result.state, name));
  1531. }
  1532. return boxes;
  1533. }
  1534. void EdgeEvidence::note_window(bool t1_window, const EdgeResult& result) {
  1535. if (!t1_window) { return; }
  1536. last_t1_ = result;
  1537. has_t1_ = true;
  1538. }
  1539. // ---------------------------------------------------------------- Detector 适配器(§10)
  1540. EdgeEvidenceDetector::EdgeEvidenceDetector(const EdgeParams& params, const LineParams& lines)
  1541. : evidence_(params, lines) {}
  1542. std::vector<Box> EdgeEvidenceDetector::infer(const Frame& frame) {
  1543. if (frame.gray == nullptr) {
  1544. last_result_ = EdgeResult();
  1545. last_result_.ev.diag = EdgeDiag::NO_BOX;
  1546. last_result_.ev.reason = "edge backend: Frame.gray == nullptr (取帧侧未填灰度图)";
  1547. return {};
  1548. }
  1549. last_result_ = evidence_.analyze(*frame.gray, frame.ts);
  1550. return evidence_.to_boxes(last_result_);
  1551. }
  1552. bool EdgeEvidenceDetector::warmup(std::string* error) {
  1553. if (error != nullptr) { error->clear(); }
  1554. return true; // 无模型、无引擎:不需要预热(首次 analyze 会分配工作缓冲)
  1555. }
  1556. } // namespace portcv