edge_v2.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. #include "portcv/edge_v2.hpp"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <limits>
  6. #include <utility>
  7. namespace portcv {
  8. namespace {
  9. constexpr double kPi = 3.14159265358979323846;
  10. /// 箱底与车面直接贴合时 `flat_contact` 把 gap 归零;允许 1 px 抗锯齿误差。
  11. /// 该分支不需要 `px_per_m`(侧视/近距时常拿不到可靠标尺),但仍走结构/稳定/运动门。
  12. constexpr double kContactGapPx = 1.0;
  13. void horizontal_bands(const GrayImage& gray, int x0, int y0, int x1, int y1,
  14. int min_h, int max_h, std::vector<V2Band>* bright,
  15. std::vector<V2Band>* dark) {
  16. if (bright != nullptr) { bright->clear(); }
  17. if (dark != nullptr) { dark->clear(); }
  18. if (gray.empty() || x1 <= x0 || y1 <= y0) { return; }
  19. x0 = std::max(0, x0);
  20. y0 = std::max(0, y0);
  21. x1 = std::min(gray.width, x1);
  22. y1 = std::min(gray.height, y1);
  23. if (x1 <= x0 || y1 <= y0) { return; }
  24. // 与 Python `horizontal_bands` 逐算子同口径:
  25. // 3×3 高斯 → 行均值 → 纵向中心差分(= 3 行 Sobel)。
  26. // 不能先对行均值做 5 行平滑:等效核被拉长到 7 行,箱底 3~4 px 暗带
  27. // 会和车体上缘亮带合并,箱底 y 被抬高 30~40 px。
  28. GrayImage crop(x1 - x0, y1 - y0, 0);
  29. for (int y = y0; y < y1; ++y) {
  30. for (int x = x0; x < x1; ++x) { crop.set(x - x0, y - y0, gray.at(x, y)); }
  31. }
  32. gaussian3x3_inplace(&crop);
  33. std::vector<double> mean(static_cast<std::size_t>(y1 - y0), 0.0);
  34. for (int y = 0; y < crop.height; ++y) {
  35. double sum = 0.0;
  36. for (int x = 0; x < crop.width; ++x) { sum += crop.at(x, y); }
  37. mean[static_cast<std::size_t>(y)] = sum / static_cast<double>(crop.width);
  38. }
  39. const int n = static_cast<int>(mean.size());
  40. if (n < 8) { return; }
  41. std::vector<double> deriv(static_cast<std::size_t>(n), 0.0);
  42. std::vector<double> abs_deriv;
  43. abs_deriv.reserve(static_cast<std::size_t>(n));
  44. for (int i = 1; i + 1 < n; ++i) {
  45. deriv[static_cast<std::size_t>(i)] =
  46. mean[static_cast<std::size_t>(i + 1)] - mean[static_cast<std::size_t>(i - 1)];
  47. abs_deriv.push_back(std::fabs(deriv[static_cast<std::size_t>(i)]));
  48. }
  49. double sum = 0.0;
  50. for (double v : abs_deriv) { sum += v; }
  51. const double avg = abs_deriv.empty() ? 0.0 : sum / abs_deriv.size();
  52. double var = 0.0;
  53. for (double v : abs_deriv) { var += (v - avg) * (v - avg); }
  54. const double stddev = abs_deriv.empty() ? 0.0 : std::sqrt(var / abs_deriv.size());
  55. const double limit = avg + 0.9 * stddev;
  56. std::vector<int> candidates;
  57. for (int i = 1; i + 1 < n; ++i) {
  58. const double mag = std::fabs(deriv[static_cast<std::size_t>(i)]);
  59. if (mag < limit) { continue; }
  60. if (mag >= std::fabs(deriv[static_cast<std::size_t>(i - 1)]) &&
  61. mag >= std::fabs(deriv[static_cast<std::size_t>(i + 1)])) {
  62. candidates.push_back(i);
  63. }
  64. }
  65. // 同一道边缘常在相邻 1~2 行出现多个极值(箱底 3 px 暗带:
  66. // y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内严格
  67. // 最大,167 会压掉 168,168 又压掉 170,最终只剩一个负峰,暗带
  68. // 无法配对 → no_box。改为 ±1 局部极大 + 3 px 贪心抑制。
  69. std::stable_sort(candidates.begin(), candidates.end(), [&](int a, int b) {
  70. return std::fabs(deriv[static_cast<std::size_t>(a)]) >
  71. std::fabs(deriv[static_cast<std::size_t>(b)]);
  72. });
  73. const int min_sep = std::max(2, min_h);
  74. std::vector<int> picked;
  75. for (int i : candidates) {
  76. bool keep = true;
  77. for (int j : picked) {
  78. if (std::abs(i - j) < min_sep) { keep = false; break; }
  79. }
  80. if (keep) { picked.push_back(i); }
  81. }
  82. std::sort(picked.begin(), picked.end());
  83. std::vector<std::pair<int, double>> events;
  84. events.reserve(picked.size());
  85. for (int i : picked) {
  86. events.push_back({i, deriv[static_cast<std::size_t>(i)]});
  87. }
  88. for (std::size_t j = 0; j + 1 < events.size(); ++j) {
  89. const int i1 = events[j].first;
  90. const int i2 = events[j + 1].first;
  91. const double v1 = events[j].second;
  92. const double v2 = events[j + 1].second;
  93. const int height = i2 - i1;
  94. if (height < min_h || height > max_h) { continue; }
  95. const double strength = std::min(std::fabs(v1), std::fabs(v2));
  96. if (strength <= 0.0) { continue; }
  97. // 约定与 Python 一致:v1>0>v2 = 亮带;v1<0<v2 = 暗带。
  98. const V2Band band{static_cast<double>(y0 + i1), static_cast<double>(y0 + i2), strength};
  99. if (v1 > 0.0 && v2 < 0.0) {
  100. if (bright != nullptr) { bright->push_back(band); }
  101. } else if (v1 < 0.0 && v2 > 0.0) {
  102. if (dark != nullptr) { dark->push_back(band); }
  103. }
  104. }
  105. auto by_strength = [](const V2Band& a, const V2Band& b) { return a.strength > b.strength; };
  106. if (bright != nullptr) {
  107. std::stable_sort(bright->begin(), bright->end(), by_strength);
  108. if (bright->size() > 12) { bright->resize(12); }
  109. }
  110. if (dark != nullptr) {
  111. std::stable_sort(dark->begin(), dark->end(), by_strength);
  112. if (dark->size() > 12) { dark->resize(12); }
  113. }
  114. }
  115. void pick_box_and_bed(const std::vector<V2Band>& bright, const std::vector<V2Band>& dark,
  116. int frame_h, double box_max_ratio, double bed_search_px,
  117. V2Band* box, V2Band* bed) {
  118. if (box != nullptr) { *box = V2Band(); }
  119. if (bed != nullptr) { *bed = V2Band(); }
  120. std::vector<const V2Band*> strong;
  121. double max_strength = 0.0;
  122. for (const V2Band& b : dark) {
  123. if (b.y1 <= box_max_ratio * frame_h && b.y0 >= 0.02 * frame_h) {
  124. max_strength = std::max(max_strength, b.strength);
  125. }
  126. }
  127. for (const V2Band& b : dark) {
  128. if (b.y1 <= box_max_ratio * frame_h && b.y0 >= 0.02 * frame_h &&
  129. b.strength >= 0.45 * max_strength) {
  130. strong.push_back(&b);
  131. }
  132. }
  133. if (strong.empty()) { return; }
  134. const V2Band* best_box = strong.front();
  135. for (const V2Band* b : strong) {
  136. if (b->y0 < best_box->y0) { best_box = b; }
  137. }
  138. if (box != nullptr) { *box = *best_box; }
  139. if (bed == nullptr) { return; }
  140. const V2Band* best_bed = nullptr;
  141. for (const V2Band& b : bright) {
  142. if (b.y0 >= best_box->y1 - 1.0 && b.y0 <= best_box->y1 + bed_search_px) {
  143. if (best_bed == nullptr || b.y0 < best_bed->y0) { best_bed = &b; }
  144. }
  145. }
  146. if (best_bed != nullptr) { *bed = *best_bed; }
  147. }
  148. double ground_like_ratio(const GrayImage& crop, const SobelResult& grad,
  149. const std::vector<Segment>& segs, int block_px, double lo,
  150. double hi) {
  151. if (crop.empty()) { return 0.0; }
  152. const float mag_ref = percentile(grad.mag, 0.60);
  153. const int b = std::max(6, block_px);
  154. int total = 0;
  155. int ground = 0;
  156. for (int by = 0; by < crop.height; by += b) {
  157. for (int bx = 0; bx < crop.width; bx += b) {
  158. const int ex = std::min(crop.width, bx + b);
  159. const int ey = std::min(crop.height, by + b);
  160. int hot = 0;
  161. int n = 0;
  162. for (int y = by; y < ey; ++y) {
  163. for (int x = bx; x < ex; ++x) {
  164. if (grad.mag_at(x, y) > mag_ref) { ++hot; }
  165. ++n;
  166. }
  167. }
  168. if (n <= 0) { continue; }
  169. const double density = static_cast<double>(hot) / static_cast<double>(n);
  170. bool long_line = false;
  171. for (const Segment& s : segs) {
  172. if (s.length < 0.6 * b) { continue; }
  173. if (s.cx() < bx || s.cx() > ex || s.cy() < by || s.cy() > ey) { continue; }
  174. long_line = true;
  175. break;
  176. }
  177. ++total;
  178. if (!long_line && density >= lo && density <= hi) { ++ground; }
  179. }
  180. }
  181. return total > 0 ? static_cast<double>(ground) / static_cast<double>(total) : 0.0;
  182. }
  183. std::vector<double> cluster_positions(const std::vector<double>& values, double gap) {
  184. std::vector<double> ordered = values;
  185. std::sort(ordered.begin(), ordered.end());
  186. std::vector<double> centers;
  187. if (ordered.empty()) { return centers; }
  188. std::vector<double> cluster{ordered.front()};
  189. for (std::size_t i = 1; i < ordered.size(); ++i) {
  190. if (ordered[i] - cluster.back() <= gap) {
  191. cluster.push_back(ordered[i]);
  192. } else {
  193. centers.push_back(cluster[cluster.size() / 2]);
  194. cluster.assign(1, ordered[i]);
  195. }
  196. }
  197. if (!cluster.empty()) { centers.push_back(cluster[cluster.size() / 2]); }
  198. return centers;
  199. }
  200. double median(std::vector<double> values) {
  201. if (values.empty()) { return 0.0; }
  202. std::sort(values.begin(), values.end());
  203. const std::size_t n = values.size();
  204. return n % 2 == 1 ? values[n / 2] : 0.5 * (values[n / 2 - 1] + values[n / 2]);
  205. }
  206. double pstdev(const std::vector<double>& values, double mean) {
  207. if (values.size() < 2) { return 0.0; }
  208. double sum = 0.0;
  209. for (double v : values) { sum += (v - mean) * (v - mean); }
  210. return std::sqrt(sum / static_cast<double>(values.size()));
  211. }
  212. /// 车体 ROI(空车/无箱)上的门板/立柱证据(P0-Q4 兜底用)。
  213. GrayImage crop_gray(const GrayImage& src, int x0, int y0, int x1, int y1);
  214. struct BodyEvidence {
  215. int posts = 0;
  216. double span_ratio = 0.0;
  217. double opacity = 0.0;
  218. int diagonal = 0;
  219. double height = 0.0;
  220. };
  221. BodyEvidence measure_body(const GrayImage& work, int x0, int y0, int x1, int y1,
  222. const EdgeV2Params& p, double scale) {
  223. BodyEvidence out;
  224. GrayImage crop = crop_gray(work, x0, y0, x1, y1);
  225. if (crop.empty() || crop.height < 8) { return out; }
  226. out.height = static_cast<double>(crop.height);
  227. const SobelResult grad = sobel(crop);
  228. const std::vector<uint8_t> edges =
  229. canny_lite(crop, grad, p.canny_lo_pct, p.canny_hi_pct);
  230. LineParams lp;
  231. lp.min_points = 12;
  232. lp.grad_pct = 0.90;
  233. const std::vector<Segment> segs = extract_segments(crop, grad, edges, lp);
  234. const std::vector<Segment> runs = extract_vertical_runs(
  235. crop, grad, edges, lp, std::max(8.0, 0.60 * crop.height), 8, nullptr);
  236. std::vector<Segment> all_segs = segs;
  237. all_segs.insert(all_segs.end(), runs.begin(), runs.end());
  238. const double post_min_len = p.min_post_len_ratio * crop.height;
  239. std::vector<double> post_x;
  240. int diagonal = 0;
  241. for (const Segment& s : all_segs) {
  242. if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
  243. post_x.push_back(s.cx());
  244. } else if (std::fabs(s.angle_deg) >= 20.0 && std::fabs(s.angle_deg) <= 70.0) {
  245. ++diagonal;
  246. }
  247. }
  248. const std::vector<double> posts =
  249. cluster_positions(post_x, std::max(3.0, 9.0 * scale));
  250. out.posts = static_cast<int>(posts.size());
  251. out.diagonal = diagonal;
  252. if (posts.size() >= 2) {
  253. out.span_ratio = (posts.back() - posts.front()) /
  254. std::max(1.0, static_cast<double>(crop.width));
  255. }
  256. const double ground = ground_like_ratio(crop, grad, all_segs, p.ground_block_px,
  257. p.ground_density_lo, p.ground_density_hi);
  258. out.opacity = std::max(0.0, std::min(1.0, 1.0 - ground));
  259. return out;
  260. }
  261. std::string fmt(const char* pattern, double value) {
  262. char buf[128];
  263. std::snprintf(buf, sizeof(buf), pattern, value);
  264. return std::string(buf);
  265. }
  266. } // namespace
  267. double find_texture_top_y(const GrayImage& gray, const int window[4],
  268. const EdgeV2Params& p) {
  269. if (!p.texture_top_enable || gray.empty()) { return -1.0; }
  270. const SobelResult grad = sobel(gray);
  271. const int x0 = std::max(0, std::min(window[0], gray.width));
  272. const int x1 = std::min(gray.width, std::max(x0, window[2]));
  273. const int block = std::max(4, p.texture_block_px);
  274. const int nb = (x1 - x0) / block;
  275. if (nb < 2) { return -1.0; }
  276. std::vector<double> cov(static_cast<std::size_t>(gray.height), 0.0);
  277. for (int y = 0; y < gray.height; ++y) {
  278. int hit = 0;
  279. for (int i = 0; i < nb; ++i) {
  280. const int bx = x0 + i * block;
  281. int cnt = 0;
  282. for (int x = bx; x < bx + block; ++x) {
  283. const std::size_t idx =
  284. static_cast<std::size_t>(y) * static_cast<std::size_t>(gray.width) +
  285. static_cast<std::size_t>(x);
  286. if (std::fabs(grad.gx[idx]) >= p.texture_grad_th) { ++cnt; }
  287. }
  288. if (static_cast<double>(cnt) / static_cast<double>(block) >=
  289. p.texture_block_hit_ratio) {
  290. ++hit;
  291. }
  292. }
  293. cov[static_cast<std::size_t>(y)] =
  294. static_cast<double>(hit) / static_cast<double>(nb);
  295. }
  296. const int smooth = std::max(1, p.texture_smooth_rows);
  297. std::vector<double> sm(static_cast<std::size_t>(gray.height), 0.0);
  298. for (int y = 0; y < gray.height; ++y) {
  299. const int a = std::max(0, y - smooth / 2);
  300. const int b = std::min(gray.height - 1, y + smooth / 2);
  301. double sum = 0.0;
  302. int n = 0;
  303. for (int k = a; k <= b; ++k) {
  304. sum += cov[static_cast<std::size_t>(k)];
  305. ++n;
  306. }
  307. sm[static_cast<std::size_t>(y)] = n > 0 ? sum / static_cast<double>(n) : 0.0;
  308. }
  309. const int run = std::max(1, p.texture_run_rows);
  310. for (int y = std::max(0, window[1]); y + run <= gray.height; ++y) {
  311. bool ok = true;
  312. for (int k = 0; k < run; ++k) {
  313. if (sm[static_cast<std::size_t>(y + k)] < p.texture_coverage_min) {
  314. ok = false;
  315. break;
  316. }
  317. }
  318. if (ok) { return static_cast<double>(y); }
  319. }
  320. return -1.0;
  321. }
  322. bool EvidenceV2Result::publishable(bool require_commit) const {
  323. if (state != 0 && state != 1 && state != 2) { return false; }
  324. return !require_commit || committed;
  325. }
  326. Observation EvidenceV2Result::to_observation(double ts, long frame_id,
  327. bool require_commit) const {
  328. Observation obs;
  329. obs.ts = ts;
  330. obs.frame_id = frame_id;
  331. const bool ok = publishable(require_commit);
  332. obs.state = ok ? state : static_cast<int>(SceneState::UNKNOWN);
  333. obs.confidence = ok ? confidence : 0.0;
  334. obs.reason = std::string("v2:") + (ok ? "ok" : "abstain") + " view=" + view +
  335. " posts=" + std::to_string(door_posts) + " opacity=" +
  336. fmt("%.2f", wall_opacity) + " gap=" +
  337. (gap_px.has_value() ? fmt("%.0f", *gap_px) + "px" : "n/a") +
  338. " commit=" + commit_reason;
  339. if (!ok && !abstain_reason.empty()) { obs.reason += " reason=" + abstain_reason; }
  340. return obs;
  341. }
  342. std::string EvidenceV2Result::evidence_summary() const {
  343. std::string out = "state=" + std::to_string(state) + " view=" + view +
  344. " top=" + (texture_top_y > 0.0 ? fmt("%.1f", texture_top_y) : "n/a") +
  345. " posts=" + std::to_string(door_posts) + " opacity=" +
  346. fmt("%.2f", wall_opacity) + " ground=" + fmt("%.2f", ground_ratio);
  347. out += " deck=" + std::string(deck_edge ? "1" : "0");
  348. out += " under_deck=" + std::string(under_deck ? "1" : "0");
  349. out += " body=(" + std::to_string(body_posts) + "," +
  350. fmt("%.2f", body_span) + "," + fmt("%.2f", body_opacity) + "," +
  351. std::to_string(body_diagonal) + ")";
  352. out += " gap=" + (gap_px.has_value() ? fmt("%.1f", *gap_px) + "px" : "n/a");
  353. out += " gap_m=" + (gap_m.has_value() ? fmt("%.3f", *gap_m) : "n/a");
  354. out += " box=" + (box_bottom_y.has_value() ? fmt("%.1f", *box_bottom_y) : "n/a") +
  355. " bed=" + (bed_top_y.has_value() ? fmt("%.1f", *bed_top_y) : "n/a");
  356. out += " phase=" + phase + " commit=" + (committed ? "1" : "0") +
  357. "(" + commit_reason + ")";
  358. out += " roi=[" + std::to_string(below_roi[0]) + "," + std::to_string(below_roi[1]) +
  359. "," + std::to_string(below_roi[2]) + "," + std::to_string(below_roi[3]) + "]";
  360. out += " edges=" + std::to_string(edge_pixels) + " segs=" + std::to_string(line_segments) +
  361. " vrun=" + std::to_string(vertical_runs);
  362. out += " gpost=" + std::to_string(generic_posts) + " rpost=" + std::to_string(run_posts);
  363. out += " spcv=" + (post_spacing_cv.has_value() ? fmt("%.2f", *post_spacing_cv) : "n/a");
  364. out += " postx=[";
  365. for (std::size_t i = 0; i < post_positions.size(); ++i) {
  366. if (i != 0) { out += ","; }
  367. out += fmt("%.0f", post_positions[i]);
  368. }
  369. out += "]";
  370. if (hoist_high) {
  371. out += " hoist=" + std::string(hoist_injected ? "injected" : "image") +
  372. "(lines=" + std::to_string(hoist_lines) + ",cables=" + std::to_string(hoist_cables) +
  373. ",probe=" + std::to_string(hoist_limit_px) + "px)";
  374. }
  375. if (spreader_contact) {
  376. out += " spreader=1(run=" + std::to_string(spreader_dark_run_px) + "px)";
  377. }
  378. if (!abstain_reason.empty()) { out += " abstain=" + abstain_reason; }
  379. return out;
  380. }
  381. V2CommitTracker::V2CommitTracker(const V2CommitParams& params) : p_(params) {
  382. if (p_.stable_frames < 1) { p_.stable_frames = 1; }
  383. if (p_.structure_frames < 1) { p_.structure_frames = 1; }
  384. p_.min_structure_hits = std::max(0.0, std::min(1.0, p_.min_structure_hits));
  385. last_ = V2CommitState();
  386. }
  387. void V2CommitTracker::reset() {
  388. samples_.clear();
  389. last_ts_ = 0.0;
  390. last_ = V2CommitState();
  391. last_.reason = "reset";
  392. }
  393. int V2CommitTracker::same_state_run(int state) const {
  394. int count = 0;
  395. for (auto it = samples_.rbegin(); it != samples_.rend(); ++it) {
  396. if (it->state != state) { break; }
  397. ++count;
  398. }
  399. return count;
  400. }
  401. bool V2CommitTracker::gap_ok(const Sample& s, bool arrival) const {
  402. if (s.state == 0 || arrival) { return true; }
  403. if (!s.gap_px.has_value() || *s.gap_px > p_.gap_px_hard_max) { return false; }
  404. // 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
  405. if (*s.gap_px <= kContactGapPx) { return true; }
  406. return s.gap_m.has_value() && *s.gap_m <= p_.gap_m_max;
  407. }
  408. std::optional<double> V2CommitTracker::gap_slope(int n) const {
  409. if (n <= 0 || samples_.empty()) { return std::nullopt; }
  410. const int start = std::max(0, static_cast<int>(samples_.size()) - n);
  411. std::optional<double> t0, g0, t1, g1;
  412. for (int i = start; i < static_cast<int>(samples_.size()); ++i) {
  413. const Sample& s = samples_[static_cast<std::size_t>(i)];
  414. if (!s.gap_m.has_value()) { continue; }
  415. if (!t0.has_value()) { t0 = s.ts; g0 = s.gap_m; }
  416. t1 = s.ts;
  417. g1 = s.gap_m;
  418. }
  419. if (!t0.has_value() || !t1.has_value() || (*t1 - *t0) <= 1e-6) { return std::nullopt; }
  420. return (*g1 - *g0) / (*t1 - *t0);
  421. }
  422. V2CommitState V2CommitTracker::update(double ts, int state, std::optional<double> gap_m,
  423. std::optional<double> gap_px, double structure_hits,
  424. bool motion_ok, bool view_known, bool plc_arrived,
  425. bool plc_spreader_released, bool hoist_high) {
  426. double now = ts;
  427. if (now < last_ts_) { now = last_ts_; }
  428. last_ts_ = now;
  429. const bool structure_ok = structure_hits >= p_.min_structure_hits;
  430. const bool arrival = p_.use_plc_arrival && (plc_arrived || plc_spreader_released);
  431. auto make = [&](bool committed, const std::string& phase, const std::string& reason,
  432. int stable, int structure) {
  433. V2CommitState s;
  434. s.committed = committed;
  435. s.phase = phase;
  436. s.reason = reason;
  437. s.gap_m = gap_m;
  438. s.gap_px = gap_px;
  439. s.stable_frames = stable;
  440. s.structure_frames = structure;
  441. s.plc_arrival = arrival;
  442. s.hoist_high = hoist_high;
  443. last_ = s;
  444. return s;
  445. };
  446. // 吊具/钢缆/臂架高悬:箱体未落位,优先于所有几何门,且不写样本窗口。
  447. if (hoist_high) {
  448. return make(false, "T3", "hoist_high", 0, 0);
  449. }
  450. if (state != 0 && state != 1 && state != 2) {
  451. return make(false, motion_ok ? "T1" : "T3", "state_unknown", 0, 0);
  452. }
  453. if (state == 1 && !p_.allow_state1) {
  454. return make(false, "T1", "state1_disabled", 0, 0);
  455. }
  456. if (state == 2 && !p_.allow_state2) {
  457. samples_.push_back(Sample{now, state, gap_m, gap_px, structure_ok, motion_ok});
  458. while (samples_.size() > 256) { samples_.pop_front(); }
  459. return make(false, "T1", "state2_disabled", 0, 0);
  460. }
  461. samples_.push_back(Sample{now, state, gap_m, gap_px, structure_ok, motion_ok});
  462. while (samples_.size() > 256) { samples_.pop_front(); }
  463. if (!motion_ok && p_.require_motion_ok) {
  464. return make(false, "T3", "motion", 0, 0);
  465. }
  466. if (!view_known && p_.require_view_known) {
  467. return make(false, "T1", "view_unknown", 0, 0);
  468. }
  469. bool gap_gate = true;
  470. if (state == 1 || state == 2) {
  471. const bool contact = gap_px.has_value() && *gap_px <= kContactGapPx;
  472. gap_gate = arrival ||
  473. (gap_px.has_value() && *gap_px <= p_.gap_px_hard_max &&
  474. (contact || (gap_m.has_value() && *gap_m <= p_.gap_m_max)));
  475. }
  476. const int window_n = std::max(p_.stable_frames, p_.structure_frames);
  477. const int start = std::max(0, static_cast<int>(samples_.size()) - window_n);
  478. int structure_n = 0;
  479. int gap_n = 0;
  480. for (int i = start; i < static_cast<int>(samples_.size()); ++i) {
  481. const Sample& s = samples_[static_cast<std::size_t>(i)];
  482. if (s.structure_ok) { ++structure_n; }
  483. if (gap_ok(s, arrival)) { ++gap_n; }
  484. }
  485. const int stable_n = same_state_run(state);
  486. const std::optional<double> slope = gap_slope(window_n);
  487. const bool stable_enough = stable_n >= p_.stable_frames;
  488. const bool structure_enough = structure_n >= p_.structure_frames;
  489. const bool gap_enough = gap_n >= p_.stable_frames;
  490. const bool not_rising = !slope.has_value() || *slope <= p_.max_gap_rise_m;
  491. const bool committed = gap_gate && stable_enough && structure_enough && gap_enough && not_rising;
  492. std::string reason;
  493. if (!gap_gate) { reason += "gap"; }
  494. if (!stable_enough) {
  495. if (!reason.empty()) { reason += ","; }
  496. reason += "stable=" + std::to_string(stable_n) + "/" + std::to_string(p_.stable_frames);
  497. }
  498. if (!structure_enough) {
  499. if (!reason.empty()) { reason += ","; }
  500. reason += "structure=" + std::to_string(structure_n) + "/" +
  501. std::to_string(p_.structure_frames);
  502. }
  503. if (!gap_enough) {
  504. if (!reason.empty()) { reason += ","; }
  505. reason += "gap_window=" + std::to_string(gap_n) + "/" +
  506. std::to_string(p_.stable_frames);
  507. }
  508. if (!not_rising) {
  509. if (!reason.empty()) { reason += ","; }
  510. reason += "gap_rising";
  511. }
  512. if (committed) {
  513. reason = arrival ? "commit:plc_arrival" : "commit";
  514. } else if (!reason.empty()) {
  515. reason = "wait:" + reason;
  516. } else {
  517. reason = "wait";
  518. }
  519. V2CommitState out = make(committed, gap_gate ? "T2" : "T1", reason, stable_n, structure_n);
  520. out.gap_slope_m_per_s = slope;
  521. last_ = out;
  522. return out;
  523. }
  524. EdgeV2::EdgeV2(const EdgeV2Params& params, const V2CommitParams& commit)
  525. : p_(params), tracker_(commit) {}
  526. void EdgeV2::reset() {
  527. tracker_.reset();
  528. prev_thumb_ = GrayImage();
  529. prev_mag_ = 0.0;
  530. last_ = EvidenceV2Result();
  531. last_.view = p_.view;
  532. }
  533. namespace {
  534. GrayImage crop_gray(const GrayImage& src, int x0, int y0, int x1, int y1) {
  535. x0 = std::max(0, x0);
  536. y0 = std::max(0, y0);
  537. x1 = std::min(src.width, x1);
  538. y1 = std::min(src.height, y1);
  539. if (x1 <= x0 || y1 <= y0) { return GrayImage(); }
  540. GrayImage out(x1 - x0, y1 - y0, 0);
  541. for (int y = y0; y < y1; ++y) {
  542. for (int x = x0; x < x1; ++x) { out.set(x - x0, y - y0, src.at(x, y)); }
  543. }
  544. return out;
  545. }
  546. } // namespace
  547. bool EdgeV2::motion_ok(const GrayImage& work, double* diff, double* ratio) {
  548. if (diff != nullptr) { *diff = 0.0; }
  549. if (ratio != nullptr) { *ratio = 1.0; }
  550. if (work.empty()) { return true; }
  551. GrayImage thumb = box_downscale(work, 160, 90);
  552. if (thumb.empty()) { return true; }
  553. const double mag = sobel(thumb).mean_mag();
  554. if (prev_thumb_.empty()) {
  555. prev_thumb_ = thumb;
  556. prev_mag_ = mag;
  557. return true;
  558. }
  559. double sum = 0.0;
  560. int n = 0;
  561. for (int y = 0; y < thumb.height; ++y) {
  562. for (int x = 0; x < thumb.width; ++x) {
  563. sum += std::fabs(static_cast<double>(thumb.at(x, y)) -
  564. static_cast<double>(prev_thumb_.at(x, y)));
  565. ++n;
  566. }
  567. }
  568. const double d = n > 0 ? sum / n : 0.0;
  569. const double r = prev_mag_ > 1e-6 ? mag / prev_mag_ : 1.0;
  570. if (diff != nullptr) { *diff = d; }
  571. if (ratio != nullptr) { *ratio = r; }
  572. prev_thumb_ = thumb;
  573. prev_mag_ = prev_mag_ > 0.0 ? 0.8 * prev_mag_ + 0.2 * mag : mag;
  574. return d <= p_.motion_diff_max && r >= p_.motion_grad_ratio_min;
  575. }
  576. std::optional<double> EdgeV2::scale_from_vertical(const GrayImage& work, const V2Band& box,
  577. const int window[4], double scale,
  578. double* run_px) {
  579. if (run_px != nullptr) { *run_px = 0.0; }
  580. if (p_.px_per_m > 0.0) { return p_.px_per_m; }
  581. const int x0 = std::max(0, window[0]);
  582. const int y0 = std::max(0, window[1]);
  583. const int x1 = std::min(work.width, window[2]);
  584. const int y1 = std::min(work.height, static_cast<int>(std::floor(box.y0)));
  585. GrayImage upper = crop_gray(work, x0, y0, x1, y1);
  586. if (upper.empty()) { return std::nullopt; }
  587. const SobelResult grad = sobel(upper);
  588. const std::vector<uint8_t> edges =
  589. canny_lite(upper, grad, p_.canny_lo_pct, p_.canny_hi_pct);
  590. LineParams lp;
  591. lp.min_points = 12;
  592. lp.grad_pct = 0.90;
  593. const std::vector<Segment> segs = extract_segments(upper, grad, edges, lp);
  594. double best = 0.0;
  595. for (const Segment& s : segs) {
  596. if (std::fabs(s.angle_deg) < 65.0) { continue; }
  597. const double dy = std::fabs(s.y2 - s.y1);
  598. if (dy > best) { best = dy; }
  599. }
  600. if (best < p_.min_scale_px * scale) { return std::nullopt; }
  601. if (run_px != nullptr) { *run_px = best / scale; }
  602. return (best / scale) / p_.box_height_m;
  603. }
  604. EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing_cv,
  605. double opacity, double ground, bool deck, int wheels,
  606. std::optional<double> gap_px, bool motion_ok,
  607. const std::string& view,
  608. double below_roi_h_px,
  609. bool under_deck, double post_spacing_px,
  610. int diagonal_braces, double post_span_ratio) const {
  611. ClassifyResult r;
  612. if (view == "unknown") {
  613. r.reason = "view_unknown";
  614. return r;
  615. }
  616. if (!motion_ok) {
  617. r.reason = "motion";
  618. return r;
  619. }
  620. // C++ 线段通道对低对比地面纹理比 Python HoughLinesP 更敏感:B(平车)中
  621. // 8~10 条互不等距的伪竖线会落进 [min_door_posts, max_door_posts] 并被误判 1。
  622. // 真实门板阵列的间距是规则的;≥8 根且 CV>1.5 视为杂波,不构成“门板阵列”。
  623. // (<8 根时样本太少,CV 不可靠,不做该判据。)
  624. const bool post_array_regular =
  625. posts < 8 || !spacing_cv.has_value() || *spacing_cv <= 1.5;
  626. // 反向补偿:自定义拟合会把同一根门板的两侧描边合并(Python Hough 常算 2 根),
  627. // A 类稳定帧实测 Python 5~8 根、C++ 4 根。posts = min_door_posts-1 时若
  628. // 侧墙不透明且间距规则,仍按门板阵列处理(不放松到更低,避免 B 的杂波)。
  629. const int relaxed_min_posts = p_.min_door_posts > 1 ? p_.min_door_posts - 1 : 1;
  630. const bool relaxed_post_array =
  631. posts >= relaxed_min_posts && opacity >= 0.65 &&
  632. (!spacing_cv.has_value() || *spacing_cv <= 1.0);
  633. const bool posts_ok = posts >= p_.min_door_posts || relaxed_post_array;
  634. // P0-Q3:门板立柱间距下限(原图像素)。容器侧壁瓦楞 10~20 px,
  635. // C70 门板 63~185 px → 低于下限不构成门板阵列(防"上层箱坐在下层箱上"→ 1)。
  636. // post_spacing_px <= 0 表示不可用,不用它拒绝。
  637. const bool post_spacing_ok =
  638. post_spacing_px <= 0.0 || post_spacing_px >= p_.min_post_spacing_px;
  639. // P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。
  640. // 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权;
  641. // 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。
  642. const bool contact_bed = !gap_px.has_value() || *gap_px <= 1.0;
  643. const bool doors_ok =
  644. !contact_bed || diagonal_braces >= p_.min_diagonal_braces;
  645. // 冲突时:A 的真实门板阵列可能只剩 min_posts-1 根(见上),同时又误检到
  646. // 车面边梁;此时按“门板阵列”优先(Python 对应帧 deck=False,不会冲突)。
  647. const bool prefer_bed_on_conflict =
  648. posts < p_.min_door_posts && relaxed_post_array;
  649. // P0-Q3:门板阵列必须横跨足够宽(>= min_post_span_ratio × 工作宽度)。
  650. // 平车车轮/制动梁/端部结构只在窄区给 5~7 条伪立柱(B f1771~f1773:
  651. // postx=666..859,跨度 ~20%),真实 C70 门板阵列横跨车体(A ~66%)。
  652. const bool post_span_ok = post_span_ratio >= p_.min_post_span_ratio;
  653. const bool bed_evidence =
  654. posts_ok && posts <= p_.max_door_posts &&
  655. opacity >= p_.min_wall_opacity && post_array_regular &&
  656. post_spacing_ok && doors_ok && post_span_ok &&
  657. (!gap_px.has_value() || *gap_px <= p_.max_bed_gap_px) &&
  658. (!spacing_cv.has_value() || *spacing_cv <= p_.max_post_spacing_cv);
  659. // 敞车(1)需要真的看得见"门板立柱阵列":箱底以下的动态 ROI 太矮时,
  660. // 立柱只有 20~27 px,与地面/钢轨纹理不可区分(B 片段 f30/f31/f36~f38 实测
  661. // 提出 5~16 条伪立柱并被投票成"已发布 1",真值 2)。不足门限 → 弃权,
  662. // 不判 1;平车(2)分支不受此限(它靠车面边梁,不需要门板)。
  663. const bool bed_roi_ok = below_roi_h_px >= static_cast<double>(p_.min_bed_roi_px);
  664. const bool bed_strong = bed_evidence && bed_roi_ok;
  665. const bool flat_strong =
  666. posts <= p_.flat_max_door_posts && deck && under_deck &&
  667. (!gap_px.has_value() || *gap_px <= p_.max_flat_gap_px);
  668. if (bed_strong && flat_strong && !prefer_bed_on_conflict) {
  669. r.reason = "conflict_1_2";
  670. return r;
  671. }
  672. if (bed_evidence && !bed_roi_ok && !flat_strong) {
  673. r.reason = "bed_roi_small";
  674. return r;
  675. }
  676. if (bed_strong) {
  677. r.state = static_cast<int>(SceneState::BED);
  678. r.confidence = std::min(1.0, 0.55 + 0.25 * std::min(1.0, posts / 8.0) +
  679. 0.15 * opacity);
  680. r.structure_hits = std::min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity);
  681. r.reason = "wall_posts";
  682. return r;
  683. }
  684. if (flat_strong) {
  685. r.state = static_cast<int>(SceneState::FLATBED);
  686. r.confidence = std::min(1.0, 0.60 + 0.20 * ground +
  687. 0.10 * std::max(0.0, 1.0 - posts / 4.0));
  688. r.structure_hits = std::min(1.0, 0.55 + 0.15 * ground +
  689. 0.10 * std::max(0.0, 1.0 - posts / 4.0));
  690. r.reason = "deck_edge";
  691. return r;
  692. }
  693. (void)wheels;
  694. if (posts <= 1 && ground >= p_.min_zero_ground_ratio && !deck) {
  695. r.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  696. r.confidence = std::min(1.0, 0.55 + 0.30 * ground);
  697. r.structure_hits = std::min(1.0, 0.50 + 0.40 * ground);
  698. r.reason = "ground_only";
  699. return r;
  700. }
  701. r.reason = "weak_evidence";
  702. return r;
  703. }
  704. EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arrived,
  705. bool plc_spreader_released, bool hoist_high) {
  706. EvidenceV2Result out;
  707. out.view = p_.view;
  708. if (gray.empty()) {
  709. out.abstain_reason = "no_image";
  710. out.commit_reason = "no_image";
  711. last_ = out;
  712. return out;
  713. }
  714. double scale = 1.0;
  715. GrayImage work = resize_long_side(gray, p_.work_width, &scale);
  716. if (work.empty()) {
  717. out.abstain_reason = "no_image";
  718. out.commit_reason = "no_image";
  719. last_ = out;
  720. return out;
  721. }
  722. // 与 Python 同口径:只做 INTER_AREA 缩放,不再额外中值/高斯预滤波。
  723. // 额外滤波会把箱底 3~4 px 的暗带与车体上缘亮带糊在一起,箱底下沿被抬到
  724. // 408 而真值在 445,动态 ROI 因此整段错位(A1 实测 posts 10 → 3)。
  725. double motion_diff = 0.0;
  726. double motion_ratio = 1.0;
  727. const bool still = motion_ok(work, &motion_diff, &motion_ratio);
  728. const int window[4] = {
  729. static_cast<int>(p_.window[0] * work.width),
  730. static_cast<int>(p_.window[1] * work.height),
  731. static_cast<int>(p_.window[2] * work.width),
  732. static_cast<int>(p_.window[3] * work.height),
  733. };
  734. std::vector<V2Band> bright;
  735. std::vector<V2Band> dark;
  736. // P0-Q4:先找“竖向纹理车体顶”,把车体顶以上的天空电线/水印从候选带里剔除。
  737. // 不移动窗口:近距画面车体顶≈窗口顶,门槛自然不触发;远距/带天空画面才生效。
  738. const double texture_top = find_texture_top_y(work, window, p_);
  739. out.texture_top_y =
  740. texture_top > 0.0 ? texture_top / std::max(scale, 1e-6) : 0.0;
  741. horizontal_bands(work, window[0], window[1], window[2], window[3],
  742. std::max(1, static_cast<int>(p_.band_min_h * scale)),
  743. std::max(6, static_cast<int>(p_.band_max_h_ratio * work.height)),
  744. &bright, &dark);
  745. if (texture_top > 0.0 &&
  746. texture_top > window[1] + 0.05 * work.height) {
  747. const double margin = p_.texture_top_margin_ratio * work.height;
  748. const std::vector<V2Band> bright_all = bright;
  749. const std::vector<V2Band> dark_all = dark;
  750. const auto filter_above = [&](std::vector<V2Band>& bands) {
  751. std::vector<V2Band> kept;
  752. for (const V2Band& b : bands) {
  753. if (b.y1 >= texture_top - margin) { kept.push_back(b); }
  754. }
  755. if (!kept.empty()) { bands.swap(kept); }
  756. };
  757. filter_above(bright);
  758. filter_above(dark);
  759. if (bright.empty()) { bright = bright_all; }
  760. if (dark.empty()) { dark = dark_all; }
  761. }
  762. const double box_hint = std::max(80.0, 0.40 * work.height);
  763. V2Band box;
  764. V2Band bed;
  765. pick_box_and_bed(bright, dark, work.height, p_.box_bottom_max_ratio,
  766. std::max(24.0, p_.bed_search_ratio * box_hint), &box, &bed);
  767. if (box.height() <= 0.0 && !dark.empty()) {
  768. double best = 0.0;
  769. for (const V2Band& b : dark) {
  770. if (b.y0 >= 0.03 * work.height && b.y1 <= 0.90 * work.height &&
  771. b.strength > best) {
  772. box = b;
  773. best = b.strength;
  774. }
  775. }
  776. }
  777. if (box.height() <= 0.0) {
  778. out.motion_ok = still;
  779. out.abstain_reason = "no_box";
  780. out.commit_reason = "no_box";
  781. out.phase = still ? "T1" : "T3";
  782. last_ = out;
  783. return out;
  784. }
  785. if (bed.height() <= 0.0) {
  786. double best = std::numeric_limits<double>::max();
  787. for (const V2Band& b : bright) {
  788. if (b.y0 >= box.y1 - 1.0 && b.y0 < best) {
  789. bed = b;
  790. best = b.y0;
  791. }
  792. }
  793. }
  794. // P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/
  795. // 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里
  796. // `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。
  797. const double est_h = std::max(60.0, box.y0 - 0.05 * work.height);
  798. bool thick_contact = false;
  799. if (bed.height() > 0.0 && bed.y0 <= box.y1 + 1.0 &&
  800. bed.height() > p_.contact_max_h_ratio * est_h) {
  801. thick_contact = true;
  802. bed = V2Band{};
  803. }
  804. double vertical_run = 0.0;
  805. const std::optional<double> px_per_m =
  806. scale_from_vertical(work, box, window, scale, &vertical_run);
  807. std::optional<double> box_h;
  808. if (px_per_m.has_value()) {
  809. box_h = *px_per_m * p_.box_height_m;
  810. } else if (vertical_run > 0.0) {
  811. box_h = vertical_run;
  812. }
  813. std::optional<double> box_top;
  814. if (box_h.has_value()) {
  815. box_top = std::max(0.0, box.y1 / std::max(scale, 1e-6) - *box_h);
  816. }
  817. // ---------------- P0-0 图像侧安全门(吊具高悬 / 吊具仍夹箱) ----------------
  818. // 与 Python 同序:调用方/PLC 注入了 hoist_high 就直接用;否则做图像检测。
  819. // 命中即整帧弃权,并且**不累计** commit 窗口(V2CommitTracker 内部早返回),
  820. // 所以它压得住"几何证据连续 5 帧都成立、但箱还在半空"这一类最危险的误判。
  821. bool hoist_flag = hoist_high;
  822. HoistCues hoist_cues;
  823. SpreaderCues spreader_cues;
  824. if (!hoist_flag && (p_.reject_hoist_high || p_.reject_spreader_contact)) {
  825. // 没有可靠箱高时按"箱底暗带往上 0.35 画幅"保守估计(与 Python 同口径)。
  826. const double inv_scale = 1.0 / std::max(scale, 1e-6);
  827. const double probe_top = box_top.has_value()
  828. ? *box_top
  829. : std::max(0.0, box.y0 * inv_scale - 0.35 * gray.height);
  830. if (p_.reject_hoist_high) {
  831. hoist_cues = detect_hoist_high(gray, probe_top, p_.hoist);
  832. }
  833. if (p_.reject_spreader_contact) {
  834. spreader_cues = detect_spreader_contact(
  835. gray, static_cast<int>(window[0] * inv_scale),
  836. static_cast<int>(box.y0 * inv_scale), static_cast<int>(window[2] * inv_scale),
  837. static_cast<int>(box.y1 * inv_scale), p_.spreader);
  838. }
  839. hoist_flag = hoist_cues.hoist_high || spreader_cues.contact;
  840. }
  841. // (est_h 在"贴合亮带厚度门"处已算好,此处复用。)
  842. // 箱底贴近画面底边时,若仍跳过 7% 箱高,动态 ROI 会整段落到画面外,
  843. // 平车车面边梁/地板线看不到(近距 192 px 帧:箱底 y=170,底部只剩
  844. // 21 px)。此时只留 2 px 保护带,与 Python 同口径。
  845. double below_start = std::max(2.0, p_.below_start_ratio * est_h);
  846. const double min_below_h = p_.below_min_height_px * std::max(scale, 1e-6);
  847. if (static_cast<double>(work.height - 1) - box.y1 <= below_start + min_below_h) {
  848. below_start = 2.0;
  849. }
  850. const int y0w = std::min(
  851. work.height - 2,
  852. static_cast<int>(std::ceil(box.y1 + below_start)));
  853. const double below_h = std::max(
  854. min_below_h,
  855. std::min(p_.below_height_ratio * est_h, 0.30 * work.height));
  856. const int y1w = std::min(
  857. work.height - 1,
  858. std::max(static_cast<int>(y0w + below_h), static_cast<int>(box.y1 + 0.10 * est_h)));
  859. const int x0w = std::max(0, static_cast<int>(0.05 * work.width));
  860. const int x1w = std::min(work.width - 1, static_cast<int>(0.95 * work.width));
  861. GrayImage crop = crop_gray(work, x0w, y0w, x1w, std::max(y0w + 8, y1w));
  862. if (crop.empty()) {
  863. out.motion_ok = still;
  864. out.abstain_reason = "roi_empty";
  865. out.commit_reason = "roi_empty";
  866. last_ = out;
  867. return out;
  868. }
  869. // 与 Python `detect_structure_v2` 同口径:ROI 内先 CLAHE(clip=2.0, 8×8) 再提边。
  870. // 真机低对比 / 逆光片段不做光照归一,门板竖棱会整段掉到 Canny 阈值以下
  871. // (A1 实测:不加时 vrun 只剩 3 根,加后回到 8–10 根)。
  872. clahe_lite_inplace(&crop, 8, 2.0);
  873. const SobelResult grad = sobel(crop);
  874. const std::vector<uint8_t> edges =
  875. canny_lite(crop, grad, p_.canny_lo_pct, p_.canny_hi_pct);
  876. LineParams lp;
  877. lp.min_points = 12;
  878. lp.grad_pct = 0.90;
  879. const std::vector<Segment> segs = extract_segments(crop, grad, edges, lp);
  880. long long hot = 0;
  881. for (uint8_t e : edges) { if (e != 0) { ++hot; } }
  882. const double edge_density = edges.empty()
  883. ? 0.0
  884. : static_cast<double>(hot) / static_cast<double>(edges.size());
  885. const double roi_h = static_cast<double>(crop.height);
  886. // 专用竖直游程通道:箱体+车体+地面连成一大块时,通用通道会把竖棱切碎。
  887. // 断口 8 px:横梁/斜撑横穿门板时会造成 3~5 px 的真实断口,2 px 会把长竖棱切没。
  888. // 长度门用 0.60×ROI:门板立柱是贯穿整个箱底以下 ROI 的长竖棱;8 px 断口会把
  889. // 地面纹理的短竖纹也接成 0.3~0.5×ROI 的伪立柱(B 实拍实测 posts 5~6 → 误判 1)。
  890. const std::vector<Segment> vertical_runs = extract_vertical_runs(
  891. crop, grad, edges, lp, std::max(8.0, 0.60 * roi_h), 8, &segs);
  892. std::vector<Segment> all_segs = segs;
  893. all_segs.insert(all_segs.end(), vertical_runs.begin(), vertical_runs.end());
  894. out.line_segments = static_cast<int>(segs.size());
  895. out.vertical_runs = static_cast<int>(vertical_runs.size());
  896. out.edge_pixels = static_cast<int>(hot);
  897. std::vector<double> post_x;
  898. int diagonal = 0;
  899. bool deck_edge = false;
  900. // Python HoughLinesP 把车面边梁给成一条长线;C++ 的自定义拟合会把同一条边梁
  901. // 按强横梁断口拆成 2~3 段(B 落位帧实测:Python deck=True,C++ 0)。
  902. // 这里按 0.25×width 计长(≈ 原 0.55×width 门限的 45%),与拆段后的最长段匹配。
  903. const double deck_min_len = std::max(20.0, p_.deck_min_len_ratio * 0.25 * work.width);
  904. const double post_min_len = p_.min_post_len_ratio * roi_h;
  905. const auto collect_post_x = [&](const std::vector<Segment>& source) {
  906. std::vector<double> xs;
  907. for (const Segment& s : source) {
  908. if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
  909. xs.push_back(s.cx());
  910. }
  911. }
  912. return xs;
  913. };
  914. for (const Segment& s : all_segs) {
  915. if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
  916. post_x.push_back(s.cx());
  917. } else if (std::fabs(s.angle_deg) <= 25.0) {
  918. const double y_abs = y0w + s.cy();
  919. // `-2` 会把箱体自身的下侧梁当成车面边梁(A 的稳定帧因此 deck=1,
  920. // 与 Python 的 deck=0 相反);C++ 拟合出的箱底线正好落在 box.y1,
  921. // 所以这里要求边梁在箱底**下方** ≥2 px。B 落位帧的间距为 4~30 px,不受影响。
  922. if (s.length >= deck_min_len &&
  923. y_abs >= box.y1 + 2.0 && y_abs <= box.y1 + 0.35 * roi_h) {
  924. deck_edge = true;
  925. }
  926. } else if (std::fabs(s.angle_deg) >= 20.0 && std::fabs(s.angle_deg) <= 70.0) {
  927. ++diagonal;
  928. }
  929. }
  930. const std::vector<double> posts =
  931. cluster_positions(post_x, std::max(3.0, 9.0 * scale));
  932. out.generic_posts = static_cast<int>(
  933. cluster_positions(collect_post_x(segs), std::max(3.0, 9.0 * scale)).size());
  934. out.run_posts = static_cast<int>(
  935. cluster_positions(collect_post_x(vertical_runs), std::max(3.0, 9.0 * scale)).size());
  936. out.post_positions = posts;
  937. std::optional<double> spacing_median;
  938. std::optional<double> spacing_cv;
  939. if (posts.size() >= 2) {
  940. std::vector<double> spacings;
  941. for (std::size_t i = 1; i < posts.size(); ++i) {
  942. spacings.push_back(posts[i] - posts[i - 1]);
  943. }
  944. const double med = median(spacings);
  945. spacing_median = med;
  946. if (spacings.size() >= 2 && med > 1e-6) {
  947. spacing_cv = pstdev(spacings, med) / med;
  948. }
  949. }
  950. const double ground = ground_like_ratio(
  951. crop, grad, all_segs, p_.ground_block_px, p_.ground_density_lo, p_.ground_density_hi);
  952. const double opacity = std::max(0.0, std::min(1.0, 1.0 - ground));
  953. // 侧视平车(X70A)的箱底与车面直接贴合:车面边梁就在箱底下沿,
  954. // 动态 ROI 从箱底下方 7% 箱高开始,边梁会落在 ROI 之外,Hough 水平线
  955. // 通道看不到它(实拍图 deck=False、gap 被错取成 62.9 px → weak_evidence)。
  956. // 这里补一条“贴合车面”证据:箱底下沿紧邻一条**薄亮边**(车面边梁;
  957. // 地面/下层箱顶/月台是厚亮面,由 contact_max_h_ratio 排除),
  958. // 且门板数 ≤4、下半幅不是连续地面。
  959. // P0-Q3:薄边门限取 1.5% 画幅(至少 4 px)。旧值 3% 在 720p 下要 ≥21.6 px,
  960. // 会把侧视 X70 的 8~9 px 车面边梁排除,只剩厚亮面(地面/箱顶)能命中 ——
  961. // 方向刚好反了。A 的 5~8 px 箱底下侧梁仍低于门限,不会误判。
  962. const double min_contact_h = std::max(4.0, 0.015 * work.height);
  963. V2Band contact_band;
  964. for (const V2Band& b : bright) {
  965. if (b.y0 >= box.y1 - 1.0 && b.y0 < box.y1 + 1.0 &&
  966. b.height() >= min_contact_h && b.height() > contact_band.height()) {
  967. contact_band = b;
  968. }
  969. }
  970. // P0-Q3:贴合亮带也必须是"薄边"。地面/下层箱顶/月台是厚亮面,
  971. // 只靠"箱底紧邻亮带"会把地面堆料判成平车(现场合成 ground 场景实测过)。
  972. if (contact_band.height() > 0.0 &&
  973. contact_band.height() > p_.contact_max_h_ratio * est_h) {
  974. contact_band = V2Band{};
  975. }
  976. const bool flat_contact =
  977. !thick_contact && contact_band.height() > 0.0 &&
  978. static_cast<int>(posts.size()) <= p_.flat_max_door_posts &&
  979. opacity >= p_.min_wall_opacity &&
  980. // 近距/落位帧车面本身占满动态 ROI,分块“地面样”会偏低,
  981. // 因此不能要求 ground >= 0.4;只需排除连续地面(>=0.65)。
  982. // 与 Python `_classify` 的 flat_strong 同口径。
  983. ground < p_.min_zero_ground_ratio;
  984. if (flat_contact) {
  985. bed = contact_band; // 车面亮带 = 箱底直接接触的 deck edge
  986. deck_edge = true;
  987. }
  988. // P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。
  989. // 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。
  990. // 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。
  991. bool under_deck = false;
  992. if (bed.height() > 0.0) {
  993. const auto row_mean = [&](int x0, int x1, int y0, int y1) -> double {
  994. x0 = std::max(0, std::min(x0, work.width));
  995. x1 = std::max(x0, std::min(x1, work.width));
  996. y0 = std::max(0, std::min(y0, work.height));
  997. y1 = std::max(y0, std::min(y1, work.height));
  998. if (x1 <= x0 || y1 <= y0) { return 0.0; }
  999. double sum = 0.0;
  1000. long long n = 0;
  1001. for (int y = y0; y < y1; ++y) {
  1002. for (int x = x0; x < x1; ++x) {
  1003. sum += static_cast<double>(work.at(x, y));
  1004. ++n;
  1005. }
  1006. }
  1007. return n > 0 ? sum / static_cast<double>(n) : 0.0;
  1008. };
  1009. const double band_mean = row_mean(
  1010. window[0], window[2], static_cast<int>(std::lround(bed.y0)),
  1011. static_cast<int>(std::lround(bed.y1)));
  1012. const int probe_h = std::max(
  1013. 2, static_cast<int>(std::lround(p_.under_deck_min_h_ratio * work.height)));
  1014. const int search_h = std::max(
  1015. probe_h + 1,
  1016. static_cast<int>(std::lround(p_.under_deck_search_h_ratio * work.height)));
  1017. const int probe_y0 = std::max(0, static_cast<int>(std::lround(bed.y1)));
  1018. const int probe_y1 = std::min(work.height - 1, probe_y0 + search_h);
  1019. double darkest = std::numeric_limits<double>::max();
  1020. for (int y = probe_y0; y + probe_h <= probe_y1; ++y) {
  1021. darkest = std::min(darkest, row_mean(window[0], window[2], y, y + probe_h));
  1022. }
  1023. under_deck = darkest < std::numeric_limits<double>::max() &&
  1024. darkest <= band_mean - p_.under_deck_dark_delta;
  1025. }
  1026. deck_edge = deck_edge && under_deck;
  1027. std::optional<double> gap_px;
  1028. if (bed.height() > 0.0) {
  1029. gap_px = std::max(0.0, (bed.y0 - box.y1) / std::max(scale, 1e-6));
  1030. }
  1031. std::optional<double> gap_m;
  1032. if (gap_px.has_value() && px_per_m.has_value() && *px_per_m > 0.0) {
  1033. gap_m = *gap_px / *px_per_m;
  1034. }
  1035. const double post_spacing_px_orig =
  1036. spacing_median.has_value() ? *spacing_median / std::max(scale, 1e-6) : 0.0;
  1037. // 门板阵列的横向跨度(工作坐标,归一化到工作宽度)。
  1038. double post_span_ratio = 0.0;
  1039. if (out.post_positions.size() >= 2) {
  1040. post_span_ratio = (out.post_positions.back() - out.post_positions.front()) /
  1041. std::max(1.0, static_cast<double>(work.width));
  1042. }
  1043. const ClassifyResult cls = classify(
  1044. static_cast<int>(posts.size()), spacing_cv, opacity, ground, deck_edge, 0, gap_px,
  1045. still, p_.view, crop.height / std::max(scale, 1e-6), under_deck,
  1046. post_spacing_px_orig, diagonal, post_span_ratio);
  1047. // P0-Q4:空车/无箱兜底。正常“箱底以下”路径给不出 1(例如空 C70 的
  1048. // 箱底是车体内部的一条横梁,下面数不到立柱)时,用纹理车体 ROI 再数一次
  1049. // 门板立柱;只有“上方能看到天空/车体顶”且正常路径不是 1 时才启用。
  1050. int final_state = cls.state;
  1051. double final_conf = cls.confidence;
  1052. double final_hits = cls.structure_hits;
  1053. std::string final_reason = cls.reason;
  1054. std::optional<double> commit_gap_px = gap_px;
  1055. std::optional<double> commit_gap_m = gap_m;
  1056. BodyEvidence body;
  1057. bool body_override = false;
  1058. int body_y0 = 0;
  1059. int body_y1 = 0;
  1060. if (p_.body_fallback_enable && texture_top > 0.0 && cls.state != 1 &&
  1061. texture_top > window[1] + 0.05 * work.height) {
  1062. body_y0 = std::max(window[1], static_cast<int>(std::lround(texture_top)));
  1063. body_y1 = std::min(
  1064. window[3], static_cast<int>(std::lround(
  1065. texture_top + p_.body_bottom_ratio *
  1066. (window[3] - texture_top))));
  1067. if (body_y1 > body_y0) {
  1068. body = measure_body(work, window[0], body_y0, window[2], body_y1, p_, scale);
  1069. const double body_h_orig = body.height / std::max(scale, 1e-6);
  1070. if (body_h_orig >= static_cast<double>(p_.body_min_roi_px) &&
  1071. body.posts >= p_.min_door_posts &&
  1072. body.span_ratio >= p_.min_post_span_ratio &&
  1073. body.opacity >= p_.body_min_opacity &&
  1074. body.diagonal >= p_.min_diagonal_braces) {
  1075. body_override = true;
  1076. final_state = 1;
  1077. final_conf = std::min(
  1078. 1.0, 0.55 + 0.25 * std::min(1.0, body.posts / 8.0) +
  1079. 0.15 * body.opacity);
  1080. final_hits = std::min(
  1081. 1.0, 0.40 + 0.05 * body.posts + 0.20 * body.opacity);
  1082. final_reason = "body_fallback_wall";
  1083. commit_gap_px = 0.0;
  1084. commit_gap_m = 0.0;
  1085. }
  1086. }
  1087. }
  1088. // 安全兜底:能看到“车体顶(上方有天空)”且正常路径给 2,但箱底以下
  1089. // 一根立柱都没有、箱体还在车体内部 → 这是空车/无箱的歧义帧,绝不判 2。
  1090. if (!body_override && texture_top > 0.0 && cls.state == 2 &&
  1091. static_cast<int>(posts.size()) == 0 &&
  1092. box.y1 > texture_top + 0.02 * work.height) {
  1093. final_state = 255;
  1094. final_conf = 0.0;
  1095. final_hits = 0.0;
  1096. final_reason = "ambiguous_empty_vehicle";
  1097. }
  1098. const V2CommitState commit = tracker_.update(
  1099. ts, final_state, commit_gap_m, commit_gap_px, final_hits, still,
  1100. p_.view != "unknown", plc_arrived, plc_spreader_released, hoist_flag);
  1101. out.state = final_state;
  1102. out.confidence = final_conf;
  1103. out.view = p_.view;
  1104. out.body_posts = body.posts;
  1105. out.body_span = body.span_ratio;
  1106. out.body_opacity = body.opacity;
  1107. out.body_diagonal = body.diagonal;
  1108. out.box_bottom_y = box.y1 / std::max(scale, 1e-6);
  1109. out.box_top_y = box_top;
  1110. out.box_h_px = box_h;
  1111. out.px_per_m = px_per_m;
  1112. out.scale_ok = px_per_m.has_value();
  1113. if (bed.height() > 0.0) { out.bed_top_y = bed.y0 / std::max(scale, 1e-6); }
  1114. out.gap_px = commit_gap_px;
  1115. out.gap_m = commit_gap_m;
  1116. if (body_override) {
  1117. out.door_posts = body.posts;
  1118. out.diagonal_braces = body.diagonal;
  1119. out.wall_opacity = body.opacity;
  1120. out.deck_edge = false;
  1121. out.under_deck = false;
  1122. out.ground_ratio = 1.0 - body.opacity;
  1123. } else {
  1124. out.door_posts = static_cast<int>(posts.size());
  1125. if (spacing_median.has_value()) {
  1126. out.post_spacing_px = *spacing_median / std::max(scale, 1e-6);
  1127. }
  1128. out.post_spacing_cv = spacing_cv;
  1129. out.diagonal_braces = diagonal;
  1130. out.wall_opacity = opacity;
  1131. out.deck_edge = deck_edge;
  1132. out.under_deck = under_deck;
  1133. out.ground_ratio = ground;
  1134. }
  1135. out.phase = still ? commit.phase : "T3";
  1136. out.committed = commit.committed;
  1137. out.commit_reason = commit.reason;
  1138. out.stable_frames = commit.stable_frames;
  1139. out.structure_frames = commit.structure_frames;
  1140. out.motion_ok = still;
  1141. out.hoist_high = hoist_flag;
  1142. out.hoist_injected = hoist_high;
  1143. out.hoist_lines = hoist_cues.horizontal_lines;
  1144. out.hoist_cables = hoist_cues.cables;
  1145. out.hoist_limit_px = hoist_cues.limit_px;
  1146. out.spreader_contact = spreader_cues.contact;
  1147. out.spreader_dark_run_px = spreader_cues.dark_run_px;
  1148. // 弃权原因要能直接回答"为什么不用这一帧":吊具未松开与吊具高悬是两件事,
  1149. // 现场排查方向不同(前者看开锁信号,后者看起升高度),所以这里分开写。
  1150. out.abstain_reason = !hoist_flag
  1151. ? (final_state == 255 ? final_reason : "")
  1152. : (spreader_cues.contact ? "spreader_contact" : "hoist_high");
  1153. if (body_override) {
  1154. out.below_roi[0] = static_cast<int>(std::lround(window[0] / scale));
  1155. out.below_roi[1] = static_cast<int>(std::lround(body_y0 / scale));
  1156. out.below_roi[2] = static_cast<int>(std::lround(window[2] / scale));
  1157. out.below_roi[3] = static_cast<int>(std::lround(body_y1 / scale));
  1158. } else {
  1159. out.below_roi[0] = static_cast<int>(std::lround(x0w / scale));
  1160. out.below_roi[1] = static_cast<int>(std::lround(y0w / scale));
  1161. out.below_roi[2] = static_cast<int>(std::lround(x1w / scale));
  1162. out.below_roi[3] = static_cast<int>(std::lround((y0w + crop.height) / scale));
  1163. }
  1164. out.class_reason = final_reason;
  1165. last_ = out;
  1166. (void)edge_density;
  1167. (void)motion_diff;
  1168. (void)motion_ratio;
  1169. return out;
  1170. }
  1171. } // namespace portcv