| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236 |
- #include "portcv/edge_v2.hpp"
- #include <algorithm>
- #include <cmath>
- #include <cstdio>
- #include <limits>
- #include <utility>
- namespace portcv {
- namespace {
- constexpr double kPi = 3.14159265358979323846;
- /// 箱底与车面直接贴合时 `flat_contact` 把 gap 归零;允许 1 px 抗锯齿误差。
- /// 该分支不需要 `px_per_m`(侧视/近距时常拿不到可靠标尺),但仍走结构/稳定/运动门。
- constexpr double kContactGapPx = 1.0;
- void horizontal_bands(const GrayImage& gray, int x0, int y0, int x1, int y1,
- int min_h, int max_h, std::vector<V2Band>* bright,
- std::vector<V2Band>* dark) {
- if (bright != nullptr) { bright->clear(); }
- if (dark != nullptr) { dark->clear(); }
- if (gray.empty() || x1 <= x0 || y1 <= y0) { return; }
- x0 = std::max(0, x0);
- y0 = std::max(0, y0);
- x1 = std::min(gray.width, x1);
- y1 = std::min(gray.height, y1);
- if (x1 <= x0 || y1 <= y0) { return; }
- // 与 Python `horizontal_bands` 逐算子同口径:
- // 3×3 高斯 → 行均值 → 纵向中心差分(= 3 行 Sobel)。
- // 不能先对行均值做 5 行平滑:等效核被拉长到 7 行,箱底 3~4 px 暗带
- // 会和车体上缘亮带合并,箱底 y 被抬高 30~40 px。
- GrayImage crop(x1 - x0, y1 - y0, 0);
- for (int y = y0; y < y1; ++y) {
- for (int x = x0; x < x1; ++x) { crop.set(x - x0, y - y0, gray.at(x, y)); }
- }
- gaussian3x3_inplace(&crop);
- std::vector<double> mean(static_cast<std::size_t>(y1 - y0), 0.0);
- for (int y = 0; y < crop.height; ++y) {
- double sum = 0.0;
- for (int x = 0; x < crop.width; ++x) { sum += crop.at(x, y); }
- mean[static_cast<std::size_t>(y)] = sum / static_cast<double>(crop.width);
- }
- const int n = static_cast<int>(mean.size());
- if (n < 8) { return; }
- std::vector<double> deriv(static_cast<std::size_t>(n), 0.0);
- std::vector<double> abs_deriv;
- abs_deriv.reserve(static_cast<std::size_t>(n));
- for (int i = 1; i + 1 < n; ++i) {
- deriv[static_cast<std::size_t>(i)] =
- mean[static_cast<std::size_t>(i + 1)] - mean[static_cast<std::size_t>(i - 1)];
- abs_deriv.push_back(std::fabs(deriv[static_cast<std::size_t>(i)]));
- }
- double sum = 0.0;
- for (double v : abs_deriv) { sum += v; }
- const double avg = abs_deriv.empty() ? 0.0 : sum / abs_deriv.size();
- double var = 0.0;
- for (double v : abs_deriv) { var += (v - avg) * (v - avg); }
- const double stddev = abs_deriv.empty() ? 0.0 : std::sqrt(var / abs_deriv.size());
- const double limit = avg + 0.9 * stddev;
- std::vector<int> candidates;
- for (int i = 1; i + 1 < n; ++i) {
- const double mag = std::fabs(deriv[static_cast<std::size_t>(i)]);
- if (mag < limit) { continue; }
- if (mag >= std::fabs(deriv[static_cast<std::size_t>(i - 1)]) &&
- mag >= std::fabs(deriv[static_cast<std::size_t>(i + 1)])) {
- candidates.push_back(i);
- }
- }
- // 同一道边缘常在相邻 1~2 行出现多个极值(箱底 3 px 暗带:
- // y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内严格
- // 最大,167 会压掉 168,168 又压掉 170,最终只剩一个负峰,暗带
- // 无法配对 → no_box。改为 ±1 局部极大 + 3 px 贪心抑制。
- std::stable_sort(candidates.begin(), candidates.end(), [&](int a, int b) {
- return std::fabs(deriv[static_cast<std::size_t>(a)]) >
- std::fabs(deriv[static_cast<std::size_t>(b)]);
- });
- const int min_sep = std::max(2, min_h);
- std::vector<int> picked;
- for (int i : candidates) {
- bool keep = true;
- for (int j : picked) {
- if (std::abs(i - j) < min_sep) { keep = false; break; }
- }
- if (keep) { picked.push_back(i); }
- }
- std::sort(picked.begin(), picked.end());
- std::vector<std::pair<int, double>> events;
- events.reserve(picked.size());
- for (int i : picked) {
- events.push_back({i, deriv[static_cast<std::size_t>(i)]});
- }
- for (std::size_t j = 0; j + 1 < events.size(); ++j) {
- const int i1 = events[j].first;
- const int i2 = events[j + 1].first;
- const double v1 = events[j].second;
- const double v2 = events[j + 1].second;
- const int height = i2 - i1;
- if (height < min_h || height > max_h) { continue; }
- const double strength = std::min(std::fabs(v1), std::fabs(v2));
- if (strength <= 0.0) { continue; }
- // 约定与 Python 一致:v1>0>v2 = 亮带;v1<0<v2 = 暗带。
- const V2Band band{static_cast<double>(y0 + i1), static_cast<double>(y0 + i2), strength};
- if (v1 > 0.0 && v2 < 0.0) {
- if (bright != nullptr) { bright->push_back(band); }
- } else if (v1 < 0.0 && v2 > 0.0) {
- if (dark != nullptr) { dark->push_back(band); }
- }
- }
- auto by_strength = [](const V2Band& a, const V2Band& b) { return a.strength > b.strength; };
- if (bright != nullptr) {
- std::stable_sort(bright->begin(), bright->end(), by_strength);
- if (bright->size() > 12) { bright->resize(12); }
- }
- if (dark != nullptr) {
- std::stable_sort(dark->begin(), dark->end(), by_strength);
- if (dark->size() > 12) { dark->resize(12); }
- }
- }
- void pick_box_and_bed(const std::vector<V2Band>& bright, const std::vector<V2Band>& dark,
- int frame_h, double box_max_ratio, double bed_search_px,
- V2Band* box, V2Band* bed) {
- if (box != nullptr) { *box = V2Band(); }
- if (bed != nullptr) { *bed = V2Band(); }
- std::vector<const V2Band*> strong;
- double max_strength = 0.0;
- for (const V2Band& b : dark) {
- if (b.y1 <= box_max_ratio * frame_h && b.y0 >= 0.02 * frame_h) {
- max_strength = std::max(max_strength, b.strength);
- }
- }
- for (const V2Band& b : dark) {
- if (b.y1 <= box_max_ratio * frame_h && b.y0 >= 0.02 * frame_h &&
- b.strength >= 0.45 * max_strength) {
- strong.push_back(&b);
- }
- }
- if (strong.empty()) { return; }
- const V2Band* best_box = strong.front();
- for (const V2Band* b : strong) {
- if (b->y0 < best_box->y0) { best_box = b; }
- }
- if (box != nullptr) { *box = *best_box; }
- if (bed == nullptr) { return; }
- const V2Band* best_bed = nullptr;
- for (const V2Band& b : bright) {
- if (b.y0 >= best_box->y1 - 1.0 && b.y0 <= best_box->y1 + bed_search_px) {
- if (best_bed == nullptr || b.y0 < best_bed->y0) { best_bed = &b; }
- }
- }
- if (best_bed != nullptr) { *bed = *best_bed; }
- }
- double ground_like_ratio(const GrayImage& crop, const SobelResult& grad,
- const std::vector<Segment>& segs, int block_px, double lo,
- double hi) {
- if (crop.empty()) { return 0.0; }
- const float mag_ref = percentile(grad.mag, 0.60);
- const int b = std::max(6, block_px);
- int total = 0;
- int ground = 0;
- for (int by = 0; by < crop.height; by += b) {
- for (int bx = 0; bx < crop.width; bx += b) {
- const int ex = std::min(crop.width, bx + b);
- const int ey = std::min(crop.height, by + b);
- int hot = 0;
- int n = 0;
- for (int y = by; y < ey; ++y) {
- for (int x = bx; x < ex; ++x) {
- if (grad.mag_at(x, y) > mag_ref) { ++hot; }
- ++n;
- }
- }
- if (n <= 0) { continue; }
- const double density = static_cast<double>(hot) / static_cast<double>(n);
- bool long_line = false;
- for (const Segment& s : segs) {
- if (s.length < 0.6 * b) { continue; }
- if (s.cx() < bx || s.cx() > ex || s.cy() < by || s.cy() > ey) { continue; }
- long_line = true;
- break;
- }
- ++total;
- if (!long_line && density >= lo && density <= hi) { ++ground; }
- }
- }
- return total > 0 ? static_cast<double>(ground) / static_cast<double>(total) : 0.0;
- }
- std::vector<double> cluster_positions(const std::vector<double>& values, double gap) {
- std::vector<double> ordered = values;
- std::sort(ordered.begin(), ordered.end());
- std::vector<double> centers;
- if (ordered.empty()) { return centers; }
- std::vector<double> cluster{ordered.front()};
- for (std::size_t i = 1; i < ordered.size(); ++i) {
- if (ordered[i] - cluster.back() <= gap) {
- cluster.push_back(ordered[i]);
- } else {
- centers.push_back(cluster[cluster.size() / 2]);
- cluster.assign(1, ordered[i]);
- }
- }
- if (!cluster.empty()) { centers.push_back(cluster[cluster.size() / 2]); }
- return centers;
- }
- double median(std::vector<double> values) {
- if (values.empty()) { return 0.0; }
- std::sort(values.begin(), values.end());
- const std::size_t n = values.size();
- return n % 2 == 1 ? values[n / 2] : 0.5 * (values[n / 2 - 1] + values[n / 2]);
- }
- double pstdev(const std::vector<double>& values, double mean) {
- if (values.size() < 2) { return 0.0; }
- double sum = 0.0;
- for (double v : values) { sum += (v - mean) * (v - mean); }
- return std::sqrt(sum / static_cast<double>(values.size()));
- }
- /// 车体 ROI(空车/无箱)上的门板/立柱证据(P0-Q4 兜底用)。
- GrayImage crop_gray(const GrayImage& src, int x0, int y0, int x1, int y1);
- struct BodyEvidence {
- int posts = 0;
- double span_ratio = 0.0;
- double opacity = 0.0;
- int diagonal = 0;
- double height = 0.0;
- };
- BodyEvidence measure_body(const GrayImage& work, int x0, int y0, int x1, int y1,
- const EdgeV2Params& p, double scale) {
- BodyEvidence out;
- GrayImage crop = crop_gray(work, x0, y0, x1, y1);
- if (crop.empty() || crop.height < 8) { return out; }
- out.height = static_cast<double>(crop.height);
- const SobelResult grad = sobel(crop);
- const std::vector<uint8_t> edges =
- canny_lite(crop, grad, p.canny_lo_pct, p.canny_hi_pct);
- LineParams lp;
- lp.min_points = 12;
- lp.grad_pct = 0.90;
- const std::vector<Segment> segs = extract_segments(crop, grad, edges, lp);
- const std::vector<Segment> runs = extract_vertical_runs(
- crop, grad, edges, lp, std::max(8.0, 0.60 * crop.height), 8, nullptr);
- std::vector<Segment> all_segs = segs;
- all_segs.insert(all_segs.end(), runs.begin(), runs.end());
- const double post_min_len = p.min_post_len_ratio * crop.height;
- std::vector<double> post_x;
- int diagonal = 0;
- for (const Segment& s : all_segs) {
- if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
- post_x.push_back(s.cx());
- } else if (std::fabs(s.angle_deg) >= 20.0 && std::fabs(s.angle_deg) <= 70.0) {
- ++diagonal;
- }
- }
- const std::vector<double> posts =
- cluster_positions(post_x, std::max(3.0, 9.0 * scale));
- out.posts = static_cast<int>(posts.size());
- out.diagonal = diagonal;
- if (posts.size() >= 2) {
- out.span_ratio = (posts.back() - posts.front()) /
- std::max(1.0, static_cast<double>(crop.width));
- }
- const double ground = ground_like_ratio(crop, grad, all_segs, p.ground_block_px,
- p.ground_density_lo, p.ground_density_hi);
- out.opacity = std::max(0.0, std::min(1.0, 1.0 - ground));
- return out;
- }
- std::string fmt(const char* pattern, double value) {
- char buf[128];
- std::snprintf(buf, sizeof(buf), pattern, value);
- return std::string(buf);
- }
- } // namespace
- double find_texture_top_y(const GrayImage& gray, const int window[4],
- const EdgeV2Params& p) {
- if (!p.texture_top_enable || gray.empty()) { return -1.0; }
- const SobelResult grad = sobel(gray);
- const int x0 = std::max(0, std::min(window[0], gray.width));
- const int x1 = std::min(gray.width, std::max(x0, window[2]));
- const int block = std::max(4, p.texture_block_px);
- const int nb = (x1 - x0) / block;
- if (nb < 2) { return -1.0; }
- std::vector<double> cov(static_cast<std::size_t>(gray.height), 0.0);
- for (int y = 0; y < gray.height; ++y) {
- int hit = 0;
- for (int i = 0; i < nb; ++i) {
- const int bx = x0 + i * block;
- int cnt = 0;
- for (int x = bx; x < bx + block; ++x) {
- const std::size_t idx =
- static_cast<std::size_t>(y) * static_cast<std::size_t>(gray.width) +
- static_cast<std::size_t>(x);
- if (std::fabs(grad.gx[idx]) >= p.texture_grad_th) { ++cnt; }
- }
- if (static_cast<double>(cnt) / static_cast<double>(block) >=
- p.texture_block_hit_ratio) {
- ++hit;
- }
- }
- cov[static_cast<std::size_t>(y)] =
- static_cast<double>(hit) / static_cast<double>(nb);
- }
- const int smooth = std::max(1, p.texture_smooth_rows);
- std::vector<double> sm(static_cast<std::size_t>(gray.height), 0.0);
- for (int y = 0; y < gray.height; ++y) {
- const int a = std::max(0, y - smooth / 2);
- const int b = std::min(gray.height - 1, y + smooth / 2);
- double sum = 0.0;
- int n = 0;
- for (int k = a; k <= b; ++k) {
- sum += cov[static_cast<std::size_t>(k)];
- ++n;
- }
- sm[static_cast<std::size_t>(y)] = n > 0 ? sum / static_cast<double>(n) : 0.0;
- }
- const int run = std::max(1, p.texture_run_rows);
- for (int y = std::max(0, window[1]); y + run <= gray.height; ++y) {
- bool ok = true;
- for (int k = 0; k < run; ++k) {
- if (sm[static_cast<std::size_t>(y + k)] < p.texture_coverage_min) {
- ok = false;
- break;
- }
- }
- if (ok) { return static_cast<double>(y); }
- }
- return -1.0;
- }
- bool EvidenceV2Result::publishable(bool require_commit) const {
- if (state != 0 && state != 1 && state != 2) { return false; }
- return !require_commit || committed;
- }
- Observation EvidenceV2Result::to_observation(double ts, long frame_id,
- bool require_commit) const {
- Observation obs;
- obs.ts = ts;
- obs.frame_id = frame_id;
- const bool ok = publishable(require_commit);
- obs.state = ok ? state : static_cast<int>(SceneState::UNKNOWN);
- obs.confidence = ok ? confidence : 0.0;
- obs.reason = std::string("v2:") + (ok ? "ok" : "abstain") + " view=" + view +
- " posts=" + std::to_string(door_posts) + " opacity=" +
- fmt("%.2f", wall_opacity) + " gap=" +
- (gap_px.has_value() ? fmt("%.0f", *gap_px) + "px" : "n/a") +
- " commit=" + commit_reason;
- if (!ok && !abstain_reason.empty()) { obs.reason += " reason=" + abstain_reason; }
- return obs;
- }
- std::string EvidenceV2Result::evidence_summary() const {
- std::string out = "state=" + std::to_string(state) + " view=" + view +
- " top=" + (texture_top_y > 0.0 ? fmt("%.1f", texture_top_y) : "n/a") +
- " posts=" + std::to_string(door_posts) + " opacity=" +
- fmt("%.2f", wall_opacity) + " ground=" + fmt("%.2f", ground_ratio);
- out += " deck=" + std::string(deck_edge ? "1" : "0");
- out += " under_deck=" + std::string(under_deck ? "1" : "0");
- out += " body=(" + std::to_string(body_posts) + "," +
- fmt("%.2f", body_span) + "," + fmt("%.2f", body_opacity) + "," +
- std::to_string(body_diagonal) + ")";
- out += " gap=" + (gap_px.has_value() ? fmt("%.1f", *gap_px) + "px" : "n/a");
- out += " gap_m=" + (gap_m.has_value() ? fmt("%.3f", *gap_m) : "n/a");
- out += " box=" + (box_bottom_y.has_value() ? fmt("%.1f", *box_bottom_y) : "n/a") +
- " bed=" + (bed_top_y.has_value() ? fmt("%.1f", *bed_top_y) : "n/a");
- out += " phase=" + phase + " commit=" + (committed ? "1" : "0") +
- "(" + commit_reason + ")";
- out += " roi=[" + std::to_string(below_roi[0]) + "," + std::to_string(below_roi[1]) +
- "," + std::to_string(below_roi[2]) + "," + std::to_string(below_roi[3]) + "]";
- out += " edges=" + std::to_string(edge_pixels) + " segs=" + std::to_string(line_segments) +
- " vrun=" + std::to_string(vertical_runs);
- out += " gpost=" + std::to_string(generic_posts) + " rpost=" + std::to_string(run_posts);
- out += " spcv=" + (post_spacing_cv.has_value() ? fmt("%.2f", *post_spacing_cv) : "n/a");
- out += " postx=[";
- for (std::size_t i = 0; i < post_positions.size(); ++i) {
- if (i != 0) { out += ","; }
- out += fmt("%.0f", post_positions[i]);
- }
- out += "]";
- if (hoist_high) {
- out += " hoist=" + std::string(hoist_injected ? "injected" : "image") +
- "(lines=" + std::to_string(hoist_lines) + ",cables=" + std::to_string(hoist_cables) +
- ",probe=" + std::to_string(hoist_limit_px) + "px)";
- }
- if (spreader_contact) {
- out += " spreader=1(run=" + std::to_string(spreader_dark_run_px) + "px)";
- }
- if (!abstain_reason.empty()) { out += " abstain=" + abstain_reason; }
- return out;
- }
- V2CommitTracker::V2CommitTracker(const V2CommitParams& params) : p_(params) {
- if (p_.stable_frames < 1) { p_.stable_frames = 1; }
- if (p_.structure_frames < 1) { p_.structure_frames = 1; }
- p_.min_structure_hits = std::max(0.0, std::min(1.0, p_.min_structure_hits));
- last_ = V2CommitState();
- }
- void V2CommitTracker::reset() {
- samples_.clear();
- last_ts_ = 0.0;
- last_ = V2CommitState();
- last_.reason = "reset";
- }
- int V2CommitTracker::same_state_run(int state) const {
- int count = 0;
- for (auto it = samples_.rbegin(); it != samples_.rend(); ++it) {
- if (it->state != state) { break; }
- ++count;
- }
- return count;
- }
- bool V2CommitTracker::gap_ok(const Sample& s, bool arrival) const {
- if (s.state == 0 || arrival) { return true; }
- if (!s.gap_px.has_value() || *s.gap_px > p_.gap_px_hard_max) { return false; }
- // 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
- if (*s.gap_px <= kContactGapPx) { return true; }
- return s.gap_m.has_value() && *s.gap_m <= p_.gap_m_max;
- }
- std::optional<double> V2CommitTracker::gap_slope(int n) const {
- if (n <= 0 || samples_.empty()) { return std::nullopt; }
- const int start = std::max(0, static_cast<int>(samples_.size()) - n);
- std::optional<double> t0, g0, t1, g1;
- for (int i = start; i < static_cast<int>(samples_.size()); ++i) {
- const Sample& s = samples_[static_cast<std::size_t>(i)];
- if (!s.gap_m.has_value()) { continue; }
- if (!t0.has_value()) { t0 = s.ts; g0 = s.gap_m; }
- t1 = s.ts;
- g1 = s.gap_m;
- }
- if (!t0.has_value() || !t1.has_value() || (*t1 - *t0) <= 1e-6) { return std::nullopt; }
- return (*g1 - *g0) / (*t1 - *t0);
- }
- V2CommitState V2CommitTracker::update(double ts, int state, std::optional<double> gap_m,
- std::optional<double> gap_px, double structure_hits,
- bool motion_ok, bool view_known, bool plc_arrived,
- bool plc_spreader_released, bool hoist_high) {
- double now = ts;
- if (now < last_ts_) { now = last_ts_; }
- last_ts_ = now;
- const bool structure_ok = structure_hits >= p_.min_structure_hits;
- const bool arrival = p_.use_plc_arrival && (plc_arrived || plc_spreader_released);
- auto make = [&](bool committed, const std::string& phase, const std::string& reason,
- int stable, int structure) {
- V2CommitState s;
- s.committed = committed;
- s.phase = phase;
- s.reason = reason;
- s.gap_m = gap_m;
- s.gap_px = gap_px;
- s.stable_frames = stable;
- s.structure_frames = structure;
- s.plc_arrival = arrival;
- s.hoist_high = hoist_high;
- last_ = s;
- return s;
- };
- // 吊具/钢缆/臂架高悬:箱体未落位,优先于所有几何门,且不写样本窗口。
- if (hoist_high) {
- return make(false, "T3", "hoist_high", 0, 0);
- }
- if (state != 0 && state != 1 && state != 2) {
- return make(false, motion_ok ? "T1" : "T3", "state_unknown", 0, 0);
- }
- if (state == 1 && !p_.allow_state1) {
- return make(false, "T1", "state1_disabled", 0, 0);
- }
- if (state == 2 && !p_.allow_state2) {
- samples_.push_back(Sample{now, state, gap_m, gap_px, structure_ok, motion_ok});
- while (samples_.size() > 256) { samples_.pop_front(); }
- return make(false, "T1", "state2_disabled", 0, 0);
- }
- samples_.push_back(Sample{now, state, gap_m, gap_px, structure_ok, motion_ok});
- while (samples_.size() > 256) { samples_.pop_front(); }
- if (!motion_ok && p_.require_motion_ok) {
- return make(false, "T3", "motion", 0, 0);
- }
- if (!view_known && p_.require_view_known) {
- return make(false, "T1", "view_unknown", 0, 0);
- }
- bool gap_gate = true;
- if (state == 1 || state == 2) {
- const bool contact = gap_px.has_value() && *gap_px <= kContactGapPx;
- gap_gate = arrival ||
- (gap_px.has_value() && *gap_px <= p_.gap_px_hard_max &&
- (contact || (gap_m.has_value() && *gap_m <= p_.gap_m_max)));
- }
- const int window_n = std::max(p_.stable_frames, p_.structure_frames);
- const int start = std::max(0, static_cast<int>(samples_.size()) - window_n);
- int structure_n = 0;
- int gap_n = 0;
- for (int i = start; i < static_cast<int>(samples_.size()); ++i) {
- const Sample& s = samples_[static_cast<std::size_t>(i)];
- if (s.structure_ok) { ++structure_n; }
- if (gap_ok(s, arrival)) { ++gap_n; }
- }
- const int stable_n = same_state_run(state);
- const std::optional<double> slope = gap_slope(window_n);
- const bool stable_enough = stable_n >= p_.stable_frames;
- const bool structure_enough = structure_n >= p_.structure_frames;
- const bool gap_enough = gap_n >= p_.stable_frames;
- const bool not_rising = !slope.has_value() || *slope <= p_.max_gap_rise_m;
- const bool committed = gap_gate && stable_enough && structure_enough && gap_enough && not_rising;
- std::string reason;
- if (!gap_gate) { reason += "gap"; }
- if (!stable_enough) {
- if (!reason.empty()) { reason += ","; }
- reason += "stable=" + std::to_string(stable_n) + "/" + std::to_string(p_.stable_frames);
- }
- if (!structure_enough) {
- if (!reason.empty()) { reason += ","; }
- reason += "structure=" + std::to_string(structure_n) + "/" +
- std::to_string(p_.structure_frames);
- }
- if (!gap_enough) {
- if (!reason.empty()) { reason += ","; }
- reason += "gap_window=" + std::to_string(gap_n) + "/" +
- std::to_string(p_.stable_frames);
- }
- if (!not_rising) {
- if (!reason.empty()) { reason += ","; }
- reason += "gap_rising";
- }
- if (committed) {
- reason = arrival ? "commit:plc_arrival" : "commit";
- } else if (!reason.empty()) {
- reason = "wait:" + reason;
- } else {
- reason = "wait";
- }
- V2CommitState out = make(committed, gap_gate ? "T2" : "T1", reason, stable_n, structure_n);
- out.gap_slope_m_per_s = slope;
- last_ = out;
- return out;
- }
- EdgeV2::EdgeV2(const EdgeV2Params& params, const V2CommitParams& commit)
- : p_(params), tracker_(commit) {}
- void EdgeV2::reset() {
- tracker_.reset();
- prev_thumb_ = GrayImage();
- prev_mag_ = 0.0;
- last_ = EvidenceV2Result();
- last_.view = p_.view;
- }
- namespace {
- GrayImage crop_gray(const GrayImage& src, int x0, int y0, int x1, int y1) {
- x0 = std::max(0, x0);
- y0 = std::max(0, y0);
- x1 = std::min(src.width, x1);
- y1 = std::min(src.height, y1);
- if (x1 <= x0 || y1 <= y0) { return GrayImage(); }
- GrayImage out(x1 - x0, y1 - y0, 0);
- for (int y = y0; y < y1; ++y) {
- for (int x = x0; x < x1; ++x) { out.set(x - x0, y - y0, src.at(x, y)); }
- }
- return out;
- }
- } // namespace
- bool EdgeV2::motion_ok(const GrayImage& work, double* diff, double* ratio) {
- if (diff != nullptr) { *diff = 0.0; }
- if (ratio != nullptr) { *ratio = 1.0; }
- if (work.empty()) { return true; }
- GrayImage thumb = box_downscale(work, 160, 90);
- if (thumb.empty()) { return true; }
- const double mag = sobel(thumb).mean_mag();
- if (prev_thumb_.empty()) {
- prev_thumb_ = thumb;
- prev_mag_ = mag;
- return true;
- }
- double sum = 0.0;
- int n = 0;
- for (int y = 0; y < thumb.height; ++y) {
- for (int x = 0; x < thumb.width; ++x) {
- sum += std::fabs(static_cast<double>(thumb.at(x, y)) -
- static_cast<double>(prev_thumb_.at(x, y)));
- ++n;
- }
- }
- const double d = n > 0 ? sum / n : 0.0;
- const double r = prev_mag_ > 1e-6 ? mag / prev_mag_ : 1.0;
- if (diff != nullptr) { *diff = d; }
- if (ratio != nullptr) { *ratio = r; }
- prev_thumb_ = thumb;
- prev_mag_ = prev_mag_ > 0.0 ? 0.8 * prev_mag_ + 0.2 * mag : mag;
- return d <= p_.motion_diff_max && r >= p_.motion_grad_ratio_min;
- }
- std::optional<double> EdgeV2::scale_from_vertical(const GrayImage& work, const V2Band& box,
- const int window[4], double scale,
- double* run_px) {
- if (run_px != nullptr) { *run_px = 0.0; }
- if (p_.px_per_m > 0.0) { return p_.px_per_m; }
- const int x0 = std::max(0, window[0]);
- const int y0 = std::max(0, window[1]);
- const int x1 = std::min(work.width, window[2]);
- const int y1 = std::min(work.height, static_cast<int>(std::floor(box.y0)));
- GrayImage upper = crop_gray(work, x0, y0, x1, y1);
- if (upper.empty()) { return std::nullopt; }
- const SobelResult grad = sobel(upper);
- const std::vector<uint8_t> edges =
- canny_lite(upper, grad, p_.canny_lo_pct, p_.canny_hi_pct);
- LineParams lp;
- lp.min_points = 12;
- lp.grad_pct = 0.90;
- const std::vector<Segment> segs = extract_segments(upper, grad, edges, lp);
- double best = 0.0;
- for (const Segment& s : segs) {
- if (std::fabs(s.angle_deg) < 65.0) { continue; }
- const double dy = std::fabs(s.y2 - s.y1);
- if (dy > best) { best = dy; }
- }
- if (best < p_.min_scale_px * scale) { return std::nullopt; }
- if (run_px != nullptr) { *run_px = best / scale; }
- return (best / scale) / p_.box_height_m;
- }
- EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing_cv,
- double opacity, double ground, bool deck, int wheels,
- std::optional<double> gap_px, bool motion_ok,
- const std::string& view,
- double below_roi_h_px,
- bool under_deck, double post_spacing_px,
- int diagonal_braces, double post_span_ratio) const {
- ClassifyResult r;
- if (view == "unknown") {
- r.reason = "view_unknown";
- return r;
- }
- if (!motion_ok) {
- r.reason = "motion";
- return r;
- }
- // C++ 线段通道对低对比地面纹理比 Python HoughLinesP 更敏感:B(平车)中
- // 8~10 条互不等距的伪竖线会落进 [min_door_posts, max_door_posts] 并被误判 1。
- // 真实门板阵列的间距是规则的;≥8 根且 CV>1.5 视为杂波,不构成“门板阵列”。
- // (<8 根时样本太少,CV 不可靠,不做该判据。)
- const bool post_array_regular =
- posts < 8 || !spacing_cv.has_value() || *spacing_cv <= 1.5;
- // 反向补偿:自定义拟合会把同一根门板的两侧描边合并(Python Hough 常算 2 根),
- // A 类稳定帧实测 Python 5~8 根、C++ 4 根。posts = min_door_posts-1 时若
- // 侧墙不透明且间距规则,仍按门板阵列处理(不放松到更低,避免 B 的杂波)。
- const int relaxed_min_posts = p_.min_door_posts > 1 ? p_.min_door_posts - 1 : 1;
- const bool relaxed_post_array =
- posts >= relaxed_min_posts && opacity >= 0.65 &&
- (!spacing_cv.has_value() || *spacing_cv <= 1.0);
- const bool posts_ok = posts >= p_.min_door_posts || relaxed_post_array;
- // P0-Q3:门板立柱间距下限(原图像素)。容器侧壁瓦楞 10~20 px,
- // C70 门板 63~185 px → 低于下限不构成门板阵列(防"上层箱坐在下层箱上"→ 1)。
- // post_spacing_px <= 0 表示不可用,不用它拒绝。
- const bool post_spacing_ok =
- post_spacing_px <= 0.0 || post_spacing_px >= p_.min_post_spacing_px;
- // P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。
- // 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权;
- // 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。
- const bool contact_bed = !gap_px.has_value() || *gap_px <= 1.0;
- const bool doors_ok =
- !contact_bed || diagonal_braces >= p_.min_diagonal_braces;
- // 冲突时:A 的真实门板阵列可能只剩 min_posts-1 根(见上),同时又误检到
- // 车面边梁;此时按“门板阵列”优先(Python 对应帧 deck=False,不会冲突)。
- const bool prefer_bed_on_conflict =
- posts < p_.min_door_posts && relaxed_post_array;
- // P0-Q3:门板阵列必须横跨足够宽(>= min_post_span_ratio × 工作宽度)。
- // 平车车轮/制动梁/端部结构只在窄区给 5~7 条伪立柱(B f1771~f1773:
- // postx=666..859,跨度 ~20%),真实 C70 门板阵列横跨车体(A ~66%)。
- const bool post_span_ok = post_span_ratio >= p_.min_post_span_ratio;
- const bool bed_evidence =
- posts_ok && posts <= p_.max_door_posts &&
- opacity >= p_.min_wall_opacity && post_array_regular &&
- post_spacing_ok && doors_ok && post_span_ok &&
- (!gap_px.has_value() || *gap_px <= p_.max_bed_gap_px) &&
- (!spacing_cv.has_value() || *spacing_cv <= p_.max_post_spacing_cv);
- // 敞车(1)需要真的看得见"门板立柱阵列":箱底以下的动态 ROI 太矮时,
- // 立柱只有 20~27 px,与地面/钢轨纹理不可区分(B 片段 f30/f31/f36~f38 实测
- // 提出 5~16 条伪立柱并被投票成"已发布 1",真值 2)。不足门限 → 弃权,
- // 不判 1;平车(2)分支不受此限(它靠车面边梁,不需要门板)。
- const bool bed_roi_ok = below_roi_h_px >= static_cast<double>(p_.min_bed_roi_px);
- const bool bed_strong = bed_evidence && bed_roi_ok;
- const bool flat_strong =
- posts <= p_.flat_max_door_posts && deck && under_deck &&
- (!gap_px.has_value() || *gap_px <= p_.max_flat_gap_px);
- if (bed_strong && flat_strong && !prefer_bed_on_conflict) {
- r.reason = "conflict_1_2";
- return r;
- }
- if (bed_evidence && !bed_roi_ok && !flat_strong) {
- r.reason = "bed_roi_small";
- return r;
- }
- if (bed_strong) {
- r.state = static_cast<int>(SceneState::BED);
- r.confidence = std::min(1.0, 0.55 + 0.25 * std::min(1.0, posts / 8.0) +
- 0.15 * opacity);
- r.structure_hits = std::min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity);
- r.reason = "wall_posts";
- return r;
- }
- if (flat_strong) {
- r.state = static_cast<int>(SceneState::FLATBED);
- r.confidence = std::min(1.0, 0.60 + 0.20 * ground +
- 0.10 * std::max(0.0, 1.0 - posts / 4.0));
- r.structure_hits = std::min(1.0, 0.55 + 0.15 * ground +
- 0.10 * std::max(0.0, 1.0 - posts / 4.0));
- r.reason = "deck_edge";
- return r;
- }
- (void)wheels;
- if (posts <= 1 && ground >= p_.min_zero_ground_ratio && !deck) {
- r.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
- r.confidence = std::min(1.0, 0.55 + 0.30 * ground);
- r.structure_hits = std::min(1.0, 0.50 + 0.40 * ground);
- r.reason = "ground_only";
- return r;
- }
- r.reason = "weak_evidence";
- return r;
- }
- EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arrived,
- bool plc_spreader_released, bool hoist_high) {
- EvidenceV2Result out;
- out.view = p_.view;
- if (gray.empty()) {
- out.abstain_reason = "no_image";
- out.commit_reason = "no_image";
- last_ = out;
- return out;
- }
- double scale = 1.0;
- GrayImage work = resize_long_side(gray, p_.work_width, &scale);
- if (work.empty()) {
- out.abstain_reason = "no_image";
- out.commit_reason = "no_image";
- last_ = out;
- return out;
- }
- // 与 Python 同口径:只做 INTER_AREA 缩放,不再额外中值/高斯预滤波。
- // 额外滤波会把箱底 3~4 px 的暗带与车体上缘亮带糊在一起,箱底下沿被抬到
- // 408 而真值在 445,动态 ROI 因此整段错位(A1 实测 posts 10 → 3)。
- double motion_diff = 0.0;
- double motion_ratio = 1.0;
- const bool still = motion_ok(work, &motion_diff, &motion_ratio);
- const int window[4] = {
- static_cast<int>(p_.window[0] * work.width),
- static_cast<int>(p_.window[1] * work.height),
- static_cast<int>(p_.window[2] * work.width),
- static_cast<int>(p_.window[3] * work.height),
- };
- std::vector<V2Band> bright;
- std::vector<V2Band> dark;
- // P0-Q4:先找“竖向纹理车体顶”,把车体顶以上的天空电线/水印从候选带里剔除。
- // 不移动窗口:近距画面车体顶≈窗口顶,门槛自然不触发;远距/带天空画面才生效。
- const double texture_top = find_texture_top_y(work, window, p_);
- out.texture_top_y =
- texture_top > 0.0 ? texture_top / std::max(scale, 1e-6) : 0.0;
- horizontal_bands(work, window[0], window[1], window[2], window[3],
- std::max(1, static_cast<int>(p_.band_min_h * scale)),
- std::max(6, static_cast<int>(p_.band_max_h_ratio * work.height)),
- &bright, &dark);
- if (texture_top > 0.0 &&
- texture_top > window[1] + 0.05 * work.height) {
- const double margin = p_.texture_top_margin_ratio * work.height;
- const std::vector<V2Band> bright_all = bright;
- const std::vector<V2Band> dark_all = dark;
- const auto filter_above = [&](std::vector<V2Band>& bands) {
- std::vector<V2Band> kept;
- for (const V2Band& b : bands) {
- if (b.y1 >= texture_top - margin) { kept.push_back(b); }
- }
- if (!kept.empty()) { bands.swap(kept); }
- };
- filter_above(bright);
- filter_above(dark);
- if (bright.empty()) { bright = bright_all; }
- if (dark.empty()) { dark = dark_all; }
- }
- const double box_hint = std::max(80.0, 0.40 * work.height);
- V2Band box;
- V2Band bed;
- pick_box_and_bed(bright, dark, work.height, p_.box_bottom_max_ratio,
- std::max(24.0, p_.bed_search_ratio * box_hint), &box, &bed);
- if (box.height() <= 0.0 && !dark.empty()) {
- double best = 0.0;
- for (const V2Band& b : dark) {
- if (b.y0 >= 0.03 * work.height && b.y1 <= 0.90 * work.height &&
- b.strength > best) {
- box = b;
- best = b.strength;
- }
- }
- }
- if (box.height() <= 0.0) {
- out.motion_ok = still;
- out.abstain_reason = "no_box";
- out.commit_reason = "no_box";
- out.phase = still ? "T1" : "T3";
- last_ = out;
- return out;
- }
- if (bed.height() <= 0.0) {
- double best = std::numeric_limits<double>::max();
- for (const V2Band& b : bright) {
- if (b.y0 >= box.y1 - 1.0 && b.y0 < best) {
- bed = b;
- best = b.y0;
- }
- }
- }
- // P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/
- // 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里
- // `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。
- const double est_h = std::max(60.0, box.y0 - 0.05 * work.height);
- bool thick_contact = false;
- if (bed.height() > 0.0 && bed.y0 <= box.y1 + 1.0 &&
- bed.height() > p_.contact_max_h_ratio * est_h) {
- thick_contact = true;
- bed = V2Band{};
- }
- double vertical_run = 0.0;
- const std::optional<double> px_per_m =
- scale_from_vertical(work, box, window, scale, &vertical_run);
- std::optional<double> box_h;
- if (px_per_m.has_value()) {
- box_h = *px_per_m * p_.box_height_m;
- } else if (vertical_run > 0.0) {
- box_h = vertical_run;
- }
- std::optional<double> box_top;
- if (box_h.has_value()) {
- box_top = std::max(0.0, box.y1 / std::max(scale, 1e-6) - *box_h);
- }
- // ---------------- P0-0 图像侧安全门(吊具高悬 / 吊具仍夹箱) ----------------
- // 与 Python 同序:调用方/PLC 注入了 hoist_high 就直接用;否则做图像检测。
- // 命中即整帧弃权,并且**不累计** commit 窗口(V2CommitTracker 内部早返回),
- // 所以它压得住"几何证据连续 5 帧都成立、但箱还在半空"这一类最危险的误判。
- bool hoist_flag = hoist_high;
- HoistCues hoist_cues;
- SpreaderCues spreader_cues;
- if (!hoist_flag && (p_.reject_hoist_high || p_.reject_spreader_contact)) {
- // 没有可靠箱高时按"箱底暗带往上 0.35 画幅"保守估计(与 Python 同口径)。
- const double inv_scale = 1.0 / std::max(scale, 1e-6);
- const double probe_top = box_top.has_value()
- ? *box_top
- : std::max(0.0, box.y0 * inv_scale - 0.35 * gray.height);
- if (p_.reject_hoist_high) {
- hoist_cues = detect_hoist_high(gray, probe_top, p_.hoist);
- }
- if (p_.reject_spreader_contact) {
- spreader_cues = detect_spreader_contact(
- gray, static_cast<int>(window[0] * inv_scale),
- static_cast<int>(box.y0 * inv_scale), static_cast<int>(window[2] * inv_scale),
- static_cast<int>(box.y1 * inv_scale), p_.spreader);
- }
- hoist_flag = hoist_cues.hoist_high || spreader_cues.contact;
- }
- // (est_h 在"贴合亮带厚度门"处已算好,此处复用。)
- // 箱底贴近画面底边时,若仍跳过 7% 箱高,动态 ROI 会整段落到画面外,
- // 平车车面边梁/地板线看不到(近距 192 px 帧:箱底 y=170,底部只剩
- // 21 px)。此时只留 2 px 保护带,与 Python 同口径。
- double below_start = std::max(2.0, p_.below_start_ratio * est_h);
- const double min_below_h = p_.below_min_height_px * std::max(scale, 1e-6);
- if (static_cast<double>(work.height - 1) - box.y1 <= below_start + min_below_h) {
- below_start = 2.0;
- }
- const int y0w = std::min(
- work.height - 2,
- static_cast<int>(std::ceil(box.y1 + below_start)));
- const double below_h = std::max(
- min_below_h,
- std::min(p_.below_height_ratio * est_h, 0.30 * work.height));
- const int y1w = std::min(
- work.height - 1,
- std::max(static_cast<int>(y0w + below_h), static_cast<int>(box.y1 + 0.10 * est_h)));
- const int x0w = std::max(0, static_cast<int>(0.05 * work.width));
- const int x1w = std::min(work.width - 1, static_cast<int>(0.95 * work.width));
- GrayImage crop = crop_gray(work, x0w, y0w, x1w, std::max(y0w + 8, y1w));
- if (crop.empty()) {
- out.motion_ok = still;
- out.abstain_reason = "roi_empty";
- out.commit_reason = "roi_empty";
- last_ = out;
- return out;
- }
- // 与 Python `detect_structure_v2` 同口径:ROI 内先 CLAHE(clip=2.0, 8×8) 再提边。
- // 真机低对比 / 逆光片段不做光照归一,门板竖棱会整段掉到 Canny 阈值以下
- // (A1 实测:不加时 vrun 只剩 3 根,加后回到 8–10 根)。
- clahe_lite_inplace(&crop, 8, 2.0);
- const SobelResult grad = sobel(crop);
- const std::vector<uint8_t> edges =
- canny_lite(crop, grad, p_.canny_lo_pct, p_.canny_hi_pct);
- LineParams lp;
- lp.min_points = 12;
- lp.grad_pct = 0.90;
- const std::vector<Segment> segs = extract_segments(crop, grad, edges, lp);
- long long hot = 0;
- for (uint8_t e : edges) { if (e != 0) { ++hot; } }
- const double edge_density = edges.empty()
- ? 0.0
- : static_cast<double>(hot) / static_cast<double>(edges.size());
- const double roi_h = static_cast<double>(crop.height);
- // 专用竖直游程通道:箱体+车体+地面连成一大块时,通用通道会把竖棱切碎。
- // 断口 8 px:横梁/斜撑横穿门板时会造成 3~5 px 的真实断口,2 px 会把长竖棱切没。
- // 长度门用 0.60×ROI:门板立柱是贯穿整个箱底以下 ROI 的长竖棱;8 px 断口会把
- // 地面纹理的短竖纹也接成 0.3~0.5×ROI 的伪立柱(B 实拍实测 posts 5~6 → 误判 1)。
- const std::vector<Segment> vertical_runs = extract_vertical_runs(
- crop, grad, edges, lp, std::max(8.0, 0.60 * roi_h), 8, &segs);
- std::vector<Segment> all_segs = segs;
- all_segs.insert(all_segs.end(), vertical_runs.begin(), vertical_runs.end());
- out.line_segments = static_cast<int>(segs.size());
- out.vertical_runs = static_cast<int>(vertical_runs.size());
- out.edge_pixels = static_cast<int>(hot);
- std::vector<double> post_x;
- int diagonal = 0;
- bool deck_edge = false;
- // Python HoughLinesP 把车面边梁给成一条长线;C++ 的自定义拟合会把同一条边梁
- // 按强横梁断口拆成 2~3 段(B 落位帧实测:Python deck=True,C++ 0)。
- // 这里按 0.25×width 计长(≈ 原 0.55×width 门限的 45%),与拆段后的最长段匹配。
- const double deck_min_len = std::max(20.0, p_.deck_min_len_ratio * 0.25 * work.width);
- const double post_min_len = p_.min_post_len_ratio * roi_h;
- const auto collect_post_x = [&](const std::vector<Segment>& source) {
- std::vector<double> xs;
- for (const Segment& s : source) {
- if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
- xs.push_back(s.cx());
- }
- }
- return xs;
- };
- for (const Segment& s : all_segs) {
- if (std::fabs(s.angle_deg) >= 65.0 && s.length >= post_min_len) {
- post_x.push_back(s.cx());
- } else if (std::fabs(s.angle_deg) <= 25.0) {
- const double y_abs = y0w + s.cy();
- // `-2` 会把箱体自身的下侧梁当成车面边梁(A 的稳定帧因此 deck=1,
- // 与 Python 的 deck=0 相反);C++ 拟合出的箱底线正好落在 box.y1,
- // 所以这里要求边梁在箱底**下方** ≥2 px。B 落位帧的间距为 4~30 px,不受影响。
- if (s.length >= deck_min_len &&
- y_abs >= box.y1 + 2.0 && y_abs <= box.y1 + 0.35 * roi_h) {
- deck_edge = true;
- }
- } else if (std::fabs(s.angle_deg) >= 20.0 && std::fabs(s.angle_deg) <= 70.0) {
- ++diagonal;
- }
- }
- const std::vector<double> posts =
- cluster_positions(post_x, std::max(3.0, 9.0 * scale));
- out.generic_posts = static_cast<int>(
- cluster_positions(collect_post_x(segs), std::max(3.0, 9.0 * scale)).size());
- out.run_posts = static_cast<int>(
- cluster_positions(collect_post_x(vertical_runs), std::max(3.0, 9.0 * scale)).size());
- out.post_positions = posts;
- std::optional<double> spacing_median;
- std::optional<double> spacing_cv;
- if (posts.size() >= 2) {
- std::vector<double> spacings;
- for (std::size_t i = 1; i < posts.size(); ++i) {
- spacings.push_back(posts[i] - posts[i - 1]);
- }
- const double med = median(spacings);
- spacing_median = med;
- if (spacings.size() >= 2 && med > 1e-6) {
- spacing_cv = pstdev(spacings, med) / med;
- }
- }
- const double ground = ground_like_ratio(
- crop, grad, all_segs, p_.ground_block_px, p_.ground_density_lo, p_.ground_density_hi);
- const double opacity = std::max(0.0, std::min(1.0, 1.0 - ground));
- // 侧视平车(X70A)的箱底与车面直接贴合:车面边梁就在箱底下沿,
- // 动态 ROI 从箱底下方 7% 箱高开始,边梁会落在 ROI 之外,Hough 水平线
- // 通道看不到它(实拍图 deck=False、gap 被错取成 62.9 px → weak_evidence)。
- // 这里补一条“贴合车面”证据:箱底下沿紧邻一条**薄亮边**(车面边梁;
- // 地面/下层箱顶/月台是厚亮面,由 contact_max_h_ratio 排除),
- // 且门板数 ≤4、下半幅不是连续地面。
- // P0-Q3:薄边门限取 1.5% 画幅(至少 4 px)。旧值 3% 在 720p 下要 ≥21.6 px,
- // 会把侧视 X70 的 8~9 px 车面边梁排除,只剩厚亮面(地面/箱顶)能命中 ——
- // 方向刚好反了。A 的 5~8 px 箱底下侧梁仍低于门限,不会误判。
- const double min_contact_h = std::max(4.0, 0.015 * work.height);
- V2Band contact_band;
- for (const V2Band& b : bright) {
- if (b.y0 >= box.y1 - 1.0 && b.y0 < box.y1 + 1.0 &&
- b.height() >= min_contact_h && b.height() > contact_band.height()) {
- contact_band = b;
- }
- }
- // P0-Q3:贴合亮带也必须是"薄边"。地面/下层箱顶/月台是厚亮面,
- // 只靠"箱底紧邻亮带"会把地面堆料判成平车(现场合成 ground 场景实测过)。
- if (contact_band.height() > 0.0 &&
- contact_band.height() > p_.contact_max_h_ratio * est_h) {
- contact_band = V2Band{};
- }
- const bool flat_contact =
- !thick_contact && contact_band.height() > 0.0 &&
- static_cast<int>(posts.size()) <= p_.flat_max_door_posts &&
- opacity >= p_.min_wall_opacity &&
- // 近距/落位帧车面本身占满动态 ROI,分块“地面样”会偏低,
- // 因此不能要求 ground >= 0.4;只需排除连续地面(>=0.65)。
- // 与 Python `_classify` 的 flat_strong 同口径。
- ground < p_.min_zero_ground_ratio;
- if (flat_contact) {
- bed = contact_band; // 车面亮带 = 箱底直接接触的 deck edge
- deck_edge = true;
- }
- // P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。
- // 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。
- // 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。
- bool under_deck = false;
- if (bed.height() > 0.0) {
- const auto row_mean = [&](int x0, int x1, int y0, int y1) -> double {
- x0 = std::max(0, std::min(x0, work.width));
- x1 = std::max(x0, std::min(x1, work.width));
- y0 = std::max(0, std::min(y0, work.height));
- y1 = std::max(y0, std::min(y1, work.height));
- if (x1 <= x0 || y1 <= y0) { return 0.0; }
- double sum = 0.0;
- long long n = 0;
- for (int y = y0; y < y1; ++y) {
- for (int x = x0; x < x1; ++x) {
- sum += static_cast<double>(work.at(x, y));
- ++n;
- }
- }
- return n > 0 ? sum / static_cast<double>(n) : 0.0;
- };
- const double band_mean = row_mean(
- window[0], window[2], static_cast<int>(std::lround(bed.y0)),
- static_cast<int>(std::lround(bed.y1)));
- const int probe_h = std::max(
- 2, static_cast<int>(std::lround(p_.under_deck_min_h_ratio * work.height)));
- const int search_h = std::max(
- probe_h + 1,
- static_cast<int>(std::lround(p_.under_deck_search_h_ratio * work.height)));
- const int probe_y0 = std::max(0, static_cast<int>(std::lround(bed.y1)));
- const int probe_y1 = std::min(work.height - 1, probe_y0 + search_h);
- double darkest = std::numeric_limits<double>::max();
- for (int y = probe_y0; y + probe_h <= probe_y1; ++y) {
- darkest = std::min(darkest, row_mean(window[0], window[2], y, y + probe_h));
- }
- under_deck = darkest < std::numeric_limits<double>::max() &&
- darkest <= band_mean - p_.under_deck_dark_delta;
- }
- deck_edge = deck_edge && under_deck;
- std::optional<double> gap_px;
- if (bed.height() > 0.0) {
- gap_px = std::max(0.0, (bed.y0 - box.y1) / std::max(scale, 1e-6));
- }
- std::optional<double> gap_m;
- if (gap_px.has_value() && px_per_m.has_value() && *px_per_m > 0.0) {
- gap_m = *gap_px / *px_per_m;
- }
- const double post_spacing_px_orig =
- spacing_median.has_value() ? *spacing_median / std::max(scale, 1e-6) : 0.0;
- // 门板阵列的横向跨度(工作坐标,归一化到工作宽度)。
- double post_span_ratio = 0.0;
- if (out.post_positions.size() >= 2) {
- post_span_ratio = (out.post_positions.back() - out.post_positions.front()) /
- std::max(1.0, static_cast<double>(work.width));
- }
- const ClassifyResult cls = classify(
- static_cast<int>(posts.size()), spacing_cv, opacity, ground, deck_edge, 0, gap_px,
- still, p_.view, crop.height / std::max(scale, 1e-6), under_deck,
- post_spacing_px_orig, diagonal, post_span_ratio);
- // P0-Q4:空车/无箱兜底。正常“箱底以下”路径给不出 1(例如空 C70 的
- // 箱底是车体内部的一条横梁,下面数不到立柱)时,用纹理车体 ROI 再数一次
- // 门板立柱;只有“上方能看到天空/车体顶”且正常路径不是 1 时才启用。
- int final_state = cls.state;
- double final_conf = cls.confidence;
- double final_hits = cls.structure_hits;
- std::string final_reason = cls.reason;
- std::optional<double> commit_gap_px = gap_px;
- std::optional<double> commit_gap_m = gap_m;
- BodyEvidence body;
- bool body_override = false;
- int body_y0 = 0;
- int body_y1 = 0;
- if (p_.body_fallback_enable && texture_top > 0.0 && cls.state != 1 &&
- texture_top > window[1] + 0.05 * work.height) {
- body_y0 = std::max(window[1], static_cast<int>(std::lround(texture_top)));
- body_y1 = std::min(
- window[3], static_cast<int>(std::lround(
- texture_top + p_.body_bottom_ratio *
- (window[3] - texture_top))));
- if (body_y1 > body_y0) {
- body = measure_body(work, window[0], body_y0, window[2], body_y1, p_, scale);
- const double body_h_orig = body.height / std::max(scale, 1e-6);
- if (body_h_orig >= static_cast<double>(p_.body_min_roi_px) &&
- body.posts >= p_.min_door_posts &&
- body.span_ratio >= p_.min_post_span_ratio &&
- body.opacity >= p_.body_min_opacity &&
- body.diagonal >= p_.min_diagonal_braces) {
- body_override = true;
- final_state = 1;
- final_conf = std::min(
- 1.0, 0.55 + 0.25 * std::min(1.0, body.posts / 8.0) +
- 0.15 * body.opacity);
- final_hits = std::min(
- 1.0, 0.40 + 0.05 * body.posts + 0.20 * body.opacity);
- final_reason = "body_fallback_wall";
- commit_gap_px = 0.0;
- commit_gap_m = 0.0;
- }
- }
- }
- // 安全兜底:能看到“车体顶(上方有天空)”且正常路径给 2,但箱底以下
- // 一根立柱都没有、箱体还在车体内部 → 这是空车/无箱的歧义帧,绝不判 2。
- if (!body_override && texture_top > 0.0 && cls.state == 2 &&
- static_cast<int>(posts.size()) == 0 &&
- box.y1 > texture_top + 0.02 * work.height) {
- final_state = 255;
- final_conf = 0.0;
- final_hits = 0.0;
- final_reason = "ambiguous_empty_vehicle";
- }
- const V2CommitState commit = tracker_.update(
- ts, final_state, commit_gap_m, commit_gap_px, final_hits, still,
- p_.view != "unknown", plc_arrived, plc_spreader_released, hoist_flag);
- out.state = final_state;
- out.confidence = final_conf;
- out.view = p_.view;
- out.body_posts = body.posts;
- out.body_span = body.span_ratio;
- out.body_opacity = body.opacity;
- out.body_diagonal = body.diagonal;
- out.box_bottom_y = box.y1 / std::max(scale, 1e-6);
- out.box_top_y = box_top;
- out.box_h_px = box_h;
- out.px_per_m = px_per_m;
- out.scale_ok = px_per_m.has_value();
- if (bed.height() > 0.0) { out.bed_top_y = bed.y0 / std::max(scale, 1e-6); }
- out.gap_px = commit_gap_px;
- out.gap_m = commit_gap_m;
- if (body_override) {
- out.door_posts = body.posts;
- out.diagonal_braces = body.diagonal;
- out.wall_opacity = body.opacity;
- out.deck_edge = false;
- out.under_deck = false;
- out.ground_ratio = 1.0 - body.opacity;
- } else {
- out.door_posts = static_cast<int>(posts.size());
- if (spacing_median.has_value()) {
- out.post_spacing_px = *spacing_median / std::max(scale, 1e-6);
- }
- out.post_spacing_cv = spacing_cv;
- out.diagonal_braces = diagonal;
- out.wall_opacity = opacity;
- out.deck_edge = deck_edge;
- out.under_deck = under_deck;
- out.ground_ratio = ground;
- }
- out.phase = still ? commit.phase : "T3";
- out.committed = commit.committed;
- out.commit_reason = commit.reason;
- out.stable_frames = commit.stable_frames;
- out.structure_frames = commit.structure_frames;
- out.motion_ok = still;
- out.hoist_high = hoist_flag;
- out.hoist_injected = hoist_high;
- out.hoist_lines = hoist_cues.horizontal_lines;
- out.hoist_cables = hoist_cues.cables;
- out.hoist_limit_px = hoist_cues.limit_px;
- out.spreader_contact = spreader_cues.contact;
- out.spreader_dark_run_px = spreader_cues.dark_run_px;
- // 弃权原因要能直接回答"为什么不用这一帧":吊具未松开与吊具高悬是两件事,
- // 现场排查方向不同(前者看开锁信号,后者看起升高度),所以这里分开写。
- out.abstain_reason = !hoist_flag
- ? (final_state == 255 ? final_reason : "")
- : (spreader_cues.contact ? "spreader_contact" : "hoist_high");
- if (body_override) {
- out.below_roi[0] = static_cast<int>(std::lround(window[0] / scale));
- out.below_roi[1] = static_cast<int>(std::lround(body_y0 / scale));
- out.below_roi[2] = static_cast<int>(std::lround(window[2] / scale));
- out.below_roi[3] = static_cast<int>(std::lround(body_y1 / scale));
- } else {
- out.below_roi[0] = static_cast<int>(std::lround(x0w / scale));
- out.below_roi[1] = static_cast<int>(std::lround(y0w / scale));
- out.below_roi[2] = static_cast<int>(std::lround(x1w / scale));
- out.below_roi[3] = static_cast<int>(std::lround((y0w + crop.height) / scale));
- }
- out.class_reason = final_reason;
- last_ = out;
- (void)edge_density;
- (void)motion_diff;
- (void)motion_ratio;
- return out;
- }
- } // namespace portcv
|