| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664 |
- // 二维边缘几何证据 · L3~L11 实现(自标尺 → 轨向 → 证据组 → 硬门槛 → 弃权 → 运动门控)。
- //
- // 与 docs/edge_evidence.md 的对应关系(评审时逐条可查):
- // §1.3 自标尺:近端竖棱像素长 / box_height_m(20/40 尺箱高同为 2.591 m → 现场不整定)
- // §2.2 证据:P1~P4(车斗)/ F1~F4(平车)/ G1~G3(无关场景)
- // §2.3 优先级:无箱 → 有箱 → A/B 组 → C 组;冲突/证据不足 → 255;运动 → 不改变判定
- // §3.5 线段有效性:长度 / 角度 / 越界比例 / 强度分位 / 纹理掩膜
- // §3.7 "明→暗→明" 车底空隙带;§3.8 暗腔;§3.9 投票与弃权
- // §12.4 C 通道(v1.1 主判据);§12.8 Q4 多目标就近优先
- //
- // 工程近似(**已明确记录**,现场整定时可逐条替换,不影响其它判据):
- // 1) 箱体轮廓用"近端竖棱 + 上/下横棱"构成的平行四边形(§3.2 第 4 步允许不完全平行);
- // 2) 高度带用图像 y 换算(近端竖棱与图像竖直夹角 ≤ 25° 时误差 ≤ 10%);
- // 3) "地面样"用灰度块统计近似(密度落在 [lo,hi] 且块内无长直线)——真机上若有彩色通道,
- // 只需替换 `region_stats()` 一处(Python 取证工具 `scripts/field_clip_probe.py --veg`
- // 已用植被比例,两者结论方向一致);
- // 4) P1/P2/P3 取"左右越界带**至少一侧**成立"(§12.3 实测:取景太近时越界带宽度不可靠,
- // 若按"两侧都必须成立",40 尺近满车会直接从 A 组掉到 C 组)。
- #include "portcv/edge_evidence.hpp"
- #include <algorithm>
- #include <cmath>
- #include <cstdio>
- #include <cstdlib>
- namespace portcv {
- namespace {
- /// 现场排错开关:`PORTCV_EDGE_TRACE=1` 时把几何中间量打到 stderr(默认关闭,零输出)。
- bool edge_trace_on() {
- static const bool on = []() {
- const char* v = std::getenv("PORTCV_EDGE_TRACE");
- return v != nullptr && v[0] != '\0' && v[0] != '0';
- }();
- return on;
- }
- /// 相对箱高 → 图像 y 的换算(rel=0 箱底、rel=1 箱顶、rel<0 箱底以下)。
- struct HeightMap {
- double y_bottom = 0.0; ///< rel = 0 的 y(箱底)
- double y_top = 0.0; ///< rel = 1 的 y(箱顶,比 y_bottom 小)
- double y_of(double rel) const { return y_bottom + rel * (y_top - y_bottom); }
- double rel_of(double y) const {
- const double d = y_top - y_bottom;
- return (d == 0.0) ? 0.0 : (y - y_bottom) / d;
- }
- };
- /// 帧级"强台阶"参考值:相邻行均值差的分位数(§3.7 说的"强台阶"= 灰度的明暗跳变)。
- /// 用整帧做参考而不是固定灰度差,是为了让雨 / 雪 / 夜 / 逆光下同一个阈值语义不变。
- double row_step_reference(const GrayImage& img, double pct) {
- if (img.empty() || img.height < 2) { return 0.0; }
- std::vector<float> diffs;
- diffs.reserve(static_cast<std::size_t>(img.height - 1));
- for (int y = 0; y + 1 < img.height; ++y) {
- double a = 0.0;
- double b = 0.0;
- for (int x = 0; x < img.width; ++x) {
- a += img.at(x, y);
- b += img.at(x, y + 1);
- }
- a /= static_cast<double>(img.width);
- b /= static_cast<double>(img.width);
- diffs.push_back(static_cast<float>(std::fabs(a - b)));
- }
- return static_cast<double>(percentile(diffs, pct));
- }
- /// 一个矩形区域的统计量(P3 / F2 / G1 / C1 / C3 共用)。
- struct RegionStats {
- double mean = 0.0; ///< 平均灰度
- double edge_density = 0.0; ///< 边缘密度:本地 mag > 帧内 60 分位 的像素比例
- double ground_like = 0.0; ///< "地面样"块比例:密度在 [lo,hi] 且块内无长直线
- double max_step = 0.0; ///< 区域内"相邻行均值差"的最大值(强台阶检测)
- int blocks = 0;
- };
- /// 区域统计。`mag_ref` 传帧内 mag 的 60 分位(调用方算一次,避免逐区域重复排序)。
- RegionStats region_stats(const GrayImage& img, const SobelResult& grad,
- const std::vector<Segment>& segs, double x0, double y0, double x1, double y1,
- const EdgeParams& p, float mag_ref) {
- RegionStats st;
- const int ix0 = std::max(0, static_cast<int>(std::floor(x0)));
- const int ix1 = std::min(img.width - 1, static_cast<int>(std::ceil(x1)));
- const int iy0 = std::max(0, static_cast<int>(std::floor(y0)));
- const int iy1 = std::min(img.height - 1, static_cast<int>(std::ceil(y1)));
- if (ix1 < ix0 || iy1 < iy0) { return st; }
- // 均值 + 边缘密度(一次遍历)
- double sum = 0.0;
- long long n = 0;
- long long hot = 0;
- for (int y = iy0; y <= iy1; ++y) {
- for (int x = ix0; x <= ix1; ++x) {
- sum += static_cast<double>(img.at(x, y));
- if (grad.mag_at(x, y) > mag_ref) { ++hot; }
- ++n;
- }
- }
- if (n == 0) { return st; }
- st.mean = sum / static_cast<double>(n);
- st.edge_density = static_cast<double>(hot) / static_cast<double>(n);
- // 最大行间台阶
- for (int y = iy0; y + 1 <= iy1; ++y) {
- double a = 0.0;
- double b = 0.0;
- for (int x = ix0; x <= ix1; ++x) {
- a += img.at(x, y);
- b += img.at(x, y + 1);
- }
- const double d = std::fabs(a - b) / static_cast<double>(ix1 - ix0 + 1);
- st.max_step = std::max(st.max_step, d);
- }
- // "地面样"块比例
- const int b = std::max(6, static_cast<int>(p.ground_block_px));
- long long ground_blocks = 0;
- long long total_blocks = 0;
- for (int by = iy0; by <= iy1; by += b) {
- for (int bx = ix0; bx <= ix1; bx += b) {
- const int ex = std::min(ix1, bx + b - 1);
- const int ey = std::min(iy1, by + b - 1);
- long long bn = 0;
- long long bhot = 0;
- for (int y = by; y <= ey; ++y) {
- for (int x = bx; x <= ex; ++x) {
- if (grad.mag_at(x, y) > mag_ref) { ++bhot; }
- ++bn;
- }
- }
- if (bn == 0) { continue; }
- const double density = static_cast<double>(bhot) / static_cast<double>(bn);
- // 块内有"长直线"→ 视为结构面(不是地面纹理)
- bool has_long_line = false;
- for (const Segment& s : segs) {
- if (s.length < 0.6 * static_cast<double>(b)) { continue; }
- if (s.cx() < bx || s.cx() > ex || s.cy() < by || s.cy() > ey) { continue; }
- has_long_line = true;
- break;
- }
- ++total_blocks;
- if (!has_long_line && density >= p.ground_density_lo && density <= p.ground_density_hi) {
- ++ground_blocks;
- }
- }
- }
- st.blocks = static_cast<int>(total_blocks);
- st.ground_like = total_blocks > 0
- ? static_cast<double>(ground_blocks) / static_cast<double>(total_blocks)
- : 0.0;
- return st;
- }
- } // namespace
- // ---------------------------------------------------------------- 帧上下文与预处理
- namespace {
- /// 一帧的中间结果(只在 analyze() 内部使用;对外暴露的是 Evidence)。
- struct FrameContext {
- GrayImage work; ///< 预处理后的工作图(长边 ≈ edge.work_width)
- SobelResult grad;
- std::vector<uint8_t> edges;
- std::vector<Segment> segs;
- float strong_threshold = 0.0f; ///< 线段 contrast 的 grad_pct 分位(§3.5 ④ 的"强边门")
- float mag_ref = 0.0f; ///< mag 的 60 分位(边缘密度参考)
- double row_step_ref = 0.0; ///< 强台阶参考(相邻行均值差的分位)
- BoxOutline outline;
- std::vector<PointF> poly; ///< 箱体轮廓四边形
- HeightMap hm; ///< 相对箱高 ↔ 图像 y
- double x_min = 0.0; ///< 箱轮廓 x 范围
- double x_max = 0.0;
- double strip_w = 0.0; ///< 越界带宽度(= cross_ratio_hi × 箱宽)
- bool low_light = false; ///< 原始帧过暗/低对比(夜间/逆光);任何状态都不猜
- double mean_gray = 0.0; ///< 原始帧均值(诊断用)
- double p05_gray = 0.0; ///< 原始帧 5 分位
- double p95_gray = 0.0; ///< 原始帧 95 分位
- };
- /// 预处理(§3.1 的顺序):降采样 → 3×3 中值 → 3×3 高斯 → CLAHE 光照归一。
- /// 说明:先降采样后滤波,等价于"在目标分辨率上滤波",且把单帧成本压到 20~40 ms 量级。
- GrayImage preprocess(const GrayImage& src, const EdgeParams& p) {
- double scale = 1.0;
- GrayImage work = resize_long_side(src, p.work_width, &scale);
- median3x3_inplace(&work);
- gaussian3x3_inplace(&work);
- if (p.use_clahe) { clahe_lite_inplace(&work, p.clahe_tiles, p.clahe_clip); }
- return work;
- }
- /// 线段中点所在的高度(相对箱高)。
- inline double mid_rel(const Segment& s, const HeightMap& hm) { return hm.rel_of(s.cy()); }
- /// 两条线段所在直线的交点(参数方程)。平行 / 退化 → false。
- bool line_intersection(const Segment& a, const Segment& b, PointF* out) {
- const double ax = a.x2 - a.x1;
- const double ay = a.y2 - a.y1;
- const double bx = b.x2 - b.x1;
- const double by = b.y2 - b.y1;
- const double den = ax * by - ay * bx;
- if (std::fabs(den) < 1e-9) { return false; }
- const double t = ((b.x1 - a.x1) * by - (b.y1 - a.y1) * bx) / den;
- if (out != nullptr) {
- out->first = a.x1 + t * ax;
- out->second = a.y1 + t * ay;
- }
- return true;
- }
- /// 某处的"轨向像方向"(度):从该点指向轨向消失点;没有消失点时退化为常量角度。
- inline double track_dir_angle_at(const BoxOutline& o, double x, double y) {
- if (!o.has_vp) { return o.track_angle_deg; }
- const double dx = o.track_vp.first - x;
- const double dy = o.track_vp.second - y;
- if (std::fabs(dx) < 1e-6 && std::fabs(dy) < 1e-6) { return o.track_angle_deg; }
- return normalize_angle_deg(std::atan2(dy, dx) * 180.0 / 3.14159265358979323846);
- }
- /// 箱体轮廓构建(§3.2):① 竖直候选 → 近端竖棱;② 上/下横棱;③ 轨向;④ 平行四边形。
- /// `boxes_seen` 统计"疑似箱体数"(≥ near_edge_px 的长竖棱条数),供 §12.8 Q4 的
- /// "多目标就近优先"与置信度折减使用。
- BoxOutline build_outline(const std::vector<Segment>& segs, const GrayImage& img, const EdgeParams& p,
- int* boxes_seen) {
- BoxOutline out;
- if (boxes_seen != nullptr) { *boxes_seen = 0; }
- // ① 竖直候选:与图像竖直方向夹角 ≤ 25°(即 |angle_deg| ≥ 65°,§3.2 ②)
- // ⚠ 不能"只挑最长的那条":贴着相机下方的钢轨在图像里也能到 65~80°,而且往往比
- // 真正的箱体竖棱还长 —— 实测 960×540 合成场景里就把一条 67.5° 的轨线当成了近端竖棱,
- // 导致 px_per_m 偏小 13%、并把轮廓锚点落到轨线上。
- // 这里按"长度 × 竖直度权重"排序(真竖直 = 1.0、65° 处降到 0.55),
- // 再依次尝试,优先采用"上 / 下横棱都能找到、且横棱与竖棱近似垂直"的候选。
- std::vector<const Segment*> verts;
- verts.reserve(segs.size());
- for (const Segment& s : segs) {
- if (std::fabs(s.angle_deg) >= 65.0 && s.length >= 10.0) { verts.push_back(&s); }
- }
- if (verts.empty()) { return out; }
- auto vertical_weight = [](const Segment* s) {
- const double t = std::min(1.0, std::max(0.0, (std::fabs(s->angle_deg) - 65.0) / 25.0));
- return 0.55 + 0.45 * t; // 65° → 0.55,85° 以上 → 1.0
- };
- std::stable_sort(verts.begin(), verts.end(), [&vertical_weight](const Segment* a,
- const Segment* b) {
- return a->length * vertical_weight(a) > b->length * vertical_weight(b);
- });
- if (boxes_seen != nullptr) {
- int count = 0;
- for (const Segment* s : verts) {
- if (s->length >= p.near_edge_px) { ++count; }
- }
- *boxes_seen = count > 0 ? count : 1;
- }
- // ③ 以竖棱两端为锚,搜索上 / 下横棱(与水平夹角 ≤ 30°,落在锚点邻域内)
- auto find_cross = [&](const PointF& anchor) -> const Segment* {
- const Segment* best = nullptr;
- const double win_x = 0.6 * out.near_len_px;
- const double win_y = 0.20 * out.near_len_px;
- for (const Segment& s : segs) {
- if (std::fabs(s.angle_deg) > 30.0) { continue; } // 只收"横向"边
- if (s.length < 0.25 * out.near_len_px) { continue; }
- const double dx = std::fabs(s.cx() - anchor.first);
- const double dy = std::fabs(s.cy() - anchor.second);
- if (dx > win_x + 0.5 * s.length || dy > win_y) { continue; }
- if (best == nullptr || s.length > best->length) { best = &s; }
- }
- return best;
- };
- /// 横棱应与竖棱近似垂直(±25°):否则会把"另一条平行斜线"当成横棱。
- auto perp_ok = [](const Segment* cross, const Segment* vert) {
- return std::fabs(angle_diff_deg(cross->angle_deg, vert->angle_deg + 90.0)) <= 25.0;
- };
- auto top_of = [](const Segment* s) -> PointF {
- return (s->y1 <= s->y2) ? PointF{s->x1, s->y1} : PointF{s->x2, s->y2};
- };
- auto bottom_of = [](const Segment* s) -> PointF {
- return (s->y1 <= s->y2) ? PointF{s->x2, s->y2} : PointF{s->x1, s->y1};
- };
- // ② 候选择优(§1.3):近端竖棱 = **箱底端点最靠下**(离相机最近)的闭合候选,
- // 不是"图像里最长的那条"。车厢端柱/背景竖线可能比 2.59 m 箱高还长,
- // 按长度选会把它们当箱体竖棱 → 自标尺与所有高度带判据全错。
- const Segment* best_strict = nullptr;
- double best_bottom_y = -1e18;
- for (const Segment* cand : verts) {
- const PointF top = top_of(cand);
- const PointF bot = bottom_of(cand);
- const Segment* t = find_cross(top);
- const Segment* b = find_cross(bot);
- if (t == nullptr || b == nullptr || !perp_ok(t, cand) || !perp_ok(b, cand)) { continue; }
- const double bottom_y = bot.second;
- if (best_strict == nullptr || bottom_y > best_bottom_y ||
- (bottom_y == best_bottom_y &&
- cand->length * vertical_weight(cand) >
- best_strict->length * vertical_weight(best_strict))) {
- best_strict = cand;
- best_bottom_y = bottom_y;
- }
- }
- const Segment* chosen = (best_strict != nullptr) ? best_strict : verts.front();
- out.near_len_px = chosen->length;
- out.near_top = top_of(chosen);
- out.near_bottom = bottom_of(chosen);
- const Segment* seg_top = find_cross(out.near_top);
- const Segment* seg_bottom = find_cross(out.near_bottom);
- out.near_edge_strict = (best_strict != nullptr);
- if (!out.near_edge_strict) { out.track_low = true; }
- // ④ 轨向(§3.3):箱顶 / 箱底横棱与轨向平行(同灭点 → 图像里同斜率);
- // 两者都不可靠 → 退化为图像水平并置 TRACKDIR_LOW。
- double width_px = 0.0;
- double dir_x = 1.0;
- double dir_y = 0.0;
- bool have_dir = false;
- for (const Segment* s : {seg_top, seg_bottom}) {
- if (s == nullptr) { continue; }
- width_px = std::max(width_px, s->length);
- if (!have_dir) {
- const bool from_top = (s == seg_top);
- const PointF anchor = from_top ? out.near_top : out.near_bottom;
- // 远端端点 = 离锚点更远的那个端点(决定"往画面哪边是纵深方向")
- const double d1 = std::hypot(s->x1 - anchor.first, s->y1 - anchor.second);
- const double d2 = std::hypot(s->x2 - anchor.first, s->y2 - anchor.second);
- const double fx = (d1 >= d2) ? s->x1 : s->x2;
- const double fy = (d1 >= d2) ? s->y1 : s->y2;
- const double len = std::hypot(fx - anchor.first, fy - anchor.second);
- if (len > 1e-6) {
- dir_x = (fx - anchor.first) / len;
- dir_y = (fy - anchor.second) / len;
- have_dir = true;
- }
- }
- }
- if (width_px <= 0.0) { width_px = 0.6 * out.near_len_px; }
- width_px = std::min(std::max(width_px, 0.30 * out.near_len_px), 3.0 * out.near_len_px);
- if (!have_dir) {
- // 退化:朝画面外侧(远离主点)的方向当纵深
- dir_x = (out.near_top.first < img.width * 0.5) ? 1.0 : -1.0;
- dir_y = 0.0;
- out.track_low = true;
- }
- out.track_angle_deg =
- normalize_angle_deg(std::atan2(dir_y, dir_x) * 180.0 / 3.14159265358979323846);
- out.width_px = width_px;
- out.far_top = {out.near_top.first + dir_x * width_px, out.near_top.second + dir_y * width_px};
- out.far_bottom = {out.near_bottom.first + dir_x * width_px,
- out.near_bottom.second + dir_y * width_px};
- // 轨向消失点 = 箱顶棱与箱底棱所在直线的交点(两者都是轨向直线,§3.3)
- if (seg_top != nullptr && seg_bottom != nullptr) {
- PointF vp;
- if (line_intersection(*seg_top, *seg_bottom, &vp)) {
- out.track_vp = vp;
- out.has_vp = true;
- out.track_angle_deg = track_dir_angle_at(out, out.near_top.first, out.near_top.second);
- }
- }
- // 轮廓质量因子(§2.4)= min(1, 近端竖棱 px / 120);若竖棱**没能闭合出平行四边形**
- // (near_edge_strict=false —— 可能把钢轨之类的斜线当成了竖棱)再打折 20%:
- // 让上层投票(confidence)与现场排错都能看出"这一帧的标尺不太可信"。
- out.quality = std::min(1.0, out.near_len_px / 120.0) * (out.near_edge_strict ? 1.0 : 0.8);
- out.ok = out.near_len_px >= 10.0;
- return out;
- }
- } // namespace
- // ---------------------------------------------------------------- 共用工具(越界性 / 纹理掩膜)
- namespace {
- /// 线段"越出箱体轮廓"的左右两侧长度(§3.5 ③ 越界性;侧别用采样点 x 与箱轮廓中心比较)。
- /// - left_len / right_len:两侧各自的"越出总长";
- /// - left_run / right_run:两侧各自的"最长连续越出段"(§2.2 要求"每段 ≥ 20 px");
- /// - ratio:越出比例(要求 ≥ edge.min_out_ratio)。
- struct OutSpans {
- double left_len = 0.0;
- double right_len = 0.0;
- double left_run = 0.0;
- double right_run = 0.0;
- double ratio = 0.0;
- };
- /// 点到凸/凹多边形边界的最短距离(px)。用于排除"贴着箱体轮廓的自身棱线":
- /// 箱体竖波纹只比轮廓外 0.006 m(≈0.2~0.6 px),旧实现把它当成"越出箱体"的强证据,
- /// 在平车/地面场景里制造 P2/F1 假阳性。真实车体结构边离箱侧 ≥0.28 m(≥10 px)。
- double point_polygon_boundary_distance(const PointF& p, const std::vector<PointF>& poly) {
- if (poly.size() < 2) { return 0.0; }
- double best = 1e18;
- for (std::size_t i = 0; i < poly.size(); ++i) {
- const PointF& a = poly[i];
- const PointF& b = poly[(i + 1) % poly.size()];
- const double dx = b.first - a.first;
- const double dy = b.second - a.second;
- const double len2 = dx * dx + dy * dy;
- double t = 0.0;
- if (len2 > 1e-12) {
- t = ((p.first - a.first) * dx + (p.second - a.second) * dy) / len2;
- t = std::min(1.0, std::max(0.0, t));
- }
- const double qx = a.first + t * dx;
- const double qy = a.second + t * dy;
- best = std::min(best, std::hypot(p.first - qx, p.second - qy));
- }
- return best;
- }
- /// 越出判定必须离开箱体边界 ≥3 px:同一份 960 宽工作图上,箱体自身棱线 ≤1 px、
- /// 车体越界带 ≥10 px,因此 3 px 既能滤掉自棱线,又不会吃掉 40 尺近满车只剩 20 px 的边界。
- constexpr double kOutBoundaryMarginPx = 3.0;
- OutSpans out_spans_by_side(const Segment& s, const std::vector<PointF>& poly, double box_cx,
- int samples = 128) {
- OutSpans out;
- if (poly.size() < 3 || samples <= 0 || s.length <= 0.0) { return out; }
- const double step = s.length / static_cast<double>(samples);
- int outside = 0;
- double run = 0.0;
- int side = 0; // -1 左、+1 右、0 未知
- for (int k = 0; k < samples; ++k) {
- const double t = (static_cast<double>(k) + 0.5) / static_cast<double>(samples);
- const PointF p = segment_point(s, t);
- if (point_in_polygon_f(p.first, p.second, poly)) {
- run = 0.0;
- side = 0;
- continue;
- }
- // 贴着轮廓的自棱线(箱体波纹 / 顶底棱)不算"越出":必须离边界 ≥ margin。
- if (point_polygon_boundary_distance(p, poly) < kOutBoundaryMarginPx) {
- run = 0.0;
- side = 0;
- continue;
- }
- ++outside;
- const int cur = (p.first < box_cx) ? -1 : 1;
- if (cur != side) {
- run = 0.0;
- side = cur;
- }
- run += step;
- if (cur < 0) {
- out.left_len += step;
- out.left_run = std::max(out.left_run, run);
- } else {
- out.right_len += step;
- out.right_run = std::max(out.right_run, run);
- }
- }
- out.ratio = static_cast<double>(outside) / static_cast<double>(samples);
- return out;
- }
- /// 纹理掩膜(§3.6):专治"箱体自身线条"——竖向波棱与横线密集。
- /// **关键**:掩膜只在箱体轮廓**内部**生效;判据要求"越出箱体轮廓",因此不会误伤真实证据。
- struct TextureMask {
- bool vertical_ribs = false;
- bool horizontal_lines = false;
- double box_w_px = 0.0;
- bool hit(const Segment& s, const std::vector<PointF>& poly) const {
- if (!point_in_polygon_f(s.cx(), s.cy(), poly)) { return false; }
- if (vertical_ribs && std::fabs(s.angle_deg) >= 60.0) { return true; }
- if (horizontal_lines && std::fabs(s.angle_deg) <= 30.0 && s.length <= 0.60 * box_w_px) {
- return true;
- }
- return false;
- }
- };
- /// 构建纹理掩膜:① 列方向边缘能量的自相关次峰(等距竖棱);② 箱内横向短线群数量(≥5 根)。
- TextureMask build_texture_mask(const FrameContext& ctx, const EdgeParams& p) {
- TextureMask mask;
- mask.box_w_px = ctx.outline.width_px;
- if (!ctx.outline.ok || ctx.poly.size() < 3) { return mask; }
- // ① 竖向波棱:只看箱体轮廓内部的"列边缘能量"
- const int x0 = std::max(0, static_cast<int>(std::floor(ctx.x_min)));
- const int x1 = std::min(ctx.work.width - 1, static_cast<int>(std::ceil(ctx.x_max)));
- std::vector<double> energy;
- for (int x = x0; x <= x1; ++x) {
- double e = 0.0;
- for (double rel = 0.15; rel <= 1.0; rel += 0.05) { // 避开顶 / 底侧梁
- const double y = ctx.hm.y_of(rel);
- const int iy = static_cast<int>(y + 0.5);
- if (iy < 0 || iy >= ctx.work.height) { continue; }
- if (!point_in_polygon_f(x + 0.5, y, ctx.poly)) { continue; }
- e += static_cast<double>(ctx.grad.mag_at(x, iy));
- }
- energy.push_back(e);
- }
- const double lag_lo = std::max(3.0, p.texture_period_lo * ctx.outline.width_px);
- const double lag_hi = std::max(lag_lo + 1.0, p.texture_period_hi * ctx.outline.width_px);
- double best = 0.0;
- for (int lag = static_cast<int>(lag_lo);
- lag <= static_cast<int>(lag_hi) && static_cast<std::size_t>(lag) < energy.size(); ++lag) {
- double num = 0.0;
- double da = 0.0;
- double db = 0.0;
- for (std::size_t k = 0; k + static_cast<std::size_t>(lag) < energy.size(); ++k) {
- num += energy[k] * energy[k + static_cast<std::size_t>(lag)];
- da += energy[k] * energy[k];
- db += energy[k + static_cast<std::size_t>(lag)] * energy[k + static_cast<std::size_t>(lag)];
- }
- const double den = std::sqrt(da * db);
- if (den > 1e-9) { best = std::max(best, num / den); }
- }
- mask.vertical_ribs = best >= 0.5; // 归一化自相关次峰明显 → 等距棱条
- // ② 横线密集:箱体轮廓内部的短横线数量(门 / 锁杆横档 / 喷字 / 反光带)
- int short_lines = 0;
- for (const Segment& s : ctx.segs) {
- if (std::fabs(s.angle_deg) > 30.0) { continue; }
- if (s.length < 10.0 || s.length > 0.60 * mask.box_w_px) { continue; }
- if (!point_in_polygon_f(s.cx(), s.cy(), ctx.poly)) { continue; }
- ++short_lines;
- }
- mask.horizontal_lines = short_lines >= 5;
- return mask;
- }
- } // namespace
- // ---------------------------------------------------------------- 高度带剖面 / 墙体验证 / 下身统计
- namespace {
- /// 越界带的 x 区间(左侧带 = 箱轮廓左边界之外的窄带;右侧带同理)。
- void side_strips(const FrameContext& ctx, const EdgeParams& p, double* left_x0, double* left_x1,
- double* right_x0, double* right_x1) {
- const double w = std::max(ctx.strip_w, p.cross_ratio_lo * ctx.outline.width_px);
- const double w_img = static_cast<double>(ctx.work.width - 1);
- if (left_x0 != nullptr) { *left_x0 = std::max(0.0, ctx.x_min - w); }
- if (left_x1 != nullptr) { *left_x1 = std::max(0.0, ctx.x_min - 1.0); }
- if (right_x0 != nullptr) { *right_x0 = std::min(w_img, ctx.x_max + 1.0); }
- if (right_x1 != nullptr) { *right_x1 = std::min(w_img, ctx.x_max + w); }
- }
- /// P3 的"实体墙体"判定(单侧越界带):低梯度大平面 + 明确的金属直线 + 看不到地面(§2.2)。
- bool evaluate_wall_strip(const FrameContext& ctx, const EdgeParams& p, double x0, double x1,
- double y_top, double y_bot) {
- if (x1 - x0 < 3.0 || y_bot - y_top < 3.0) { return false; }
- const RegionStats st =
- region_stats(ctx.work, ctx.grad, ctx.segs, x0, y_top, x1, y_bot, p, ctx.mag_ref);
- if (st.blocks <= 0) { return false; }
- if (st.edge_density > p.wall_density_max) { return false; } // ① 低梯度"大平面"
- if (st.ground_like >= p.c1_below_ground_max) { return false; } // ② 看不到地面
- for (const Segment& s : ctx.segs) { // ③ 明确的结构直线
- if (s.length < p.min_len_cross_px || s.contrast < ctx.strong_threshold) { continue; }
- if (s.cx() < x0 || s.cx() > x1) { continue; }
- if (s.cy() < y_top || s.cy() > y_bot) { continue; }
- return true;
- }
- return false;
- }
- /// 沿一条竖直线取"平滑后的亮度剖面"(§3.7 的明-暗-明 / 接触阴影都用它)。
- /// 相对高度 rel_lo..rel_hi(可为负 = 箱底以下),n 个样本;每个样本横向取 3 列均值抗噪。
- struct ColumnProfile {
- std::vector<double> v;
- double rel_lo = 0.0;
- double drel = 0.0;
- double range() const {
- if (v.empty()) { return 0.0; }
- double lo = v[0];
- double hi = v[0];
- for (double x : v) {
- lo = std::min(lo, x);
- hi = std::max(hi, x);
- }
- return hi - lo;
- }
- };
- ColumnProfile sample_column(const GrayImage& img, double x, const HeightMap& hm, double rel_lo,
- double rel_hi, int n) {
- ColumnProfile prof;
- if (n <= 1) { return prof; }
- prof.rel_lo = rel_lo;
- prof.drel = (rel_hi - rel_lo) / static_cast<double>(n - 1);
- prof.v.reserve(static_cast<std::size_t>(n));
- for (int k = 0; k < n; ++k) {
- const double rel = rel_lo + prof.drel * static_cast<double>(k);
- const double y = hm.y_of(rel);
- prof.v.push_back((img.sample_bilinear(x - 1.0, y) + img.sample_bilinear(x, y) +
- img.sample_bilinear(x + 1.0, y)) /
- 3.0);
- }
- return prof;
- }
- } // namespace
- /// 箱底以下的"下身结构"统计(F2 / G1 / G3 / C1 / C2 共用,只算一次)。
- struct BelowMetrics {
- double gap_col_ratio = 0.0; ///< 看到"明→暗→明"车底空隙的列比例(F2 / C2)
- double contact_ratio = 0.0; ///< 看到"接触阴影"的列比例(G3)
- double strong_step_ratio = 0.0; ///< 出现强台阶的列比例(G1 的反向条件)
- double thick_dark_ratio = 0.0; ///< 亮带下方出现"厚暗区"(>0.32 箱高)的列比例:不透明车帮
- RegionStats region; ///< 箱底以下 0~0.45 箱高的区域统计(G1)
- };
- /// 逐列剖线分析(§3.7):只有"多数列"都看到同一种结构,才认为该结构成立 —— 抗局部遮挡。
- /// 高度约定:rel = 0 箱底、rel < 0 为箱底以下。
- ///
- /// 采样区间**按图像下边界自适应**:`[-0.80, +0.10]` 只在画面里确实有这么多箱底以下像素时成立;
- /// 现场常见"箱底贴近画面下沿",若仍按固定 -0.80 采样,`sample_bilinear` 会把整段钳到最后一
- /// 行(所有亮度相同)→ F2 永远 0(2026-10 实测 A/B 片段即如此)。这里把 rel_lo 收到可见下限,
- /// 并把暗带宽度门限按实际可见带宽等比缩小;完全看不到箱底以下时如实判 F2=0,不猜。
- BelowMetrics analyze_below(const FrameContext& ctx, const EdgeParams& p) {
- BelowMetrics m;
- const HeightMap& hm = ctx.hm;
- const double y_last = static_cast<double>(ctx.work.height - 1);
- // 箱底以下实际可采样到的下限(rel 越小 = 越靠画面下方);永久 ≤ +0.10。
- const double rel_floor = std::max(-0.80, hm.rel_of(y_last));
- // 采样列覆盖"箱体 + 两侧越界带":箱体坐在平车地板上时,**箱底正下方被箱体自己挡住**,
- // 真正的"车面板边线 → 车底空隙 → 地面"出现在箱侧越界带里;只采箱体 x 范围会永远
- // 看不到暗带(2026-10 B 片与合成平车都是这个原因)。G1 的 ROI 也用同一横向范围。
- const double below_x0 = std::max(0.0, ctx.x_min - ctx.strip_w);
- const double below_x1 =
- std::min(static_cast<double>(ctx.work.width - 1), ctx.x_max + ctx.strip_w);
- const double region_y0 = hm.y_of(-0.02);
- const double region_y1 = std::min(hm.y_of(-p.gap_band_hi), y_last);
- // G1 用**箱体投影正下方**的 ROI(不含两侧越界带):箱在地面时那里是连续地面;
- // 平车 40 尺近满车时那里是车面板/结构边,不能因为两侧看到地面就判 0。
- m.region = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min, region_y0,
- ctx.x_max, region_y1, p, ctx.mag_ref);
- // 暗带(-0.45..-0.12)实际可见宽度;箱底贴边时按比例降低"连续暗带 ≥0.12 箱高"的门槛。
- const double dark_lo = std::max(rel_floor, -0.45);
- const double dark_avail = std::max(0.0, -0.12 - dark_lo);
- const double dark_run_min = std::min(0.06, std::max(0.04, 0.55 * dark_avail));
- // F2 只在箱底两侧的**近箱带**里找"明→暗→明":箱底正中被箱体挡住,而车面板边线 /
- // 车底空隙就在箱侧 0.1~0.3 箱宽内。左右分别统计,取较好一侧(单侧遮挡不判失败)。
- const double near_band = 0.30 * ctx.outline.width_px;
- const double outer_band = 0.10 * ctx.outline.width_px;
- const double x_img_max = static_cast<double>(ctx.work.width - 1);
- const double left_x0 = std::max(0.0, ctx.x_min - outer_band);
- const double left_x1 = std::max(0.0, ctx.x_min + near_band);
- const double right_x0 = std::min(x_img_max, ctx.x_max - near_band);
- const double right_x1 = std::min(x_img_max, ctx.x_max + outer_band);
- std::vector<double> col_x;
- std::vector<int> col_side; // -1 左、+1 右
- for (int k = 0; k < 11; ++k) {
- if (left_x1 - left_x0 < 1.0) { break; }
- const double t = (static_cast<double>(k) + 0.5) / 11.0;
- col_x.push_back(left_x0 + (left_x1 - left_x0) * t);
- col_side.push_back(-1);
- }
- for (int k = 0; k < 10; ++k) {
- if (right_x1 - right_x0 < 1.0) { break; }
- const double t = (static_cast<double>(k) + 0.5) / 10.0;
- col_x.push_back(right_x0 + (right_x1 - right_x0) * t);
- col_side.push_back(1);
- }
- const int cols = static_cast<int>(col_x.size());
- int used = 0;
- int left_used = 0;
- int right_used = 0;
- int left_candidates = 0;
- int right_candidates = 0;
- int gap_hits = 0;
- int left_gap_hits = 0;
- int right_gap_hits = 0;
- int contact_hits = 0;
- int step_hits = 0;
- int thick_hits = 0;
- for (int k = 0; k < cols; ++k) {
- const double x = col_x[static_cast<std::size_t>(k)];
- const int side = col_side[static_cast<std::size_t>(k)];
- const ColumnProfile prof = sample_column(ctx.work, x, hm, rel_floor, 0.10, 46);
- if (prof.v.size() < 8) { continue; }
- ++used;
- if (side < 0) { ++left_used; } else { ++right_used; }
- double bright1 = -1e9; // 箱底带(≈0 箱高):车面板边线 / 围挡上缘亮带
- double dark_min = 1e9; // 车底空隙带(0.12~0.45 箱高)
- double bright2 = -1e9; // 暗带**下方**的亮部(地面 / 轮对 / 远处):只要 rel ≤ -0.20 都算
- int osc = 0; // 暗带内的方向反转次数(平滑暗带 → 少;条纹 → 多)
- double prev_d = 0.0;
- bool has_prev_d = false;
- for (std::size_t i = 0; i < prof.v.size(); ++i) {
- const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
- const double val = prof.v[i];
- if (rel >= -0.12 && rel <= 0.10) { bright1 = std::max(bright1, val); }
- if (rel >= -0.45 && rel < -0.12) { dark_min = std::min(dark_min, val); }
- if (rel <= -0.20) { bright2 = std::max(bright2, val); }
- if (rel >= -0.45 && rel <= -0.12) {
- const double d = (i > 0) ? (prof.v[i] - prof.v[i - 1]) : 0.0;
- if (has_prev_d && ((d > 0.0) != (prev_d > 0.0)) &&
- std::fabs(d) > 0.05 * prof.range()) {
- ++osc;
- }
- prev_d = d;
- has_prev_d = true;
- }
- }
- const double dynamic = prof.range();
- const double need = std::max(12.0, p.c2_dark_k * dynamic);
- bool gap = false;
- double dark_run = 0.0;
- // 三带都采到才谈"明→暗→明";贴边帧允许只有上半段,但绝不把钳位像素当成结构。
- if (bright1 > -1e8 && dark_min < 1e8 && bright2 > -1e8) {
- const bool usable = (bright1 - dark_min) >= 0.5 * need;
- if (usable) {
- if (side < 0) { ++left_candidates; } else { ++right_candidates; }
- }
- // "明→暗→明":箱底带亮 → 空隙暗 → 更下方重回亮(§3.7 平车 vs 地面的分水岭)
- const bool gap_dir = (bright1 - dark_min) >= need &&
- (bright2 - dark_min) >= 0.40 * need && osc <= 10;
- // 暗带宽度:连续暗区(排除"一根细横线"造成的假暗带);门限随可见带宽缩放。
- double cur_run = 0.0;
- for (std::size_t i = 0; i < prof.v.size(); ++i) {
- const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
- if (rel < -0.45 || rel > -0.12) { continue; }
- if (prof.v[i] <= dark_min + 0.30 * need) {
- cur_run += std::fabs(prof.drel);
- dark_run = std::max(dark_run, cur_run);
- } else {
- cur_run = 0.0;
- }
- }
- gap = gap_dir && dark_run >= dark_run_min && dark_run <= 0.32;
- if (gap) {
- ++gap_hits;
- if (side < 0) { ++left_gap_hits; } else { ++right_gap_hits; }
- }
- if (bright1 - dark_min >= need && dark_run > 0.32) { ++thick_hits; }
- }
- if (edge_trace_on() && (k % 5) == 0) {
- std::fprintf(stderr,
- " col[%d] x=%.1f rel=[%.2f,0.10] b1=%.1f dark=%.1f b2=%.1f "
- "dyn=%.1f need=%.1f run=%.3f min=%.3f gap=%d osc=%d\n",
- k, x, rel_floor, bright1, dark_min, bright2, dynamic, need, dark_run,
- dark_run_min, gap ? 1 : 0, osc);
- }
- // ---- G3 接触特征:贴箱底的窄暗带(接触阴影)且其下明显更亮 ----
- double contact_mean = 0.0;
- double lower_mean = 0.0;
- int contact_n = 0;
- int lower_n = 0;
- for (std::size_t i = 0; i < prof.v.size(); ++i) {
- const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
- if (rel >= -0.06 && rel <= -0.005) {
- contact_mean += prof.v[i];
- ++contact_n;
- } else if (rel >= -0.45 && rel <= -0.12) {
- lower_mean += prof.v[i];
- ++lower_n;
- }
- }
- if (contact_n > 0 && lower_n > 0) {
- contact_mean /= static_cast<double>(contact_n);
- lower_mean /= static_cast<double>(lower_n);
- if (lower_mean - contact_mean >= std::max(6.0, p.contact_dark_k * dynamic)) {
- ++contact_hits;
- }
- }
- // ---- G1 的反向条件:箱底以下是否出现"强台阶"(金属直边)----
- double max_step = 0.0;
- for (std::size_t i = 1; i < prof.v.size(); ++i) {
- const double rel = prof.rel_lo + prof.drel * static_cast<double>(i);
- if (rel < -0.45 || rel > -0.10) { continue; }
- max_step = std::max(max_step, std::fabs(prof.v[i] - prof.v[i - 1]));
- }
- if (max_step >= std::max(8.0, 1.5 * ctx.row_step_ref)) { ++step_hits; }
- }
- if (used > 0) {
- const double left_n = static_cast<double>(std::max(1, left_candidates));
- const double right_n = static_cast<double>(std::max(1, right_candidates));
- const double left_ratio = static_cast<double>(left_gap_hits) / left_n;
- const double right_ratio = static_cast<double>(right_gap_hits) / right_n;
- m.gap_col_ratio = std::max(left_ratio, right_ratio);
- m.contact_ratio = static_cast<double>(contact_hits) / static_cast<double>(used);
- m.strong_step_ratio = static_cast<double>(step_hits) / static_cast<double>(used);
- m.thick_dark_ratio = static_cast<double>(thick_hits) / static_cast<double>(used);
- }
- if (edge_trace_on()) {
- std::fprintf(stderr,
- " below: used=%d gap=%.2f (L=%.2f[%d] R=%.2f[%d]) contact=%.2f step=%.2f "
- "thick=%.2f rel_floor=%.2f region(ground=%.2f mean=%.1f dens=%.2f blocks=%d)\n",
- used, m.gap_col_ratio,
- left_candidates > 0
- ? static_cast<double>(left_gap_hits) / left_candidates
- : 0.0,
- left_candidates,
- right_candidates > 0
- ? static_cast<double>(right_gap_hits) / right_candidates
- : 0.0,
- right_candidates, m.contact_ratio, m.strong_step_ratio, m.thick_dark_ratio,
- rel_floor, m.region.ground_like, m.region.mean, m.region.edge_density,
- m.region.blocks);
- }
- return m;
- }
- // ---------------------------------------------------------------- A 组(车斗 / 敞车)
- namespace {
- /// P1 / P2 / P3 / P4 + C1 / C3(§2.2 + §12.3 + §12.4)。
- void evaluate_a_group(const FrameContext& ctx, const EdgeParams& p, const TextureMask& mask,
- const BelowMetrics& below, Evidence* ev) {
- const HeightMap& hm = ctx.hm;
- const std::vector<PointF>& poly = ctx.poly;
- const double box_cx = 0.5 * (ctx.x_min + ctx.x_max);
- const double track_len = p.min_len_track * ctx.outline.width_px; // §3.5 ① 轨向线最小长
- const double img_w = static_cast<double>(ctx.work.width);
- double left_run = 0.0;
- double right_run = 0.0;
- int near_lines = 0; // 贴着箱体轮廓的候选结构线(VIEW_LIMITED 判定用)
- double c1_line_y = -1.0; // C1 候选亮带的位置
- double c1_line_len = 0.0;
- for (const Segment& s : ctx.segs) {
- const double rel_top0 = hm.rel_of(std::min(s.y1, s.y2));
- const double rel_bottom0 = hm.rel_of(std::max(s.y1, s.y2));
- if (edge_trace_on() && rel_bottom0 >= -0.35 && rel_top0 <= 0.15) {
- std::fprintf(stderr,
- " C1seg pre mask=%d ang=%.1f rel=[%.2f,%.2f] len=%.1f strong=%d\n",
- mask.hit(s, poly) ? 1 : 0, s.angle_deg, rel_top0, rel_bottom0, s.length,
- (s.contrast >= ctx.strong_threshold) ? 1 : 0);
- }
- if (mask.hit(s, poly)) { continue; } // §3.6 纹理掩膜(只在箱轮廓内部生效)
- const bool strong = s.contrast >= ctx.strong_threshold; // §3.5 ④ 强度分位门
- const OutSpans spans = out_spans_by_side(s, poly, box_cx);
- const double rel = mid_rel(s, hm);
- const bool near_box =
- (rel <= 1.10 && rel >= -0.60) &&
- ((s.cx() < box_cx && s.cx() >= ctx.x_min - 1.45 * ctx.strip_w) ||
- (s.cx() >= box_cx && s.cx() <= ctx.x_max + 1.45 * ctx.strip_w));
- if (near_box && strong && std::fabs(s.angle_deg) >= 55.0) { ++near_lines; }
- if (spans.ratio >= p.min_out_ratio) {
- left_run = std::max(left_run, spans.left_run);
- right_run = std::max(right_run, spans.right_run);
- }
- // C1 候选:箱底 ±0.15 箱高内的"贯穿视场"亮带(§12.4)。
- // 不要求 `strong` / 越界比例:车帮上缘是**宽亮带**,Canny 对比可能低于强边门;
- // 它的安全性由"其下看不到地面"与 F2 互斥(C1 成立时 F2 被抑制)保证。
- if (rel_bottom0 >= -0.15 && rel_top0 <= 0.06 &&
- s.length >= std::max(0.5 * ctx.outline.width_px, 0.25 * img_w) &&
- // 亮带下方至少还能看到 0.20 箱高:否则那是画面下沿的地面线,不是车帮亮带。
- std::max(s.y1, s.y2) <=
- static_cast<double>(ctx.work.height - 1) - 0.20 * ctx.outline.near_len_px &&
- s.length > c1_line_len) {
- c1_line_len = s.length;
- c1_line_y = std::max(s.y1, s.y2);
- }
- if (!strong || spans.ratio < p.min_out_ratio) { continue; }
- // 该处的轨向 = 指向轨向消失点的方向(§3.3;平行线在透视下向同一消失点收敛);
- // 没有可靠消失点时自动退化为箱顶/底棱的常量角度。
- const double track_local = track_dir_angle_at(ctx.outline, s.cx(), s.cy());
- const bool track_dir = angle_diff_deg(s.angle_deg, track_local) <= p.line_angle_deg;
- const bool cross_dir = angle_diff_deg(s.angle_deg, track_local + 90.0) <= p.line_angle_deg;
- const double out_run = std::max(spans.left_run, spans.right_run);
- if (edge_trace_on() && spans.ratio >= p.min_out_ratio) {
- std::fprintf(stderr,
- " Aseg cand ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f "
- "track=%d cross=%d strong=%d\n",
- s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
- spans.right_len, track_dir ? 1 : 0, cross_dir ? 1 : 0,
- strong ? 1 : 0);
- }
- // P1 侧墙上缘纵深线:轨向 + 高位带 + 长度 ≥ 0.30×箱宽 + 越出 ≥ 20 px
- if (track_dir && rel >= p.band_high_lo && rel <= p.band_high_hi && s.length >= track_len &&
- out_run >= p.min_len_cross_px) {
- ev->set(EvidenceKey::P1, true);
- }
- // P2 端墙上缘横线:**图像里近水平**(跨轨向的端墙线投影后不会竖直)+ 高位带 +
- // **两侧都越出** ≥20 px(端墙线横穿箱宽,两侧都伸到车宽外;箱体竖棱/端柱做不到)。
- // 旧实现用"与轨向垂直"→ 把箱体竖波纹/车厢端柱当成 P2(合成平车 F3 因此恒假)。
- if (std::fabs(s.angle_deg) <= 25.0 && rel >= p.band_high_lo &&
- rel <= p.band_high_hi &&
- std::min(spans.left_run, spans.right_run) >= p.min_len_cross_px) {
- ev->set(EvidenceKey::P2, true);
- }
- }
- // 越界带实测宽度(§9.3 第 3 项 / §12.3:40 尺近满车时只剩几十像素)
- ev->out_left_px = left_run > 0.0 ? left_run : std::min(ctx.strip_w, std::max(0.0, ctx.x_min));
- ev->out_right_px = right_run > 0.0
- ? right_run
- : std::min(ctx.strip_w, std::max(0.0,
- static_cast<double>(ctx.work.width - 1) -
- ctx.x_max));
- // P3 越界带实体墙体:低梯度大平面 + 明确直线 + 看不到地面
- double lx0 = 0.0;
- double lx1 = 0.0;
- double rx0 = 0.0;
- double rx1 = 0.0;
- side_strips(ctx, p, &lx0, &lx1, &rx0, &rx1);
- const double y_top = hm.y_of(0.75);
- const double y_bot = hm.y_of(0.0);
- ev->set(EvidenceKey::P3, evaluate_wall_strip(ctx, p, lx0, lx1, y_top, y_bot) ||
- evaluate_wall_strip(ctx, p, rx0, rx1, y_top, y_bot));
- // P4 箱–围挡暗腔(§3.8):内侧 0~0.10 箱宽窄带比外侧 0.10~0.35 箱宽明显更暗
- const double w_box = ctx.outline.width_px;
- const RegionStats in_l = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min - 0.10 * w_box,
- hm.y_of(0.70), ctx.x_min, hm.y_of(0.10), p, ctx.mag_ref);
- const RegionStats out_l =
- region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_min - 0.35 * w_box, hm.y_of(0.70),
- ctx.x_min - 0.10 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
- const RegionStats in_r = region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_max, hm.y_of(0.70),
- ctx.x_max + 0.10 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
- const RegionStats out_r =
- region_stats(ctx.work, ctx.grad, ctx.segs, ctx.x_max + 0.10 * w_box, hm.y_of(0.70),
- ctx.x_max + 0.35 * w_box, hm.y_of(0.10), p, ctx.mag_ref);
- const bool p4_left =
- in_l.blocks > 0 && out_l.blocks > 0 && in_l.mean <= p.p4_dark_ratio * out_l.mean;
- const bool p4_right =
- in_r.blocks > 0 && out_r.blocks > 0 && in_r.mean <= p.p4_dark_ratio * out_r.mean;
- ev->set(EvidenceKey::P4, p4_left || p4_right);
- // §12.3 的 C3:箱底以下 ROI 看不到地面(旧口径"全画面占比"会随车距/构图从 0.24 漂到 0.38,
- // 跨在 0.25 阈值两侧 → 同一台车同一机位也抖动)。ROI 口径与 C1 内层的 no_ground_below 同源。
- const double full_w = static_cast<double>(ctx.work.width - 1);
- const double full_h = static_cast<double>(ctx.work.height - 1);
- const RegionStats full =
- region_stats(ctx.work, ctx.grad, ctx.segs, 0.0, 0.0, full_w, full_h, p, ctx.mag_ref);
- ev->ground_ratio_full = full.ground_like;
- ev->ground_ratio_below = below.region.ground_like;
- ev->set(EvidenceKey::C3, below.region.blocks > 0 &&
- below.region.ground_like < p.c1_below_ground_max);
- // §12.4 的 C1:亮带 + 其下看不到地面 + 其下**没有**车底空隙(与平车互斥 → 不会造假冲突)
- bool no_ground_below = false;
- double below_ground = 0.0;
- const bool gap_below = below.gap_col_ratio >= p.c2_col_ratio_min;
- if (c1_line_y > 0.0) {
- const double y_end = std::min(full_h, hm.y_of(-0.45));
- const double y_start = std::max(c1_line_y, hm.y_of(0.06));
- // 亮带下方必须确实有 ≥0.25 箱高的可见区域;否则只是画面下沿的一条线(地面/边框)。
- if (y_end - y_start >= 0.25 * ctx.outline.near_len_px) {
- const RegionStats b = region_stats(ctx.work, ctx.grad, ctx.segs,
- std::max(0.0, ctx.x_min - ctx.strip_w), y_start,
- std::min(full_w, ctx.x_max + ctx.strip_w), y_end, p,
- ctx.mag_ref);
- below_ground = b.ground_like;
- no_ground_below = b.ground_like < p.c1_below_ground_max;
- }
- }
- if (edge_trace_on()) {
- std::fprintf(stderr,
- " C1: line_y=%.1f line_len=%.1f no_ground_below=%d below_ground=%.2f "
- "gap_below=%d gap_ratio=%.2f full_ground=%.2f thick=%.2f region_mean=%.1f\n",
- c1_line_y, c1_line_len, no_ground_below ? 1 : 0, below_ground,
- gap_below ? 1 : 0, below.gap_col_ratio, full.ground_like,
- below.thick_dark_ratio, below.region.mean);
- }
- // C1 主路径:亮带 + 其下看不到地面。补充路径:亮带下方是**厚暗区**(>0.32 箱高的连续
- // 暗面 = 不透明车帮),即使线段通道没把车帮上缘拼成一条长线(夜/雪/纹理断裂)也能判 1。
- const bool opaque_wall = below.thick_dark_ratio >= 0.15 && below.region.blocks > 0 &&
- below.region.mean < 110.0;
- // 地面 ROI(亮 + 高"地面样"占比)直接否决 C1:箱在地面时 C1 必须是假。
- const bool ground_roi = below.region.ground_like >= 0.40 && below.region.mean >= 120.0;
- ev->set(EvidenceKey::C1,
- (((c1_line_y > 0.0) && no_ground_below) || opaque_wall) && !ground_roi);
- ev->view_limited = (ev->out_left_px < p.min_len_cross_px) &&
- (ev->out_right_px < p.min_len_cross_px) && (near_lines >= 1);
- }
- // ---------------------------------------------------------------- B 组(平板车)
- /// F1 低位坐板线 / F2 车底空隙带 / F3 无高位结构 / F4 车端低矮结构 + 平车地板俯视面(§12.4 F4')。
- void evaluate_b_group(const FrameContext& ctx, const EdgeParams& p, const TextureMask& mask,
- const BelowMetrics& below, Evidence* ev) {
- const HeightMap& hm = ctx.hm;
- const std::vector<PointF>& poly = ctx.poly;
- const double box_cx = 0.5 * (ctx.x_min + ctx.x_max);
- // band_low 以"箱底 = 0"为中心;斜前视下贴底横线的**中点**会因纵深透视明显偏高,
- // 因此用"线的 rel 区间与低带相交"判定,高带放到 +0.35 箱高(实测 A/B 与合成都要)。
- const double low_lo = p.band_low_lo - 0.25;
- const double low_hi = p.band_low_hi + 0.25;
- const double track_len = p.min_len_track * ctx.outline.width_px;
- for (const Segment& s : ctx.segs) {
- if (mask.hit(s, poly)) { continue; }
- if (s.contrast < ctx.strong_threshold) { continue; }
- const OutSpans spans = out_spans_by_side(s, poly, box_cx);
- const double rel = mid_rel(s, hm);
- if (edge_trace_on() && rel >= -0.25 && rel <= 0.35) {
- std::fprintf(stderr,
- " F1seg pre ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f\n",
- s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
- spans.right_len);
- }
- if (spans.ratio < p.min_out_ratio) { continue; }
- const double out_run = std::max(spans.left_run, spans.right_run);
- if (edge_trace_on()) {
- std::fprintf(stderr,
- " Bseg ang=%.1f rel=%.2f len=%.1f out=%.2f L=%.1f R=%.1f strong=%d\n",
- s.angle_deg, rel, s.length, spans.ratio, spans.left_len,
- spans.right_len, (s.contrast >= ctx.strong_threshold) ? 1 : 0);
- }
- // F1:贴箱底的强直线,且"左右越出箱体轮廓(每段 ≥ 20 px)或沿轨向长(≥ 0.30×箱长)"。
- // 用线的 rel **区间**与低带相交,而不是中点(车面板边线沿纵深是斜的)。
- const double f1_rel_top = hm.rel_of(std::min(s.y1, s.y2));
- const double f1_rel_bottom = hm.rel_of(std::max(s.y1, s.y2));
- if (f1_rel_bottom >= low_lo && f1_rel_top <= low_hi &&
- (out_run >= p.min_len_cross_px || s.length >= track_len)) {
- ev->set(EvidenceKey::F1, true);
- }
- }
- // F2:车底空隙带(多列剖线的"明→暗→明",§3.7)。
- // 还要求箱底以下 ROI 看得到**地面**:敞车围挡下方是一整片不透明墙,也会形成
- // "亮墙顶→暗墙→远处亮"的假三带;没有地面的"暗带"不是车底空隙。
- ev->set(EvidenceKey::F2, below.gap_col_ratio >= p.c2_col_ratio_min &&
- below.region.ground_like >= 0.18 &&
- below.thick_dark_ratio < 0.40 &&
- !ev->hit[static_cast<int>(EvidenceKey::C1)]);
- // F2 的 bright1 本身就是"车面板边线"(箱底坐板线)。合成/现场都可能出现线段通道
- // 因箱底被遮挡而漏掉 F1 的情况;F2 成立时把 F1 一并置真(低光帧已在 classify 前置 255)。
- if (ev->hit[static_cast<int>(EvidenceKey::F2)]) { ev->set(EvidenceKey::F1, true); }
- // F3:无高位结构 —— 直接取 A 组结论的反(§2.2)
- ev->set(EvidenceKey::F3, !(ev->hit[static_cast<int>(EvidenceKey::P1)] ||
- ev->hit[static_cast<int>(EvidenceKey::P2)] ||
- ev->hit[static_cast<int>(EvidenceKey::P3)]));
- // F4:① 平车地板"俯视面"(§12.4 F4'):箱底正下方 0.02~0.20 箱高的低梯度平面 + 长边线;
- // ② 车端低矮结构(端梁 / 挡块 / 走台):越界带内、略高于箱底(0.05~0.25 箱高)的结构边。
- const double d_lo = hm.y_of(-0.20);
- const double d_hi = hm.y_of(-0.02);
- const RegionStats deck =
- region_stats(ctx.work, ctx.grad, ctx.segs, std::max(0.0, ctx.x_min - ctx.strip_w), d_lo,
- std::min(static_cast<double>(ctx.work.width - 1), ctx.x_max + ctx.strip_w), d_hi,
- p, ctx.mag_ref);
- const bool deck_flat = deck.blocks > 0 && deck.edge_density <= p.wall_density_max &&
- deck.ground_like < 0.50;
- bool deck_long_edge = false;
- for (const Segment& s : ctx.segs) {
- if (s.length < 2.0 * p.min_len_cross_px || s.contrast < ctx.strong_threshold) { continue; }
- if (s.cy() < d_lo || s.cy() > d_hi) { continue; }
- deck_long_edge = true;
- break;
- }
- bool bump = false;
- for (const Segment& s : ctx.segs) {
- if (s.contrast < ctx.strong_threshold || s.length < p.min_len_cross_px) { continue; }
- const OutSpans spans = out_spans_by_side(s, poly, box_cx);
- if (spans.ratio < p.min_out_ratio) { continue; }
- const double rel = mid_rel(s, hm);
- if (rel >= 0.05 && rel <= 0.25) {
- bump = true;
- break;
- }
- }
- ev->set(EvidenceKey::F4, (deck_flat && deck_long_edge) || bump);
- }
- // ---------------------------------------------------------------- C 组(无关场景)
- /// G1 地面连续 / G2 无越界线 / G3 接触特征(§2.2)。
- void evaluate_c_group(const FrameContext& ctx, const EdgeParams& p, const BelowMetrics& below,
- Evidence* ev) {
- // G1:箱底以下 0~0.45 箱高内为连续地面纹理(多数块"地面样" + 无强台阶)
- const bool ground_continuous =
- below.region.blocks > 0 && below.region.ground_like >= 0.40 &&
- below.region.max_step <= std::max(10.0, 2.0 * ctx.row_step_ref);
- ev->set(EvidenceKey::G1, ground_continuous);
- // G2:无越界线 —— P1 / P2 不成立,且 F1 必须与 F2(车底空隙)同时成立。
- // F1 单独出现时可能只是箱体自己的底棱 / 地面纹理(箱坐在地面上与坐在车面上,
- // 单看一条贴底线分不开);F2 才是"车体"的判别证据。B 片 F1∧F2 成立 → G2=0。
- ev->set(EvidenceKey::G2,
- !(ev->hit[static_cast<int>(EvidenceKey::P1)] ||
- ev->hit[static_cast<int>(EvidenceKey::P2)] ||
- (ev->hit[static_cast<int>(EvidenceKey::F1)] &&
- ev->hit[static_cast<int>(EvidenceKey::F2)])));
- // G3:接触特征(接触阴影 / 垫木 / 托盘)
- ev->set(EvidenceKey::G3, below.contact_ratio >= 0.50);
- (void)ctx;
- (void)p;
- }
- /// §3.9 的分数公式(**原样照抄文档**,任何权重调整都要先改文档再改代码):
- /// score_A = 1.0·P1 + 0.9·P2 + 0.8·P3 + 0.6·P4
- /// score_B = 1.0·F1 + 1.0·F2 + 0.7·F3 + 0.5·F4
- /// score_C = 1.0·G1 + 1.0·G2 + 0.5·G3
- void compute_scores(Evidence* ev) {
- const auto h = [ev](EvidenceKey k) { return ev->hit[static_cast<int>(k)] ? 1.0 : 0.0; };
- ev->score_a = 1.0 * h(EvidenceKey::P1) + 0.9 * h(EvidenceKey::P2) + 0.8 * h(EvidenceKey::P3) +
- 0.6 * h(EvidenceKey::P4);
- ev->score_b = 1.0 * h(EvidenceKey::F1) + 1.0 * h(EvidenceKey::F2) + 0.7 * h(EvidenceKey::F3) +
- 0.5 * h(EvidenceKey::F4);
- ev->score_c = 1.0 * h(EvidenceKey::G1) + 1.0 * h(EvidenceKey::G2) + 0.5 * h(EvidenceKey::G3);
- // C2 与 F2 是同一件事实(§12.4 的编号),单独记一份便于现场统计
- ev->set(EvidenceKey::C2, ev->hit[static_cast<int>(EvidenceKey::F2)]);
- }
- } // namespace
- // ---------------------------------------------------------------- 判定(§2.2 硬门槛 / §2.3 优先级 / §2.4 置信度)
- namespace {
- /// 判定结果(内部用)。
- struct Verdict {
- int state = static_cast<int>(SceneState::UNKNOWN);
- double confidence = 0.0;
- EdgeDiag diag = EdgeDiag::NONE;
- bool abstain = false;
- bool conflict = false;
- std::string reason;
- };
- std::string fmt2(const char* pattern, double a, double b) {
- char buf[192];
- std::snprintf(buf, sizeof(buf), pattern, a, b);
- return std::string(buf);
- }
- /// §2.3 的判定优先级 + §2.2 的硬门槛 + §3.9 的弃权 + §2.4 的置信度。
- Verdict classify(const FrameContext& ctx, const EdgeParams& p, Evidence* ev) {
- Verdict v;
- if (ctx.low_light) {
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.confidence = 0.0;
- v.diag = EdgeDiag::SCALE_FAIL;
- v.reason = "low light / low contrast -> 255 (safety)";
- return v;
- }
- const auto h = [ev](EvidenceKey k) { return ev->hit[static_cast<int>(k)]; };
- constexpr double kTotalA = 3.3; // 1.0+0.9+0.8+0.6
- constexpr double kTotalB = 3.2; // 1.0+1.0+0.7+0.5
- constexpr double kTotalC = 2.5; // 1.0+1.0+0.5
- int a_hits = 0;
- for (EvidenceKey k : {EvidenceKey::P1, EvidenceKey::P2, EvidenceKey::P3, EvidenceKey::P4}) {
- if (h(k)) { ++a_hits; }
- }
- // ---------- ① 箱体轮廓未建立(§2.3 ①)----------
- if (!ctx.outline.ok) {
- bool structure = false;
- for (const Segment& s : ctx.segs) {
- if (s.length >= 40.0 && s.contrast >= ctx.strong_threshold) {
- structure = true;
- break;
- }
- }
- if (ev->segments_total >= 3 && structure) {
- v.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
- v.confidence = 0.50;
- v.diag = EdgeDiag::NO_BOX;
- v.reason = "no box outline but wagon structure seen -> 0 (spec 2.3-1)";
- } else {
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.confidence = 0.0;
- v.diag = EdgeDiag::NO_BOX;
- v.reason = "no structure at all -> 255 (spec 2.3-1)";
- }
- return v;
- }
- // ---------- ② 硬门槛(§2.2 / §12.4)----------
- const bool gate_a_doc = (h(EvidenceKey::P1) || h(EvidenceKey::P2)) && h(EvidenceKey::P3);
- // §12.4(v1.1 主判据):C 通道的 C1 本身就是"箱底以下 ≤0.15 箱高的贯穿亮带 + 其下看不到地面",
- // 已隐含"围挡挡住地面"这一条,因此 C1 单独成立即可判 `1`(与 §2.2 的 A 组硬门槛并存,
- // 任一成立 → `1`)。安全性由 C1 内置的 `!gap_below`(没有车底空隙)保证 —— 平车不可能满足它。
- const bool gate_a = gate_a_doc || h(EvidenceKey::C1);
- const bool gate_b_doc = h(EvidenceKey::F1) && h(EvidenceKey::F2) && h(EvidenceKey::F3);
- const bool gate_b = gate_b_doc && p.allow_state2;
- // `0` 还必须 score_A < 1.0(防止"雪盖围挡"被误判为 0 —— §3.9)
- const bool gate_0 = h(EvidenceKey::G1) && h(EvidenceKey::G2) && ev->score_a < 1.0 && !h(EvidenceKey::C1);
- if (gate_a && gate_b_doc) {
- // ---------- 冲突:A 组与 B 组同时成立(§2.3 ②)----------
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.confidence = std::min(0.30, (ev->score_a + ev->score_b) / (kTotalA + kTotalB));
- v.diag = EdgeDiag::CONFLICT;
- v.conflict = true;
- ev->conflict = true;
- v.reason = fmt2("conflict A=%.1f B=%.1f -> 255 (spec 2.3-2)", ev->score_a, ev->score_b);
- } else if (gate_a) {
- v.state = static_cast<int>(SceneState::BED);
- v.confidence = ev->score_a / kTotalA;
- // §12.4 C1 是 1 的**主判据**,但 score_A 只含 P1~P4 → C1-only 帧置信度为 0,
- // 会被 TemporalVoter 的 min_confidence 挡掉(实测 A 片 C1=25/50 却全 255)。
- // 给 C1 支撑的 1 一个明确下限;随后仍乘轮廓质量与多目标折减,低质量/多目标会自然压低。
- if (h(EvidenceKey::C1)) { v.confidence = std::max(v.confidence, 0.75); }
- v.reason = fmt2("bed: scoreA=%.1f/3.3 (spec 2.2 A)", ev->score_a, 0.0);
- if (h(EvidenceKey::C1)) { v.reason += " | C1"; }
- } else if (gate_b) {
- v.state = static_cast<int>(SceneState::FLATBED);
- v.confidence = ev->score_b / kTotalB;
- v.reason = fmt2("flatbed: scoreB=%.1f/3.2 (spec 2.2 B)", ev->score_b, 0.0);
- } else if (gate_0) {
- v.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
- v.confidence = ev->score_c / kTotalC;
- v.reason = fmt2("not on train: scoreC=%.1f/2.5 (spec 2.2 C)", ev->score_c, 0.0);
- } else {
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.confidence = std::max({ev->score_a / kTotalA, ev->score_b / kTotalB, ev->score_c / kTotalC});
- v.reason = fmt2("no gate satisfied: A=%.1f B=%.1f -> 255", ev->score_a, ev->score_b);
- }
- // ---------- ④ 自标尺失效 → 禁止输出 2(§2.3 ④ / §0 安全铁律)----------
- if (!ev->scale_ok && v.state == static_cast<int>(SceneState::FLATBED)) {
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.diag = EdgeDiag::SCALE_FAIL;
- v.reason += " | SCALE_OK=0 -> state 2 forbidden";
- }
- // ---------- 40 尺近满车:越界带不足时不允许 `2`(§5 / §12.8 Q2 ⑤)----------
- if (ev->view_limited && v.state == static_cast<int>(SceneState::FLATBED)) {
- v.state = static_cast<int>(SceneState::UNKNOWN);
- v.diag = EdgeDiag::VIEW_LIMITED;
- v.reason += " | VIEW_LIMITED (out-band too small) -> 255";
- }
- if (ev->view_limited && v.diag == EdgeDiag::NONE) { v.diag = EdgeDiag::VIEW_LIMITED; }
- // ---------- ⑤ 证据项数不足 / 弃权(§2.3 ⑤ / §3.9)----------
- if (v.state == static_cast<int>(SceneState::UNKNOWN) && !v.conflict) {
- const bool insufficient = (a_hits < 2) ||
- (!h(EvidenceKey::F2) && (h(EvidenceKey::F1) || h(EvidenceKey::F3)));
- const bool low_scores = (ev->score_a < 1.8) && (ev->score_b < 1.7) && (ev->score_c < 2.0);
- if (insufficient || low_scores) {
- ev->abstain = true;
- v.reason += " | ABSTAIN (spec 3.9)";
- }
- }
- // ---------- 置信度(§2.4):× 轮廓质量因子;多目标只降置信度(§12.8 Q4)----------
- v.confidence *= ctx.outline.quality;
- if (ev->boxes_seen > 1) { v.confidence *= 0.80; }
- if (v.state == static_cast<int>(SceneState::UNKNOWN)) {
- v.confidence = std::min(v.confidence, 0.25);
- }
- if (v.confidence < 0.0) { v.confidence = 0.0; }
- if (v.confidence > 1.0) { v.confidence = 1.0; }
- return v;
- }
- } // namespace
- // ---------------------------------------------------------------- 对外接口实现
- EdgeEvidence::EdgeEvidence(const EdgeParams& params, const LineParams& lines)
- : p_(params), l_(lines), gate_(params) {
- l_.grad_pct = p_.grad_pct; // §7 的 edge.grad_pct 同时是"线段强度分位门"
- }
- EdgeResult EdgeEvidence::analyze(const GrayImage& gray, double ts) {
- EdgeResult result;
- result.ev.reason = "no frame";
- result.ev.diag = EdgeDiag::NO_BOX;
- // 0) 运动门控(§6):用**原始**灰度(位移与模糊是成像特性,与预处理无关)
- const bool motion = gate_.update(gray, ts);
- result.ev.motion = motion;
- result.ev.motion_held_s = gate_.held_s();
- if (gray.empty()) { return result; }
- // 1) L0~L2:预处理 + 梯度 + 边缘 + 线段
- FrameContext ctx;
- {
- long long sum = 0;
- for (uint8_t v : gray.data) { sum += v; }
- ctx.mean_gray = gray.data.empty() ? 0.0 : static_cast<double>(sum) / gray.data.size();
- ctx.p05_gray = percentile_u8(gray, 0.05);
- ctx.p95_gray = percentile_u8(gray, 0.95);
- // 夜间(均值低)/ 雪天或逆光(灰度动态范围被压缩):都不冒险输出 1/2/0。
- // 实测合成 night mean=67,snow p05..p95 = 140..177(spread 37),正常帧 spread≈73。
- ctx.low_light = ctx.mean_gray < 80.0 || (ctx.p95_gray - ctx.p05_gray) < 50.0;
- }
- ctx.work = preprocess(gray, p_);
- if (edge_trace_on()) {
- std::fprintf(stderr, "frame mean=%.1f p05=%.1f p95=%.1f low_light=%d\n",
- ctx.mean_gray, ctx.p05_gray, ctx.p95_gray, ctx.low_light ? 1 : 0);
- }
- ctx.grad = sobel(ctx.work);
- ctx.edges = canny_lite(ctx.work, ctx.grad, l_.canny_lo_pct, l_.canny_hi_pct);
- ctx.mag_ref = percentile(ctx.grad.mag, 0.60);
- ctx.row_step_ref = row_step_reference(ctx.work, p_.strong_step_pct);
- ctx.segs = extract_segments(ctx.work, ctx.grad, ctx.edges, l_, &ctx.strong_threshold);
- // §3.2 ① 的**补充通道:专用竖直游程**(逐列近箱高的连续游程)。
- // 为什么单开:通用通道在"箱体 + 车体 + 地面 + 钢轨连成一个巨连通域"时会先被水平结构耗尽
- // 迭代预算、并把竖棱切碎 → 自标尺(= 全部高度带判据的**分母**)丢失或错位。
- // 本通道对斜线天然免疫(单列只有 2~3 px),且只读未改动的 `edges`,把竖棱稳定拿回来。
- {
- const std::vector<Segment> vsegs = extract_vertical_runs(ctx.work, ctx.grad, ctx.edges, l_,
- 0.5 * p_.near_edge_px, 4, &ctx.segs);
- ctx.segs.insert(ctx.segs.end(), vsegs.begin(), vsegs.end());
- }
- result.ev.segments_total = static_cast<int>(ctx.segs.size());
- result.ev.strong_threshold = ctx.strong_threshold;
- // 2) L3:箱体轮廓 + 自标尺(§1.3 / §3.2)
- ctx.outline = build_outline(ctx.segs, ctx.work, p_, &result.ev.boxes_seen);
- result.ev.box_h_px = ctx.outline.near_len_px;
- result.ev.box_w_px = ctx.outline.width_px;
- result.ev.outline_quality = ctx.outline.quality;
- result.ev.scale_ok = ctx.outline.ok && (ctx.outline.near_len_px >= p_.near_edge_px);
- result.ev.px_per_m =
- ctx.outline.near_len_px > 0.0 ? ctx.outline.near_len_px / p_.box_height_m : 0.0;
- if (ctx.outline.ok) {
- ctx.poly = ctx.outline.polygon();
- ctx.x_min = ctx.poly[0].first;
- ctx.x_max = ctx.poly[0].first;
- for (const PointF& pt : ctx.poly) {
- ctx.x_min = std::min(ctx.x_min, pt.first);
- ctx.x_max = std::max(ctx.x_max, pt.first);
- }
- ctx.hm.y_bottom = ctx.outline.near_bottom.second;
- ctx.hm.y_top = ctx.outline.near_top.second;
- ctx.strip_w = p_.cross_ratio_hi * ctx.outline.width_px;
- if (edge_trace_on()) {
- std::fprintf(stderr,
- "outline: near_top=(%.1f,%.1f) near_bot=(%.1f,%.1f) "
- "far_top=(%.1f,%.1f) far_bot=(%.1f,%.1f) w=%.1f h=%.1f q=%.2f "
- "x=[%.1f,%.1f] hm=[%.1f,%.1f]\n",
- ctx.outline.near_top.first, ctx.outline.near_top.second,
- ctx.outline.near_bottom.first, ctx.outline.near_bottom.second,
- ctx.outline.far_top.first, ctx.outline.far_top.second,
- ctx.outline.far_bottom.first, ctx.outline.far_bottom.second,
- ctx.outline.width_px, ctx.outline.near_len_px, ctx.outline.quality,
- ctx.x_min, ctx.x_max, ctx.hm.y_top, ctx.hm.y_bottom);
- }
- // 3) L5/L6:纹理掩膜 → 下身统计 → 三组证据(A / B / C)
- const TextureMask mask = build_texture_mask(ctx, p_);
- const BelowMetrics below = analyze_below(ctx, p_);
- evaluate_a_group(ctx, p_, mask, below, &result.ev);
- evaluate_b_group(ctx, p_, mask, below, &result.ev);
- evaluate_c_group(ctx, p_, below, &result.ev);
- }
- // 4) L8:分数 → 硬门槛 → 优先级 → 置信度
- compute_scores(&result.ev);
- const Verdict v = classify(ctx, p_, &result.ev);
- result.state = v.state;
- result.confidence = v.confidence;
- result.ev.diag = v.diag;
- result.ev.reason = v.reason;
- if (edge_trace_on()) {
- std::fprintf(stderr, "verdict: state=%d conf=%.3f reason=%s\n", result.state,
- result.confidence, result.ev.reason.c_str());
- }
- // 5) L9:运动门控 —— 本帧**不改变判定**(§2.3 ③)。
- // 输出 state=255 + hold=true:上层 TemporalVoter 会走"保持上一状态"分支;
- // 连续超时由 decision.hold_s / lost_timeout_s(0.6 s / 1.5 s)兜底,
- // 与 edge.motion_hold_s(1.5 s)取值一致,可直接对照(§6)。
- if (motion) {
- result.ev.hold = true;
- result.state = static_cast<int>(SceneState::UNKNOWN);
- result.confidence = std::min(result.confidence, 0.20);
- result.ev.diag = EdgeDiag::MOTION;
- char buf[160];
- std::snprintf(buf, sizeof(buf),
- "MOTION=1: frame ignored (hold), moving for %.2fs (spec 6)", gate_.held_s());
- result.ev.reason = std::string(buf) + " | " + result.ev.reason;
- }
- // 6) 缓存(日志 / 现场整定 / 调试 dump 用)
- last_ = result.ev;
- segments_ = ctx.segs;
- outline_ = ctx.outline;
- return result;
- }
- // ---------------------------------------------------------------- 运动门控(§6)
- MotionGate::MotionGate(const EdgeParams& params) : p_(params) {}
- void MotionGate::reset() {
- prev_ = GrayImage();
- last_ = GrayImage();
- prev_mean_mag_ = -1.0;
- still_run_ = 0;
- motion_ = false;
- motion_since_ = -1.0;
- held_s_ = 0.0;
- }
- bool MotionGate::update(const GrayImage& gray, double ts) {
- if (!p_.motion_gate || gray.empty()) {
- motion_ = false;
- held_s_ = 0.0;
- motion_since_ = -1.0;
- return false;
- }
- const double mean_mag = sobel(gray).mean_mag();
- // 位移估计统一在 160×90 缩略图上做:与参考帧的缩略图同尺寸才能算投影互相关
- const GrayImage cur = box_downscale(gray, 160, 90);
- bool far = false; ///< 相对**参考帧**(最近静止帧)的累计位移超门限
- bool blurred = false; ///< 相对参考帧的模糊指标超限(§6 ③)
- bool step_still = false; ///< 与上一帧几乎完全一样(帧间无变化)→ 运动结束 / 允许重同步
- constexpr double kStepStillEps = 0.25; // 灰阶:低于它="这一帧与上一帧没有变化"
- constexpr int kStillFrames = 3; // 连续多少帧"无变化"才重同步参考帧(滞回)
- // 帧间变化量 = 行 / 列投影的平均绝对差(灰阶)。只用来判断"画面是否已经不再变化"。
- auto profile_diff = [](const GrayImage& a, const GrayImage& b) -> double {
- double acc = 0.0;
- int n = 0;
- for (int x = 0; x < a.width; ++x) {
- double sa = 0.0;
- double sb = 0.0;
- for (int y = 0; y < a.height; ++y) {
- sa += static_cast<double>(a.at(x, y));
- sb += static_cast<double>(b.at(x, y));
- }
- acc += std::fabs(sa - sb) / static_cast<double>(a.height);
- ++n;
- }
- for (int y = 0; y < a.height; ++y) {
- double sa = 0.0;
- double sb = 0.0;
- for (int x = 0; x < a.width; ++x) {
- sa += static_cast<double>(a.at(x, y));
- sb += static_cast<double>(b.at(x, y));
- }
- acc += std::fabs(sa - sb) / static_cast<double>(a.width);
- ++n;
- }
- return n > 0 ? acc / static_cast<double>(n) : 0.0;
- };
- if (!prev_.empty() && prev_.width == cur.width && prev_.height == cur.height) {
- // ② **累计位移**(当前帧 vs 参考帧 = 最近静止帧):行 / 列投影的一维互相关(SAD 最小)。
- // 为什么是累计而不是"帧间":单帧位移会被缩略图量化抹平(8× 缩略时 6 px 恰好落在
- // 一个像素格内)→ 慢速漂移(3~5 px/帧)永远不报警,而"车辆行走 / 箱体下放"正是慢速
- // 持续位移;按累计口径,位移只要持续累积就必然超门限。
- // 为什么用投影而不是稀疏光流:确定性、无第三方库、对"整幅平移"最敏感。
- const int max_shift = static_cast<int>(p_.motion_shift_max_px * 2.0) + 2;
- // 缩略图 → 原图的换算系数。门限 motion_shift_max_px 是**原图像素**(现场标定口径),
- // 而互相关在 160×90 缩略图上做、估出来的是缩略图像素 → 必须先折算回原图再比较;
- // 否则门限会随缩略倍数漂移(1280×720 是 8 倍 → 6 px 被悄悄放宽成 48 px,整幅平移反而漏检)。
- const double px_per_thumb_x =
- cur.width > 0 ? static_cast<double>(gray.width) / cur.width : 1.0;
- const double px_per_thumb_y =
- cur.height > 0 ? static_cast<double>(gray.height) / cur.height : 1.0;
- // hit_limit = 最优位移落在搜索窗口边界 → 真实位移比窗口还大(必然超门限)。
- auto axis_shift = [&](bool vertical, bool* hit_limit) -> int {
- *hit_limit = false;
- const int len = vertical ? cur.height : cur.width;
- const int cross = vertical ? cur.width : cur.height;
- std::vector<double> a(static_cast<std::size_t>(len), 0.0);
- std::vector<double> b(static_cast<std::size_t>(len), 0.0);
- for (int i = 0; i < len; ++i) {
- double sa = 0.0;
- double sb = 0.0;
- for (int j = 0; j < cross; ++j) {
- const int x = vertical ? j : i;
- const int y = vertical ? i : j;
- sa += static_cast<double>(prev_.at(x, y));
- sb += static_cast<double>(cur.at(x, y));
- }
- a[static_cast<std::size_t>(i)] = sa / static_cast<double>(cross);
- b[static_cast<std::size_t>(i)] = sb / static_cast<double>(cross);
- }
- double sad0 = 0.0;
- for (int i = 0; i < len; ++i) {
- sad0 += std::fabs(a[static_cast<std::size_t>(i)] - b[static_cast<std::size_t>(i)]);
- }
- sad0 /= static_cast<double>(len);
- int best = 0;
- double best_sad = sad0;
- for (int s = -max_shift; s <= max_shift; ++s) {
- if (s == 0) { continue; }
- double sad = 0.0;
- int n = 0;
- for (int i = 0; i < len; ++i) {
- const int k = i + s;
- if (k < 0 || k >= len) { continue; }
- sad += std::fabs(a[static_cast<std::size_t>(i)] -
- b[static_cast<std::size_t>(k)]);
- ++n;
- }
- if (n == 0) { continue; }
- sad /= static_cast<double>(n);
- if (sad < best_sad) {
- best_sad = sad;
- best = s;
- }
- }
- // 只有"明显更优"才认这个位移(否则算噪声抖动 → 视为静止)。三条同时成立才算"真位移":
- // ① 剖面本身有对比(sad0 ≥ 0.10 灰阶)—— 全平剖面(纯天空 / 全黑)不做位移搜索;
- // ② 绝对增益 ≥ 0.10 灰阶 —— 压住"在 28 个候选位移里取最小"带来的噪声假阳性:静止场景的
- // 相邻帧只差噪声,SAD 最小值天然比 s=0 低一点点,只看相对比例会把抖动误判成运动;
- // ③ 相对增益 < 0.90 —— 与规范 §6 ② "明显更优" 同义。
- const double gain = sad0 - best_sad;
- if (sad0 >= 0.10 && gain >= 0.10 && best_sad < 0.90 * sad0) {
- *hit_limit = std::fabs(static_cast<double>(best)) >= max_shift;
- } else {
- best = 0;
- }
- return best;
- };
- bool dx_hit = false;
- bool dy_hit = false;
- const int dx = axis_shift(false, &dx_hit);
- const int dy = axis_shift(true, &dy_hit);
- // 折算回**原图像素**再与门限比较;撞窗口边界同样按"超门限"处理。
- far = dx_hit || dy_hit ||
- std::fabs(static_cast<double>(dx) * px_per_thumb_x) > p_.motion_shift_max_px ||
- std::fabs(static_cast<double>(dy) * px_per_thumb_y) > p_.motion_shift_max_px;
- // ③ 运动模糊:梯度均值相对参考帧基线明显下降(§6 ③)
- if (prev_mean_mag_ > 1e-6) { blurred = mean_mag < p_.motion_blur_ratio * prev_mean_mag_; }
- // ④ 帧间已无变化?—— 运动**结束**的出口。若运动结束后仍拿旧参考帧比对,累计位移会永远
- // 超门限 → 永久锁死在 MOTION;所以另设"连续 kStillFrames 帧帧间无变化 → 重同步参考帧"。
- if (!last_.empty() && last_.width == cur.width && last_.height == cur.height) {
- step_still = profile_diff(last_, cur) < kStepStillEps;
- }
- }
- motion_ = far || blurred;
- if (motion_) {
- if (motion_since_ < 0.0) { motion_since_ = ts; }
- held_s_ = (ts > motion_since_) ? (ts - motion_since_) : 0.0;
- still_run_ = 0; // 运动中不重同步:位移要继续累积(慢速漂移迟早超门限)
- } else {
- motion_since_ = -1.0;
- held_s_ = 0.0;
- still_run_ = step_still ? (still_run_ + 1) : 0;
- if (prev_.empty() || still_run_ >= kStillFrames) {
- prev_ = cur; // 画面确实不再变化 → 参考帧挪过来(此后每帧都重同步,回到"逐帧"灵敏度)
- prev_mean_mag_ = mean_mag;
- }
- }
- // 只保留一张 160×90 参考帧 + 一张上一帧:投影统计够用,内存占用可忽略
- last_ = cur;
- return motion_;
- }
- // ---------------------------------------------------------------- 公共小函数
- const char* edge_diag_label(EdgeDiag diag) {
- switch (diag) {
- case EdgeDiag::NONE: return "none";
- case EdgeDiag::NO_BOX: return "no_box";
- case EdgeDiag::VIEW_LIMITED: return "view_limited";
- case EdgeDiag::SCALE_FAIL: return "scale_fail";
- case EdgeDiag::CONFLICT: return "conflict";
- case EdgeDiag::MOTION: return "motion";
- }
- return "none";
- }
- const char* evidence_key_name(EvidenceKey key) {
- switch (key) {
- case EvidenceKey::P1: return "P1";
- case EvidenceKey::P2: return "P2";
- case EvidenceKey::P3: return "P3";
- case EvidenceKey::P4: return "P4";
- case EvidenceKey::F1: return "F1";
- case EvidenceKey::F2: return "F2";
- case EvidenceKey::F3: return "F3";
- case EvidenceKey::F4: return "F4";
- case EvidenceKey::G1: return "G1";
- case EvidenceKey::G2: return "G2";
- case EvidenceKey::G3: return "G3";
- case EvidenceKey::C1: return "C1";
- case EvidenceKey::C2: return "C2";
- case EvidenceKey::C3: return "C3";
- case EvidenceKey::COUNT: break;
- }
- return "?";
- }
- std::vector<PointF> BoxOutline::polygon() const {
- // 顺序:近端上角 → 远端上角 → 远端下角 → 近端下角(凸四边形,射线法判内外即可)
- return {near_top, far_top, far_bottom, near_bottom};
- }
- std::string EdgeResult::evidence_summary() const {
- std::string hits;
- for (int i = 0; i < static_cast<int>(EvidenceKey::COUNT); ++i) {
- if (ev.hit[i]) {
- hits += evidence_key_name(static_cast<EvidenceKey>(i));
- hits += " ";
- }
- }
- if (hits.empty()) { hits = "- "; }
- char buf[320];
- std::snprintf(buf, sizeof(buf),
- "[%s] sA=%.1f sB=%.1f sC=%.1f q=%.2f near=%.0fpx %.1fpx/m out=%.0f/%.0f "
- "segs=%d ground=%.2f held=%.2fs diag=%s",
- hits.c_str(), ev.score_a, ev.score_b, ev.score_c, ev.outline_quality, ev.box_h_px,
- ev.px_per_m, ev.out_left_px, ev.out_right_px, ev.segments_total,
- ev.ground_ratio_full, ev.motion_held_s, edge_diag_label(ev.diag));
- return std::string(buf);
- }
- Observation EdgeResult::to_observation(double ts, long frame_id) const {
- Observation obs;
- obs.ts = ts;
- obs.state = state;
- obs.confidence = confidence;
- obs.reason = evidence_summary();
- obs.frame_id = frame_id;
- return obs;
- }
- // ---------------------------------------------------------------- 证据 → 检测框(接口适配)
- std::vector<Box> EdgeEvidence::to_boxes(const EdgeResult& result) const {
- std::vector<Box> boxes;
- if (!outline_.ok) { return boxes; }
- const std::vector<PointF> poly = outline_.polygon();
- double x1 = poly[0].first;
- double x2 = poly[0].first;
- double y1 = poly[0].second;
- double y2 = poly[0].second;
- for (const PointF& p : poly) {
- x1 = std::min(x1, p.first);
- x2 = std::max(x2, p.first);
- y1 = std::min(y1, p.second);
- y2 = std::max(y2, p.second);
- }
- // ① 箱体框(class = container):供 scene.py 的几何关联(support_overlap 等)继续使用
- boxes.push_back(Box(static_cast<float>(x1), static_cast<float>(y1), static_cast<float>(x2),
- static_cast<float>(y2), static_cast<float>(outline_.quality), 0, "container"));
- // ② 车型框(class = bed / flatbed):框住"箱底以下 + 两侧越界带"的车体区域。
- // 注意:这里给出的是**证据结论**(硬门槛 + 弃权之后),而不是模型的类别概率;
- // score 直接取归一化证据分,便于上层日志与人工复核对齐。
- if (result.state == static_cast<int>(SceneState::BED) ||
- result.state == static_cast<int>(SceneState::FLATBED)) {
- const double box_h = outline_.near_bottom.second - outline_.near_top.second; // >0
- const double wide = 0.35 * (x2 - x1);
- const double body_x1 = std::max(0.0, x1 - wide);
- const double body_x2 = x2 + wide;
- const double body_y1 = outline_.near_bottom.second;
- const double body_y2 = body_y1 + 1.40 * box_h;
- const char* name = result.state == static_cast<int>(SceneState::BED) ? "bed" : "flatbed";
- const double raw = result.state == static_cast<int>(SceneState::BED)
- ? result.ev.score_a / 3.3
- : result.ev.score_b / 3.2;
- boxes.push_back(Box(static_cast<float>(body_x1), static_cast<float>(body_y1),
- static_cast<float>(body_x2), static_cast<float>(body_y2),
- static_cast<float>(raw * outline_.quality), result.state, name));
- }
- return boxes;
- }
- void EdgeEvidence::note_window(bool t1_window, const EdgeResult& result) {
- if (!t1_window) { return; }
- last_t1_ = result;
- has_t1_ = true;
- }
- // ---------------------------------------------------------------- Detector 适配器(§10)
- EdgeEvidenceDetector::EdgeEvidenceDetector(const EdgeParams& params, const LineParams& lines)
- : evidence_(params, lines) {}
- std::vector<Box> EdgeEvidenceDetector::infer(const Frame& frame) {
- if (frame.gray == nullptr) {
- last_result_ = EdgeResult();
- last_result_.ev.diag = EdgeDiag::NO_BOX;
- last_result_.ev.reason = "edge backend: Frame.gray == nullptr (取帧侧未填灰度图)";
- return {};
- }
- last_result_ = evidence_.analyze(*frame.gray, frame.ts);
- return evidence_.to_boxes(last_result_);
- }
- bool EdgeEvidenceDetector::warmup(std::string* error) {
- if (error != nullptr) { error->clear(); }
- return true; // 无模型、无引擎:不需要预热(首次 analyze 会分配工作缓冲)
- }
- } // namespace portcv
|