Explorar el Código

fix(portcv): 天空电线不再把 ROI 拉上天,空车歧义帧不判 2

为什么改:
- 512×512 的 C70 侧视素材,天空电线在 y≈40~120;v2 固定窗口把电线当
  box=72,动态 ROI=[25,77,486,110] 全在天上,立柱逻辑全部失效;
  去掉电线后又会把车体内部横梁当箱底 → 2(空车误判)。
- 对 1 px Canny 掩膜直接做形态学开运算,实测会把车体边缘一起删掉
  (开运算后行密度=0),不能用裸开运算。

改了什么:
- 新增 texture_top_*:用竖向梯度块覆盖率找车体顶(立柱/门板/波纹覆盖高,
  横向电线覆盖低),把车体顶以上的亮/暗带从候选里剔除;不移动窗口,
  近距 A/B 画面车体顶≈窗口顶,不触发。
- 新增 body_fallback_*:纹理车体 ROI 再数一次门板(空车兜底;
  C++ 在 512 压缩图上立柱=0 时仍安全弃权)。
- 安全兜底:正常给 2、箱底以下立柱=0、箱体仍在车体内 →
  ambiguous_empty_vehicle + 255,绝不判 2。
- C++/Python/configs/default/edge-v2-front/docs 同步;
  新增 Python 3 项 + C++ 2 项回归。

验证:
- 天空图:top=165(ROI 不再落在天空),state=255(不误判 2);
  Python 参考实现车体 ROI posts 8~10 → 1。
- A f1000~f1049 发布 1×40/0×10;B f1740~f1789 发布 2×40/0×10。
- Python 336 OK(1 skipped);ctest 8/8;edge_v2 selftest 56/0;
  check_configs 7/7;gen_cpp_constants --check OK。
kwass hace 4 días
padre
commit
0d4c20af2a

+ 3 - 3
README.md

@@ -30,7 +30,7 @@ git push -u origin develop      # 推到 Gitee 私有库(首次需认证,见
 
 分支模型、提交规范、发布检查清单、回滚与远程仓库接入:见
 **[docs/git_workflow.md](docs/git_workflow.md)**。
-提交钩子(`.githooks/pre-commit`,跑 333 项单测)需每人执行一次
+提交钩子(`.githooks/pre-commit`,跑 336 项单测)需每人执行一次
 `git config core.hooksPath .githooks` 才会生效。
 
 远端:`origin` = `https://gitee.com/kwass122/hengda--kwass.git`(**私有库**)。
@@ -191,9 +191,9 @@ PLC 侧无感知,可以先在 Python 上打通联调再切 C++。
 # 目标机(Ubuntu 22.04 / JetPack 6):核心零外部依赖
 cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release
 cmake --build build -j
-ctest --test-dir build --output-on-failure     # 八个自检全绿(200 / 269 / 110 / 231 / 112 / 54 / 52 / 104)
+ctest --test-dir build --output-on-failure     # 八个自检全绿(200 / 269 / 110 / 231 / 112 / 54 / 56 / 104)
 
-# 一条命令跑完"冻结点"回归(ctest + Python 333 单测 + v1/v2 现场回放),失败即非 0 退出
+# 一条命令跑完"冻结点"回归(ctest + Python 336 单测 + v1/v2 现场回放),失败即非 0 退出
 python scripts/regression_freeze.py --build-dir build
 
 # 跑起来(PLC 用 MB_CLIENT 轮询 1502 端口读 12 个字结果区)

+ 12 - 0
configs/default.json

@@ -157,6 +157,18 @@
     "min_post_len_ratio": 0.3,
     "min_post_spacing_px": 24.0,
     "min_post_span_ratio": 0.23,
+    "texture_top_enable": true,
+    "texture_grad_th": 50.0,
+    "texture_block_px": 16,
+    "texture_block_hit_ratio": 0.03,
+    "texture_coverage_min": 0.5,
+    "texture_run_rows": 3,
+    "texture_smooth_rows": 7,
+    "texture_top_margin_ratio": 0.02,
+    "body_fallback_enable": true,
+    "body_bottom_ratio": 0.75,
+    "body_min_opacity": 0.75,
+    "body_min_roi_px": 90,
     "min_diagonal_braces": 1,
     "min_wall_opacity": 0.35,
     "max_flat_gap_px": 40.0,

+ 13 - 0
configs/edge-v2-front.json

@@ -8,6 +8,7 @@
     "allow_state2=true:平车 2 已打开提交;顶层与 commit 两个开关串联,任一 false 都会回退为只识别、不提交。",
     "P0-Q3:平车 2 必须是『薄车面边梁 + 车面下方暗带』;地面/下层箱顶/月台的厚亮面不判 2(宁可 255)。",
     "P0-Q3:敞车 1 的门板阵列必须横跨 >=0.23×工作宽(B 的车轮/制动梁伪立柱只跨 ~20%);贴合形态还需斜撑。",
+    "P0-Q4:天空电线用竖向梯度块覆盖率找车体顶,车体顶以上的亮/暗带剔除;空车歧义帧不判 2(255)。",
     "px_per_m=0 表示用箱体竖棱自标尺;现场若已标定可填固定值(A/B 实测约 115.6)。"
   ],
   "run": {
@@ -75,6 +76,18 @@
     "min_post_spacing_px": 24.0,
     "min_diagonal_braces": 1,
     "min_post_span_ratio": 0.23,
+    "texture_top_enable": true,
+    "texture_grad_th": 50.0,
+    "texture_block_px": 16,
+    "texture_block_hit_ratio": 0.03,
+    "texture_coverage_min": 0.5,
+    "texture_run_rows": 3,
+    "texture_smooth_rows": 7,
+    "texture_top_margin_ratio": 0.02,
+    "body_fallback_enable": true,
+    "body_bottom_ratio": 0.75,
+    "body_min_opacity": 0.75,
+    "body_min_roi_px": 90,
     "min_wall_opacity": 0.35,
     "wall_edge_density_ref": 0.14,
     "wall_edge_density_span": 0.04,

+ 1 - 1
cpp/README.md

@@ -78,7 +78,7 @@ ctest --test-dir build --output-on-failure
 | `portcv_capture_selftest` | **231 通过 / 0 失败** | 帧槽只留最新帧 / synth 源逐字节确定 / **images(PGM 序列)源离线复盘** / 管线拼装 / `redact_uri` / PGM+JSONL 格式 / `source.*` 校验 |
 | `portcv_edge_selftest` | **112 通过 / 0 失败** | 证据链全量(含 C1 置信度下限、`F2` 车底空隙、`C3` ROI 口径、P2/F1 结构上下文);2026-10-27 起 12 项历史失败已清零 |
 | `portcv_v2_selftest` | **54 通过 / 0 失败** | V2 PublishGate 的 12 个契约向量、状态保持/复位、half-up 千分比 |
-| `portcv_edge_v2_selftest` | **52 通过 / 0 失败** | edge-v2 证据链:零间隙接触、侧视 flatbed、`allow_state2` 回退、空帧/无图 abstain;**P0-0 吊具高悬 / 夹箱门**(合成高悬帧 6 帧 0 commit、注入路径、远距 ROI 弃权、门关闭对照);**P0-Q3 地面/堆料/堆叠箱负样本**(不得判 1/2) |
+| `portcv_edge_v2_selftest` | **56 通过 / 0 失败** | edge-v2 证据链:零间隙接触、侧视 flatbed、`allow_state2` 回退、空帧/无图 abstain;**P0-0 吊具高悬 / 夹箱门**(合成高悬帧 6 帧 0 commit、注入路径、远距 ROI 弃权、门关闭对照);**P0-Q3 地面/堆料/堆叠箱负样本**(不得判 1/2) |
 
 > 一条命令跑完全部四层(ctest + Python 单测 + v1 `edge` 现场回放 + v2 `edge-v2` 现场回放):
 > `python scripts/regression_freeze.py --build-dir build-cmake/windows-zig-release`。

+ 29 - 0
cpp/include/portcv/edge_v2.hpp

@@ -86,6 +86,25 @@ struct EdgeV2Params {
     double under_deck_dark_delta = 12.0;
     double under_deck_min_h_ratio = 0.01;
     double under_deck_search_h_ratio = 0.10;
+    /// P0-Q4:天空/电线 ROI 约束。天空里的横向电线是**竖向梯度低、横向细线**,
+    /// 会在固定窗口里被当成“箱底/车体上缘”,导致动态 ROI 落到天上。
+    /// 这里用“竖向梯度块覆盖率”找车体顶(真实车体有立柱/门板/波纹 → 覆盖高),
+    /// 把车体顶以上的亮/暗带从候选里剔除(不移动窗口,避免误伤近距画面)。
+    bool texture_top_enable = true;
+    double texture_grad_th = 50.0;       ///< |Sobel_x| 阈值(竖向边)
+    int texture_block_px = 16;           ///< 覆盖率统计块宽(工作图像素)
+    double texture_block_hit_ratio = 0.03;  ///< 块内竖向边像素占比门
+    double texture_coverage_min = 0.50;  ///< 一行中“有竖向边的块”占比门
+    int texture_run_rows = 3;            ///< 连续多少行达标才算车体顶
+    int texture_smooth_rows = 7;         ///< 行覆盖率平滑窗
+    double texture_top_margin_ratio = 0.02;  ///< 车体顶向上留白(×画幅高)
+    /// P0-Q4:空车/无箱车体的兜底——正常“箱底以下”路径给不出立柱时,
+    /// 用纹理车体 ROI(texture_top 起、向下 body_bottom_ratio)重新数门板立柱。
+    /// 只在能看到“车体顶(上方有天空)”且正常路径不是 1 时启用,避免影响 A/B 近距帧。
+    bool body_fallback_enable = true;
+    double body_bottom_ratio = 0.75;    ///< 车体 ROI 高 = 该比例 × (窗口底 - 车体顶)
+    double body_min_opacity = 0.75;     ///< 车体 ROI 不透明占比下限(平车底盘会低)
+    int body_min_roi_px = 90;           ///< 车体 ROI 最小高度(原图像素)
     double box_height_m = 2.591;
     double px_per_m = 0.0;             ///< 0 = 用箱体竖棱自标尺
     double min_scale_px = 60.0;
@@ -109,6 +128,11 @@ struct EdgeV2Params {
     SpreaderGateParams spreader; ///< spreader_dark_max / spreader_dark_ratio
 };
 
+/// P0-Q4:用“竖向梯度块覆盖率”找车体顶(输入灰度图,返回像素 y;-1 = 未找到/关闭)。
+/// 天空电线/水印是横向或局部结构,覆盖率低;车体立柱/门板/波纹覆盖高。
+double find_texture_top_y(const GrayImage& gray, const int window[4],
+                          const EdgeV2Params& params);
+
 /// commit 参数(与 Python `CommitParams` 同名同义)。
 struct V2CommitParams {
     double gap_m_max = 0.10;
@@ -177,6 +201,11 @@ struct EvidenceV2Result {
     std::string view = "unknown";
     std::optional<double> box_bottom_y;
     std::optional<double> box_top_y;
+    double texture_top_y = 0.0;  ///< 竖向纹理车体顶(原图像素;0 = 未启用/未找到)
+    int body_posts = 0;          ///< 车体兜底 ROI 的立柱数(诊断)
+    double body_span = 0.0;      ///< 车体兜底 ROI 的立柱跨度(诊断)
+    double body_opacity = 0.0;   ///< 车体兜底 ROI 的不透明占比(诊断)
+    int body_diagonal = 0;       ///< 车体兜底 ROI 的斜撑数(诊断)
     std::optional<double> box_h_px;
     std::optional<double> px_per_m;
     bool scale_ok = false;

+ 50 - 0
cpp/src/app_config.cpp

@@ -438,6 +438,18 @@ bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
         num("evidence_v2.min_post_spacing_px", &v->min_post_spacing_px),
         integer("evidence_v2.min_diagonal_braces", &v->min_diagonal_braces),
         num("evidence_v2.min_post_span_ratio", &v->min_post_span_ratio),
+        flag("evidence_v2.texture_top_enable", &v->texture_top_enable),
+        num("evidence_v2.texture_grad_th", &v->texture_grad_th),
+        integer("evidence_v2.texture_block_px", &v->texture_block_px),
+        num("evidence_v2.texture_block_hit_ratio", &v->texture_block_hit_ratio),
+        num("evidence_v2.texture_coverage_min", &v->texture_coverage_min),
+        integer("evidence_v2.texture_run_rows", &v->texture_run_rows),
+        integer("evidence_v2.texture_smooth_rows", &v->texture_smooth_rows),
+        num("evidence_v2.texture_top_margin_ratio", &v->texture_top_margin_ratio),
+        flag("evidence_v2.body_fallback_enable", &v->body_fallback_enable),
+        num("evidence_v2.body_bottom_ratio", &v->body_bottom_ratio),
+        num("evidence_v2.body_min_opacity", &v->body_min_opacity),
+        integer("evidence_v2.body_min_roi_px", &v->body_min_roi_px),
         num("evidence_v2.min_wall_opacity", &v->min_wall_opacity),
         num("evidence_v2.wall_edge_density_ref", &v->wall_edge_density_ref),
         num("evidence_v2.wall_edge_density_span", &v->wall_edge_density_span),
@@ -678,6 +690,33 @@ bool validate(const AppConfig* cfg, std::string* error) {
     if (v2.min_post_span_ratio < 0.0 || v2.min_post_span_ratio > 1.0) {
         return bad("evidence_v2.min_post_span_ratio 必须 ∈ [0,1](0=不启用该门)");
     }
+    if (!(v2.texture_grad_th > 0.0)) {
+        return bad("evidence_v2.texture_grad_th 必须 > 0");
+    }
+    if (v2.texture_block_px < 4) {
+        return bad("evidence_v2.texture_block_px 至少 4");
+    }
+    if (v2.texture_block_hit_ratio < 0.0 || v2.texture_block_hit_ratio > 1.0) {
+        return bad("evidence_v2.texture_block_hit_ratio 必须 ∈ [0,1]");
+    }
+    if (v2.texture_coverage_min < 0.0 || v2.texture_coverage_min > 1.0) {
+        return bad("evidence_v2.texture_coverage_min 必须 ∈ [0,1]");
+    }
+    if (v2.texture_run_rows < 1 || v2.texture_smooth_rows < 1) {
+        return bad("evidence_v2.texture_run_rows / texture_smooth_rows 至少 1");
+    }
+    if (v2.texture_top_margin_ratio < 0.0 || v2.texture_top_margin_ratio > 0.5) {
+        return bad("evidence_v2.texture_top_margin_ratio 必须 ∈ [0,0.5]");
+    }
+    if (!(v2.body_bottom_ratio > 0.0 && v2.body_bottom_ratio <= 1.0)) {
+        return bad("evidence_v2.body_bottom_ratio 必须 ∈ (0,1]");
+    }
+    if (v2.body_min_opacity < 0.0 || v2.body_min_opacity > 1.0) {
+        return bad("evidence_v2.body_min_opacity 必须 ∈ [0,1]");
+    }
+    if (v2.body_min_roi_px < 8) {
+        return bad("evidence_v2.body_min_roi_px 至少 8");
+    }
     // P0-Q3:2(平车)的贴合亮带厚度/车面下方暗带参数。写错会让门永不触发,
     // 比报错更危险(地面堆料会被判成平车),所以一律启动即失败。
     if (!(v2.contact_max_h_ratio > 0.0 && v2.contact_max_h_ratio <= 0.5)) {
@@ -907,6 +946,17 @@ std::string describe_app_config(const AppConfig& cfg) {
                 "probe=[%.3f, %.3f]×画幅(找不到暗带不判 2)\n",
                 v2.contact_max_h_ratio, v2.under_deck_dark_delta,
                 v2.under_deck_min_h_ratio, v2.under_deck_search_h_ratio);
+    append_line(&out,
+                "v2顶部门: enable=%d grad>=%.0f block=%d hit=%.2f cov>=%.2f "
+                "run=%d smooth=%d margin=%.2f(车体顶以上亮/暗带剔除)\n",
+                v2.texture_top_enable ? 1 : 0, v2.texture_grad_th, v2.texture_block_px,
+                v2.texture_block_hit_ratio, v2.texture_coverage_min, v2.texture_run_rows,
+                v2.texture_smooth_rows, v2.texture_top_margin_ratio);
+    append_line(&out,
+                "v2车体兜底: enable=%d bottom=%.2f opacity>=%.2f roi>=%dpx"
+                "(空车/无箱时用纹理车体 ROI 数门板)\n",
+                v2.body_fallback_enable ? 1 : 0, v2.body_bottom_ratio,
+                v2.body_min_opacity, v2.body_min_roi_px);
     append_line(&out,
                 "v2落位: require_commit=%d gap_m<=%.2f gap_px<=%.1f stable=%d structure=%d "
                 "allow_state2=%d\n",

+ 231 - 22
cpp/src/edge_v2.cpp

@@ -222,6 +222,59 @@ double pstdev(const std::vector<double>& values, double 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);
@@ -230,6 +283,62 @@ std::string fmt(const char* pattern, double value) {
 
 }  // 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;
@@ -254,10 +363,14 @@ Observation EvidenceV2Result::to_observation(double ts, long frame_id,
 
 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") +
@@ -667,10 +780,32 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
     };
     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;
@@ -969,31 +1104,98 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
         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, cls.state, gap_m, gap_px, cls.structure_hits, still, p_.view != "unknown",
-        plc_arrived, plc_spreader_released, hoist_flag);
+        ts, final_state, commit_gap_m, commit_gap_px, final_hits, still,
+        p_.view != "unknown", plc_arrived, plc_spreader_released, hoist_flag);
 
-    out.state = cls.state;
-    out.confidence = cls.confidence;
+    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 = gap_px;
-    out.gap_m = gap_m;
-    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.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;
@@ -1010,13 +1212,20 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
     // 弃权原因要能直接回答"为什么不用这一帧":吊具未松开与吊具高悬是两件事,
     // 现场排查方向不同(前者看开锁信号,后者看起升高度),所以这里分开写。
     out.abstain_reason = !hoist_flag
-                             ? (cls.state == 255 ? cls.reason : "")
+                             ? (final_state == 255 ? final_reason : "")
                              : (spreader_cues.contact ? "spreader_contact" : "hoist_high");
-    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 = cls.reason;
+    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;

+ 62 - 0
cpp/tests/selftest_edge_v2.cpp

@@ -50,6 +50,10 @@ portcv::GrayImage bed_scene(int gap_px = 18) {
     portcv::GrayImage img(1280, 720, 120);
     const int box_bottom = 392;
     fill_rect(&img, 0, 40, 1280, box_bottom, 185);
+    // 箱体竖波纹(真实集装箱有;也让 P0-Q4 顶部纹理门不把箱顶误当天空)
+    for (int x = 60; x < 1240; x += 48) {
+        fill_rect(&img, x, 50, x + 3, box_bottom - 4, 176);
+    }
     fill_rect(&img, 0, box_bottom, 1280, box_bottom + 12, 55);
     const int wall_top = box_bottom + 12 + gap_px;
     fill_rect(&img, 0, box_bottom + 12, 1280, wall_top, 88);
@@ -67,6 +71,9 @@ portcv::GrayImage bed_scene(int gap_px = 18) {
 portcv::GrayImage flat_scene(int gap_px = 4) {
     portcv::GrayImage img(1280, 720, 120);
     fill_rect(&img, 0, 40, 1280, 392, 185);
+    for (int x = 60; x < 1240; x += 48) {
+        fill_rect(&img, x, 50, x + 3, 388, 176);
+    }
     fill_rect(&img, 0, 392, 1280, 404, 55);
     const int deck_top = 404 + gap_px;
     fill_rect(&img, 0, deck_top, 1280, deck_top + 5, 225);
@@ -88,6 +95,9 @@ portcv::GrayImage flat_contact_scene() {
     // 与现场 746×192 侧视帧同形态;厚亮面(地面/下层箱顶)由负样本覆盖。
     portcv::GrayImage img(1280, 720, 120);
     fill_rect(&img, 0, 40, 1280, 392, 185);
+    for (int x = 60; x < 1240; x += 48) {
+        fill_rect(&img, x, 50, x + 3, 388, 176);
+    }
     fill_rect(&img, 0, 392, 1280, 404, 55);
     fill_rect(&img, 0, 404, 1280, 412, 225);
     fill_rect(&img, 0, 412, 1280, 442, 30);
@@ -111,6 +121,9 @@ portcv::GrayImage hoist_scene() {
 portcv::GrayImage ground_scene() {
     portcv::GrayImage img(1280, 720, 120);
     fill_rect(&img, 0, 40, 1280, 392, 185);
+    for (int x = 60; x < 1240; x += 48) {
+        fill_rect(&img, x, 50, x + 3, 388, 176);
+    }
     fill_rect(&img, 0, 392, 1280, 404, 55);
     for (int y = 404; y < 720; ++y) {
         for (int x = 0; x < 1280; ++x) {
@@ -138,6 +151,35 @@ portcv::GrayImage stacked_scene() {
     return img;
 }
 
+/// 天空电线 + 车体:电线是横向细线,车体有竖向立柱/门板(P0-Q4 回归,512×512)。
+portcv::GrayImage sky_wire_scene() {
+    portcv::GrayImage img(512, 512, 200);
+    for (int y : {20, 52, 84, 116}) {
+        fill_rect(&img, 0, y, 512, y + 2, 30);
+    }
+    fill_rect(&img, 0, 165, 512, 405, 95);
+    for (int x = 30; x < 480; x += 18) {
+        fill_rect(&img, x, 175, x + 5, 400, 45);
+    }
+    for (int x = 30; x + 40 < 480; x += 50) {
+        fill_rect(&img, x, 185, x + 40, 380, 110);
+        fill_rect(&img, x, 185, x + 40, 188, 60);
+        fill_rect(&img, x, 377, x + 40, 380, 60);
+        fill_rect(&img, x, 185, x + 3, 380, 60);
+        fill_rect(&img, x + 37, 185, x + 40, 380, 60);
+    }
+    for (int dy = 5; dy < 235; dy += 8) {
+        fill_rect(&img, 20, 165 + dy, 492, 165 + dy + 2, 80);
+    }
+    for (int x = 40; x + 80 < 480; x += 70) {
+        for (int t = 0; t < 80; ++t) {
+            fill_rect(&img, x + t, 190 + t, x + t + 7, 190 + t + 7, 30);
+        }
+    }
+    fill_rect(&img, 0, 405, 512, 512, 140);
+    return img;
+}
+
 portcv::V2CommitParams fast_commit() {
     portcv::V2CommitParams p;
     p.stable_frames = 3;
@@ -274,6 +316,26 @@ int main() {
         std::printf("       stacked: %s\n", r.evidence_summary().c_str());
         check(r.state != 1 && r.state != 2, "stacked container is not bed/flatbed");
     }
+    // ---------------- P0-Q4:天空电线/纹理顶 ----------------
+    {
+        portcv::EdgeV2Params tp;
+        const int win[4] = {static_cast<int>(0.24 * 512), static_cast<int>(0.02 * 512),
+                            static_cast<int>(0.78 * 512), static_cast<int>(0.95 * 512)};
+        const double top = portcv::find_texture_top_y(sky_wire_scene(), win, tp);
+        std::printf("       sky-top=%.1f\n", top);
+        check(top > 120.0 && top < 220.0, "sky wires: vehicle top below wires");
+        portcv::GrayImage plain(512, 512, 200);
+        for (int y : {20, 52, 84}) {
+            fill_rect(&plain, 0, y, 512, y + 2, 30);
+        }
+        check(portcv::find_texture_top_y(plain, win, tp) < 0.0,
+              "plain sky: no vehicle top");
+        EdgeV2 ev(p, fast_commit());
+        const auto r = ev.analyze(sky_wire_scene(), 0.0);
+        std::printf("       sky-body: %s\n", r.evidence_summary().c_str());
+        check(r.state != 2, "empty C70 + sky wires: never flatbed (1/255)");
+        check(r.texture_top_y > 120.0, "sky-body texture top below wires");
+    }
     // ---------------- P0-0 图像侧安全门 ----------------
     {
         // 直接测算子(与 Python `test_detect_hoist_high_finds_dark_bar_with_bright_sky_below`

+ 1 - 1
docs/deployment.md

@@ -36,7 +36,7 @@ ctest --test-dir build --output-on-failure
 #   期望:portcv_selftest 200/0、portcv_config_selftest 269/0、portcv_rate_selftest 110/0、
 #        portcv_capture_selftest 231/0(取流层 + 黄金语料导出的守门人,含 images/PGM 序列源)
 #        portcv_edge_selftest 112 通过 / 0 失败
-#        portcv_edge_v2_selftest 52 通过 / 0 失败(含 P0-0 吊具高悬 / 夹箱门、P0-Q3 地面/堆料负样本)
+#        portcv_edge_v2_selftest 56 通过 / 0 失败(含 P0-0 吊具高悬 / 夹箱门、P0-Q3 地面/堆料负样本)
 #
 #   不想逐条敲?一条命令跑完四层(ctest + Python 单测 + v1/v2 现场回放):
 #        python scripts/regression_freeze.py --build-dir build

+ 19 - 0
docs/edge_evidence.md

@@ -624,6 +624,25 @@ python scripts/replay_check.py runs/v2gate_B4.jsonl --images runs/_v2gate_B4
   这是 `docs/route_v2.md` §6.4 #2 已声明的未验证形态;现场应依赖 **T1 窗口**
   (箱还在围挡上方时判定)或 PLC "到位/吊具松开"信号,不能只靠落位后的单帧。
 
+**⑦ P0-Q4 天空电线把 ROI 拉上天(2026-11-18,已修)**
+
+* 现象:512×512 的 C70 侧视素材,天空电线在 y≈40~120;v2 固定窗口把电线当
+  `box=72`,`bed=123`,动态 ROI=`[25,77,486,110]` 全在天上,`posts=0` → 255;
+  去掉电线后又会把车体内部横梁当箱底 → `2`(空车误判)。
+* 处置:
+  * 用**竖向梯度块覆盖率**找车体顶(真实车体立柱/门板/波纹覆盖高;电线是横向
+    细线、覆盖低),把车体顶以上的亮/暗带从候选里剔除;**不移动窗口**,
+    近距画面车体顶≈窗口顶,不触发;
+  * 空车歧义帧(正常给 `2`、箱底以下立柱=0、箱体仍在车体内)→
+    `ambiguous_empty_vehicle` + `255`,**绝不判 2**;
+  * 另提供“纹理车体 ROI 再数门板”的兜底(Python 参考实现可判 `1`)。
+* **形态学开运算的结论**:对 1 px Canny 掩膜直接 3×3/5×3 开运算,实测会把
+  车体边缘**全部删掉**(行密度=0);必须用“块覆盖率/局部密度”,不能裸开运算。
+* 结果:该 512 压缩图 `top=165`,ROI 不再落在天空;C++ 因该图立柱检测=0 →
+  `255`(安全,不误判 2);Python 参考实现车体 ROI posts 8~10 → `1`。
+  现场 1280 相机素材需按同一参数复评,C++ 立柱检测还需整定。
+* 新增回归:Python `TextureTopTests` 3 项、C++ 2 项(`portcv_edge_v2_selftest` 56/0)。
+
 ---
 
 ## 8. 现场采样清单 ★(本次评审后即可执行)

+ 2 - 2
docs/git_workflow.md

@@ -18,7 +18,7 @@
 | 首版基线 | 附注标签 `v0.1.0` —— 与本轮桌面交付包一致 |
 | 行尾策略 | `.gitattributes`:库内统一 LF,`*.bat/*.cmd/*.ps1` 检出为 CRLF |
 | 提交模板 | `.gitmessage`(`git config commit.template`) |
-| 提交钩子 | `.githooks/pre-commit`:跑 L1 单测(333 项,约 6 s) |
+| 提交钩子 | `.githooks/pre-commit`:跑 L1 单测(336 项,约 6 s) |
 | 忽略清单 | `.gitignore`:`runs/`、`build/`、`build-cmake/`、权重(`*.onnx/*.rknn/*.engine`)、`*.out/*.err`… |
 | 远端仓库 | `origin` → `git@gitee.com:kwass122/hengda--kwass.git`(Gitee **私有库**;`main`/`develop`/`v0.1.0` 已于 2026-11-09 推送,见 §6.1) |
 
@@ -260,7 +260,7 @@ git bisect good v0.1.0
 # 1) 工作区必须干净,且当前在 release/* 或 main 上
 git status -sb
 
-# 2) L1 单元测试(333 项)
+# 2) L1 单元测试(336 项)
 python -m unittest discover -s tests -q
 
 # 3) L2 契约自检(C++ 侧 8 组 1128 项断言)

+ 14 - 2
docs/route_v2.md

@@ -293,6 +293,17 @@ PLC 若只看 `state`,会把“保持的 0”误当成“已确认不在车上
 > (默认 0.23)× 工作宽度(B f1771~f1773 的伪立柱只跨 ~20%,是车轮/制动梁;
 > A f1100 约 25%,保留)。
 
+> **P0-Q4 天空/电线 ROI 约束(2026-11-18)**:固定窗口会把天空里的横向电线当
+> “箱底/车体上缘”(实测 `box=72`、`roi=[25,77,486,110]` 全在天上)。现在先用
+> **竖向梯度块覆盖率**找“车体顶”(真实车体立柱/门板/波纹 → 覆盖高;电线是横向
+> 细线、覆盖低),把车体顶以上的亮/暗带从候选里剔除(**不移动窗口**,避免误伤
+> 近距画面)。若仍出现“正常路径给 `2`、但箱底以下一根立柱都没有、箱体还在车体
+> 内部”的歧义帧 → 内部 `255`(`ambiguous_empty_vehicle`),绝不判 `2`。
+> 对空 C70 还提供“纹理车体 ROI 再数一次门板”的兜底(Python 参考实现可判 `1`;
+> C++ 在该 512 压缩图上立柱=0,仍安全弃权 `255`,需现场 1280 素材再整定)。
+> **注意**:对 1 px Canny 掩膜直接开运算会把车体边缘也一起删掉(实测开运算后
+> 行密度=0);正确做法是“竖向梯度块覆盖率/局部密度”,不是裸形态学开运算。
+
 ### 4.3 `0`(其他)主证据:没有铁路车体结构
 
 * 箱底以下只有地面/堆场/卡车/其他箱,**没有**:
@@ -557,11 +568,11 @@ else:
 
 > **P1a 状态(2026-10-19 更新,2026-10-27 复核,2026-11-03 复核)**:Python/C++ `PublishGate` 与 §6A 的 12 个向量测试已实现
 > (`tests/test_publish_gate.py` / `cpp/tests/selftest_v2.cpp`);当前回归
-> `python -m unittest discover` **333 OK**(2026-11-18,含 P0-Q3 地面/堆料负样本)、`portcv_v2_selftest` **54/0**、`ctest` **8/8**。
+> `python -m unittest discover` **336 OK**(2026-11-18,含 P0-Q3 地面/堆料负样本)、`portcv_v2_selftest` **54/0**、`ctest` **8/8**。
 > `PublishGate` 已接进 `RunService` / `main.cpp`,旧 dump 回放不再把 255 发给 PLC。
 >
 > **P1b/P1c 状态(2026-10-19,2026-10-27 复核)**:C++ `edge_v2` + commit 已接入 `--backend edge-v2`;
-> `portcv_edge_v2_selftest` **52/52**(含 P0-0 吊具高悬 / 夹箱门与"远距 ROI 弃权"回归;P0-Q3 地面/堆料/堆叠箱负样本)。
+> `portcv_edge_v2_selftest` **56/56**(含 P0-0 吊具高悬 / 夹箱门与"远距 ROI 弃权"回归;P0-Q3 地面/堆料/堆叠箱负样本)。
 > **2026-10-27 用 C++ 后端跑 A/B 现场片段**(`configs/edge-v2-front.json`,`--source-type images`):
 > A 50 帧 `edge_state` **1×41 / 255×9**、发布 **1×40 / 0×10**;B 59 帧 `edge_state` **2×11 / 255×48**、
 > 发布 **2×49 / 0×10**,**`1` 的发布次数 = 0**(修前 B 会在尾部误发布 `1` 23 帧,见
@@ -751,6 +762,7 @@ else:
 
 | 日期 | 变更 |
 | --- | --- |
+| 2026-11-18 | **P0-Q4 天空/电线 ROI**:竖向梯度块覆盖率找车体顶,剔除车体顶以上亮/暗带;空车歧义帧(正常给 2、立柱=0、箱体在车体内)改判 255(`ambiguous_empty_vehicle`);新增纹理车体 ROI 兜底(Python 参考可判 1,C++ 512 压缩图仍 255)。裸开运算实测会把 1 px Canny 边缘全删,改用块覆盖率/局部密度。新增 Python 3 项 + C++ 2 项回归(336/56) |
 | 2026-11-18 | **P0-Q3 地面/堆料误判修复**:`2` 增加"薄车面边梁(≤`contact_max_h_ratio`×估箱高)+ 车面下方暗带(≥`under_deck_dark_delta` 灰阶)"双门(`contact_max_h_ratio` / `under_deck_*`);`1` 增加"门板立柱间距 ≥`min_post_spacing_px`(24 px)"、"贴合形态需斜撑 ≥`min_diagonal_braces`"与"门板阵列跨度 ≥`min_post_span_ratio`(0.23×工作宽)"门。**真实 B 片段 f1740~f1789 修前误判 1×10 帧、发布 1×4 帧(真值 2);加跨度门后本帧 1 = 0、发布 2×40/0×10**;A f1000~f1049 仍发布 1×40/0×10。新增地面/堆料/堆叠箱负样本:Python `test_evidence_v2.GroundStackSafetyTests` 3 项、C++ `portcv_edge_v2_selftest` 4 项(52/0)。合成 `ground` 场景由 `2` 改判 `255`;**代价**:远距/遮挡帧弃权率上升,B 现场片段需按新门复跑后再定 `allow_state2` |
 | 2026-10-19 | **近距平车帧误弃权修复**:`horizontal_bands` 旧峰值规则(±2 行严格最大)会把 3 px 箱底暗带与相邻车面亮带并掉 → `no_box`;改为 ±1 局部极大 + 3 px 贪心抑制。箱底-车面贴合允许 `bed.y0 >= box.y1-1`,贴底时动态 ROI 只留 2 px 保护带,C++ `flat_contact` 不再强制 `ground>=0.4`。Python 全量 146/146、C++ edge_v2 21/21;746×192 实帧第 5 帧提交后发布 `2(flatbed)` |
 | 2026-10-19 | 创建 v2 路线;锁定 0/1/2 输出契约、PublishGate、front/high 双模式、证据拆分;P0 条件通过 |

+ 2 - 2
docs/runtime_route_decision.md

@@ -169,7 +169,7 @@ python scripts/replay_check.py runs/field_B/dump.jsonl --report runs/field_B/rep
 | 配置自检 | `portcv_config_selftest` | 269 通过 / 0 失败(含 `source.*` 默认值与 10 条非法值、`evidence_v2` 安全门参数校验) |
 | 帧率自检 | `portcv_rate_selftest` | 110 通过 / 0 失败 |
 | 证据自检 | `portcv_edge_selftest` | **112 通过 / 0 失败**(2026-10-27:C1/F2/F3/G2 等 12 项历史失败清零;A/B 现场片段同步通过,见 `docs/edge_evidence.md` §7.1) |
-| v2 证据自检 | `portcv_edge_v2_selftest` | **52 通过 / 0 失败**(含 P0-0 吊具高悬 / 夹箱门、远距 ROI 弃权、`allow_state2` 回退、P0-Q3 地面/堆料/堆叠箱负样本) |
+| v2 证据自检 | `portcv_edge_v2_selftest` | **56 通过 / 0 失败**(含 P0-0 吊具高悬 / 夹箱门、远距 ROI 弃权、`allow_state2` 回退、P0-Q3 地面/堆料/堆叠箱负样本) |
 | 端到端导出 | `portcv_run --backend edge --source-type synth --source-uri gondola --dump-frames runs/dump/dump.jsonl --max-frames 12 --no-plc` | 退出码 0,产出 12 帧 PGM + 12 行 JSONL |
 | 回放断言 | `python scripts/replay_check.py runs/dump/dump.jsonl` | **322 项断言通过 / 0 FAIL / 0 WARN**,12 帧像素逐字节校验(`gray_crc32` = `zlib.crc32`) |
 | 负向对照 ① | 篡改 1 个像素字节后回放 | 1 FAIL:`frame 3: gray_crc32=95890003 与像素实算 1924143813 不符` |
@@ -183,7 +183,7 @@ python scripts/replay_check.py runs/field_B/dump.jsonl --report runs/field_B/rep
 | **P0 修复:v2 导出契约缺口** | `replay_check.py` 对 v2 dump | 修前 20 FAIL(`abstain` 被写死 false、脚本只认 v1 的 14 项 `ev`)→ 修后 `abstain` 如实填写 + 脚本支持双口径 + 新增"高悬命中 ⇒ `edge_state=255` 且 `abstain=true`"断言 |
 | **残留风险**(2026-10-27 复核) | 同一批帧的 `edge_state` | v1:B 有 **2 帧**本帧结论 = `1`(未成串、未发布);A 打开 `allow_state2` 后 **1 帧** = `2`(`px_per_m=67.4` 最远帧)。v2:修 `min_bed_roi_px` 后 B 已 **0 帧** = `1`,但 A 255×9 / B 255×48 说明**远距与遮挡帧仍大量弃权**;需 step 1 连续帧 + 现场补拍整定 → `docs/edge_evidence.md` §7.1 ⑤ / §7.2 ③ |
 | **确定性复核** | 同一批 PGM 再跑一遍,与第一遍逐帧对拍(`replay_check.py --baseline`) | **状态 0 / 置信度 0 / 证据 0 / 像素 0 处差异**,1887 项断言 PASS → 判据链确定性成立 |
-| **冻结点回归(一条命令)** | `python scripts/regression_freeze.py` | **8 组全绿**:ctest 8/8、unittest 333、v1 回放 4 份(`A_s2` 按白名单恰好 1 条已知 FAIL)、v2 回放 2 份;缺产物 / 多一条失败即非 0 退出,绝不静默跳过(`runs/_freeze.txt`) |
+| **冻结点回归(一条命令)** | `python scripts/regression_freeze.py` | **8 组全绿**:ctest 8/8、unittest 336、v1 回放 4 份(`A_s2` 按白名单恰好 1 条已知 FAIL)、v2 回放 2 份;缺产物 / 多一条失败即非 0 退出,绝不静默跳过(`runs/_freeze.txt`) |
 | **现场语料的负向对照** | 把 1 帧的 1 个像素字节 +1 后回放 | 1 FAIL(`gray_crc32=2002841861 与像素实算 3586875639 不符`),退出码 1 → 现场语料同样"能过也能不过" |
 | **连续帧窗口**(f1550–1569,step 1) | 同上,`--start 1550 --stop 1569 --step 1` | 20 帧全 `255`;**`motion=0/20`**(对比 step5 的 37/59),`px_per_m` 115.07–115.49、`box_h_px` 298.1–299.2 → 运动门控与几何量都稳定 |
 | P0 修复:`--fps nan` | `python scripts/fuzz_app.py --exe … --only fps_nan` | 改前 `rc=0`(全速空转风险)→ 改后 **`rc=2` + `--fps 必须 ∈ (0, 240]`**(判据写成 `!(x > 0)`,NaN 比较恒 false 的坑) |

+ 1 - 1
docs/soak_7x24.md

@@ -257,6 +257,6 @@ ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 \
 - 此前跑过 6 s 冒烟(`runs/soak7_final4`):PASS,4 个样本,FC4+CRC 探活 100%。
 - 质量补丁/报告脱敏/终止事件硬失败后再次跑 6 s 冒烟(`runs/soak7_postpatch6`,合成输入 + 放宽阈值):
   PASS,4 个样本、0 重启、FC4+CRC 探活 100%;仅验证链路,不是 168 h 证据。
-- 单测 `python -m unittest discover -s tests -t .` 共 184 项全部通过(当时口径;当前主线为 333 项,见 `docs/stability_soak.md`)。
+- 单测 `python -m unittest discover -s tests -t .` 共 184 项全部通过(当时口径;当前主线为 336 项,见 `docs/stability_soak.md`)。
 - **168 h 未在本聊天会话内执行**:它必须在目标板卡 + 真实 RTSP + 真实 PLC 环境连续运行;
   本页给出的是可复现的执行与验收方法,不能把 20 s 冒烟当成 7×24 结论。

+ 1 - 1
docs/stability_soak.md

@@ -96,7 +96,7 @@ CSV 每行一次采样,可直接拖进表格画曲线,也可以当交付证
 | 运行期观测量自检(p50/p95/p99 / LOW_FPS / `fps_x10`) | `portcv_rate_selftest` | **110 通过 / 0 失败**(两个变体一致) |
 | 边缘证据自检 | `portcv_edge_selftest` | **112 通过 / 0 失败**(2026-10-27:C1/F2/F3/G2 等 12 项历史失败清零) |
 | 标定记录自检(sha256 / canonical JSON 跨语言黄金向量 / 过期与漂移) | `portcv_calib_selftest` | **104 通过 / 0 失败**(2026-10-27 新增;`ctest` **8/8**) |
-| Python 回归 | `python -m unittest discover -s tests -t .` | **333 项全绿**(本机 ~6 s,2026-11-18 复核) |
+| Python 回归 | `python -m unittest discover -s tests -t .` | **336 项全绿**(本机 ~6 s,2026-11-18 复核) |
 | 配置模板校验 | `python scripts/check_configs.py` | **4/4 通过**(default / edge-cpp / jetson-rtsp / rk3588-rtsp) |
 | 默认值防漂移 | `dump_default_config.py` 与 `configs/default.json` 逐字节对比 | **完全一致**(4945 字节) |
 | 默认值防漂移 | `dump_default_config.py --stdout` 与 `configs/default.json` 逐字节对比 | **完全一致**(2815 字节) |

+ 2 - 2
docs/standard_gbt45163_5_review.md

@@ -184,7 +184,7 @@ a) 传感器标定;b) 目标识别(被吊物、位置、抓取特征、装
 
 | 项 | 状态 | 代码/证据 |
 | --- | --- | --- |
-| P0-0 时序/commit 安全 | **已完成(Python + C++ 全链路,含 C++ 图像高悬门)** | `TemporalVoter` 去掉 UNKNOWN 冷启动直通,首帧/复位首帧必须过 `min_dwell_s`;`CommitTracker` 新增 `hoist_high` 安全门(不累计窗口);Python `detect_spreader_contact` / `detect_hoist_high` ↔ C++ `cpp/src/edge_v2_gates.cpp`(同判据、零依赖,`extract_segments` 代替 Hough);C++ 侧命中即 `abstain_reason=hoist_high/spreader_contact`、`edge_state=255`;回归 `portcv_edge_v2_selftest` 52/0(合成高悬帧 6 帧 0 commit、注入路径、门关闭对照;P0-Q3 地面/堆料/堆叠箱负样本)+ `replay_check.py` 新增"高悬命中 ⇒ 必须 255"断言。**负样本原片(TP-SAFE-001 mp4)仍缺失**,`i=668` 用等价合成帧覆盖 |
+| P0-0 时序/commit 安全 | **已完成(Python + C++ 全链路,含 C++ 图像高悬门)** | `TemporalVoter` 去掉 UNKNOWN 冷启动直通,首帧/复位首帧必须过 `min_dwell_s`;`CommitTracker` 新增 `hoist_high` 安全门(不累计窗口);Python `detect_spreader_contact` / `detect_hoist_high` ↔ C++ `cpp/src/edge_v2_gates.cpp`(同判据、零依赖,`extract_segments` 代替 Hough);C++ 侧命中即 `abstain_reason=hoist_high/spreader_contact`、`edge_state=255`;回归 `portcv_edge_v2_selftest` 56/0(合成高悬帧 6 帧 0 commit、注入路径、门关闭对照;P0-Q3 地面/堆料/堆叠箱负样本)+ `replay_check.py` 新增"高悬命中 ⇒ 必须 255"断言。**负样本原片(TP-SAFE-001 mp4)仍缺失**,`i=668` 用等价合成帧覆盖 |
 | P0-1 识别结果对象 | **已完成** | `portcv/recognition.py`:`RecognitionResult` / `ObjectType` / `results_from_observation`;`schema.recognition_results()` 兼容入口;JSON 往返测试 |
 | P0-2 flags 扩展 | **已完成(Python + C++ 位定义/契约)** | `StatusBits` bit8~12;`PublishGate.perception_uncertain`;`PERCEPTION_UNCERTAIN ⇒ RESULT_VALID=0`;`DATA_LOSS` 随 `FRAME_TIMEOUT`;契约向量与寄存器说明同步 |
 | P0-3 自监测 | **已完成(Python 运行时)** | `portcv/health.py`:清晰度/削顶/低纹理/时域差 + 迟滞;`runner` 输出 `SENSOR_DEGRADED`、`PERCEPTION_UNCERTAIN`、`MRC_REQUEST` 与健康日志 |
@@ -193,7 +193,7 @@ a) 传感器标定;b) 目标识别(被吊物、位置、抓取特征、装
 | P0-6 置信度校准 | **待 P0-4 数据积累** | 按 ODD 分桶可靠性图/ECE、分对象阈值、弃权率 |
 | P0-7 试验模板 | **已完成(初版)** | `docs/test_plan_gbt45163_5.md`:L1~L5、16 条用例、ODD 矩阵、300 事件/桶、通过准则与未关闭项 |
 
-> 已执行:`python -m unittest discover -s tests -v` → **333 项通过**(含新增 `test_decision`、`test_commit`、`test_recognition`、`test_health`、`test_evidence_v2`、`test_negative_frame_regression`、`test_storage`、`test_evidence_drill`、`test_calibration`(含 `hold_on_stale` 与跨语言黄金哈希)、`test_cli_selftest` 用例)。
+> 已执行:`python -m unittest discover -s tests -v` → **336 项通过**(含新增 `test_decision`、`test_commit`、`test_recognition`、`test_health`、`test_evidence_v2`、`test_negative_frame_regression`、`test_storage`、`test_evidence_drill`、`test_calibration`(含 `hold_on_stale` 与跨语言黄金哈希)、`test_cli_selftest` 用例)。
 > 真实视频回归因原始 mp4 已不在 `C:\Users\Administrator\Videos`,本轮用 `runs/video_eval/v2_120939_annot_05_i0668.jpg` 的取证帧验证拦截;现场拿到原片后必须重跑 `scripts/video_eval.py`,验收两个负样本 **0 次 commit**。
 > **交付完整性提醒**:`build/` 在 `.gitignore` 内,凡被文档/单测引用的工具都必须迁到 `scripts/`。本轮已迁:`scripts/calib_record.py`(标定记录)、`scripts/evidence_drill.py`(证据恢复演练,**`tests/test_evidence_drill.py` 直接 import 它,不迁则交付版本单测必红**)、`scripts/video_eval.py`(L3/TP-SAFE-001 回放)、`scripts/summarize_eval.py`(回放汇总)、`scripts/verify_equiv.py`(回放复算 vs `VisionPipeline.step`,已改成 `--video` 传参)。`build/` 里剩下的 `a1_*.py`、`_probe_*.py` 等为**一次性调参/看图脚本,明确列为非交付物**,不得写进验收步骤。
 

+ 14 - 0
portcv/config.py

@@ -117,6 +117,20 @@ DEFAULTS: Dict[str, Any] = {
         "min_post_len_ratio": 0.30,
         "min_post_spacing_px": 24.0,  # P0-Q3:门板立柱间距下限(原图像素);容器瓦楞 10~20 px
         "min_post_span_ratio": 0.23,  # P0-Q3:门板阵列 x 跨度下限;平车伪立柱只在窄区(~20%)
+        # P0-Q4:天空/电线 ROI 约束(竖向梯度块覆盖率找车体顶)
+        "texture_top_enable": True,
+        "texture_grad_th": 50.0,
+        "texture_block_px": 16,
+        "texture_block_hit_ratio": 0.03,
+        "texture_coverage_min": 0.50,
+        "texture_run_rows": 3,
+        "texture_smooth_rows": 7,
+        "texture_top_margin_ratio": 0.02,
+        # P0-Q4:空车/无箱兜底(纹理车体 ROI 再数一次门板立柱)
+        "body_fallback_enable": True,
+        "body_bottom_ratio": 0.75,
+        "body_min_opacity": 0.75,
+        "body_min_roi_px": 90,
         "min_diagonal_braces": 1,     # P0-Q3:敞车必须有"八"字斜撑;容器瓦楞没有
         "min_wall_opacity": 0.35,
         "max_flat_gap_px": 40.0,

+ 158 - 9
portcv/logic/evidence_v2.py

@@ -53,6 +53,7 @@ __all__ = [
     "detect_hoist_high",
     "detect_spreader_contact",
     "detect_structure_v2",
+    "find_texture_top",
     "ground_like_ratio",
     "horizontal_bands",
     "pick_box_and_bed",
@@ -102,6 +103,20 @@ class EvidenceV2Params:
     # P0-Q3:门板阵列的 x 跨度下限(占工作宽度)。真实 C70 横跨车体(A 25%~66%),
     # 平车车轮/制动梁只在窄区给伪立柱(B ~20%)→ 取 0.23(B 挡、A f1100 保留)。
     min_post_span_ratio: float = 0.23
+    # P0-Q4:天空/电线 ROI 约束(与 C++ 同名同义)。
+    texture_top_enable: bool = True
+    texture_grad_th: float = 50.0
+    texture_block_px: int = 16
+    texture_block_hit_ratio: float = 0.03
+    texture_coverage_min: float = 0.50
+    texture_run_rows: int = 3
+    texture_smooth_rows: int = 7
+    texture_top_margin_ratio: float = 0.02
+    # P0-Q4:空车/无箱兜底(纹理车体 ROI 再数一次门板立柱)
+    body_fallback_enable: bool = True
+    body_bottom_ratio: float = 0.75
+    body_min_opacity: float = 0.75
+    body_min_roi_px: int = 90
     # P0-Q3:`1`(敞车)还必须有"八"字斜撑/三角撑证据(docs/edge_evidence.md §4.1)。
     # 容器侧壁只有瓦楞、没有斜撑 → 防"上层箱坐在下层箱上"被判成敞车。
     # 0 = 关闭该门(只用于对照实验,现场不要关)。
@@ -168,6 +183,24 @@ class EvidenceV2Params:
             raise ValueError("min_post_spacing_px 不能为负")
         if not 0.0 <= self.min_post_span_ratio <= 1.0:
             raise ValueError("min_post_span_ratio 必须在 [0,1]")
+        if self.texture_grad_th <= 0.0:
+            raise ValueError("texture_grad_th 必须 > 0")
+        if self.texture_block_px < 4:
+            raise ValueError("texture_block_px 至少 4")
+        if not 0.0 <= self.texture_block_hit_ratio <= 1.0:
+            raise ValueError("texture_block_hit_ratio 必须在 [0,1]")
+        if not 0.0 <= self.texture_coverage_min <= 1.0:
+            raise ValueError("texture_coverage_min 必须在 [0,1]")
+        if self.texture_run_rows < 1 or self.texture_smooth_rows < 1:
+            raise ValueError("texture_run_rows / texture_smooth_rows 至少 1")
+        if not 0.0 <= self.texture_top_margin_ratio <= 0.5:
+            raise ValueError("texture_top_margin_ratio 必须在 [0,0.5]")
+        if not 0.0 < self.body_bottom_ratio <= 1.0:
+            raise ValueError("body_bottom_ratio 必须在 (0,1]")
+        if not 0.0 <= self.body_min_opacity <= 1.0:
+            raise ValueError("body_min_opacity 必须在 [0,1]")
+        if self.body_min_roi_px < 8:
+            raise ValueError("body_min_roi_px 至少 8")
         if self.min_diagonal_braces < 0:
             raise ValueError("min_diagonal_braces 不能为负")
         if self.box_height_m <= 0.0:
@@ -199,6 +232,18 @@ class EvidenceV2Params:
             min_post_len_ratio=float(raw.get("min_post_len_ratio", 0.30)),
             min_post_spacing_px=float(raw.get("min_post_spacing_px", 24.0)),
             min_post_span_ratio=float(raw.get("min_post_span_ratio", 0.23)),
+            texture_top_enable=bool(raw.get("texture_top_enable", True)),
+            texture_grad_th=float(raw.get("texture_grad_th", 50.0)),
+            texture_block_px=int(raw.get("texture_block_px", 16)),
+            texture_block_hit_ratio=float(raw.get("texture_block_hit_ratio", 0.03)),
+            texture_coverage_min=float(raw.get("texture_coverage_min", 0.50)),
+            texture_run_rows=int(raw.get("texture_run_rows", 3)),
+            texture_smooth_rows=int(raw.get("texture_smooth_rows", 7)),
+            texture_top_margin_ratio=float(raw.get("texture_top_margin_ratio", 0.02)),
+            body_fallback_enable=bool(raw.get("body_fallback_enable", True)),
+            body_bottom_ratio=float(raw.get("body_bottom_ratio", 0.75)),
+            body_min_opacity=float(raw.get("body_min_opacity", 0.75)),
+            body_min_roi_px=int(raw.get("body_min_roi_px", 90)),
             min_diagonal_braces=int(raw.get("min_diagonal_braces", 1)),
             min_wall_opacity=float(raw.get("min_wall_opacity", 0.35)),
             max_flat_gap_px=float(raw.get("max_flat_gap_px", 40.0)),
@@ -240,6 +285,7 @@ class EvidenceV2Result:
     view: ViewMode = ViewMode.UNKNOWN
     box_bottom_y: Optional[float] = None
     box_top_y: Optional[float] = None
+    texture_top_y: Optional[float] = None
     box_h_px: Optional[float] = None
     px_per_m: Optional[float] = None
     scale_ok: bool = False
@@ -296,9 +342,10 @@ class EvidenceV2Result:
         ok = self.publishable(require_commit)
         state = int(self.state) if ok else int(SceneState.UNKNOWN)
         conf = float(self.confidence) if ok else 0.0
-        reason = "v2:%s view=%s posts=%d opacity=%.2f deck=%d under_deck=%d gap=%s commit=%s hoist=%d" % (
+        reason = "v2:%s view=%s top=%s posts=%d opacity=%.2f deck=%d under_deck=%d gap=%s commit=%s hoist=%d" % (
             "ok" if ok else "abstain",
             self.view.value,
+            "n/a" if self.texture_top_y is None else "%.0f" % self.texture_top_y,
             int(self.door_posts),
             float(self.wall_opacity),
             int(bool(self.deck_edge)),
@@ -325,6 +372,7 @@ class EvidenceV2Result:
             "view": self.view.value,
             "box_bottom_y": _round_opt(self.box_bottom_y),
             "box_top_y": _round_opt(self.box_top_y),
+            "texture_top_y": _round_opt(self.texture_top_y),
             "box_h_px": _round_opt(self.box_h_px),
             "px_per_m": _round_opt(self.px_per_m),
             "scale_ok": bool(self.scale_ok),
@@ -372,6 +420,37 @@ def _to_gray(image: np.ndarray) -> np.ndarray:
     return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
 
+def find_texture_top(gray: np.ndarray, window: Tuple[int, int, int, int],
+                     params: EvidenceV2Params) -> float:
+    """P0-Q4:用“竖向梯度块覆盖率”找车体顶;-1 = 未找到/关闭。"""
+
+    if not params.texture_top_enable or gray.size == 0:
+        return -1.0
+    gx = np.abs(cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3))
+    x0 = max(0, min(int(window[0]), gray.shape[1]))
+    x1 = min(gray.shape[1], max(x0, int(window[2])))
+    block = max(4, int(params.texture_block_px))
+    nb = (x1 - x0) // block
+    if nb < 2:
+        return -1.0
+    cov = np.zeros(gray.shape[0], dtype=np.float32)
+    for y in range(gray.shape[0]):
+        hit = 0
+        for i in range(nb):
+            bx = x0 + i * block
+            if float((gx[y, bx:bx + block] >= params.texture_grad_th).mean()) >= \
+                    params.texture_block_hit_ratio:
+                hit += 1
+        cov[y] = hit / nb
+    smooth = max(1, int(params.texture_smooth_rows))
+    sm = np.convolve(cov, np.ones(smooth, dtype=np.float32) / smooth, mode="same")
+    run = max(1, int(params.texture_run_rows))
+    for y in range(max(0, int(window[1])), gray.shape[0] - run + 1):
+        if all(sm[y + k] >= params.texture_coverage_min for k in range(run)):
+            return float(y)
+    return -1.0
+
+
 def _row_mean(gray: np.ndarray, x0: int, x1: int, y0: int, y1: int) -> float:
     """``[x0,x1) × [y0,y1)`` 的灰度均值(越界自动钳制;空框返回 0)。"""
 
@@ -1053,9 +1132,20 @@ class EvidenceV2:
             int(self.p.window[2] * ww), int(self.p.window[3] * wh),
         )
         max_h = max(6, int(self.p.band_max_h_ratio * wh))
+        # P0-Q4:车体顶以上(天空电线/水印)的亮/暗带不参与 box/bed 选择。
+        texture_top = find_texture_top(gray, window, self.p)
         bright, dark = horizontal_bands(
             gray, window, min_h=max(1, int(self.p.band_min_h * scale)), max_h=max_h
         )
+        if texture_top > 0.0 and texture_top > window[1] + 0.05 * wh:
+            margin = self.p.texture_top_margin_ratio * wh
+            bright_all, dark_all = list(bright), list(dark)
+            bright = [b for b in bright if b.y1 >= texture_top - margin]
+            dark = [b for b in dark if b.y1 >= texture_top - margin]
+            if not bright:
+                bright = bright_all
+            if not dark:
+                dark = dark_all
         # 先估一个箱高,用于“车体上缘搜索窗”(P0 固定 120 px 的等价物)。
         box_hint = max(80.0, 0.40 * wh)
         box, bed = pick_box_and_bed(
@@ -1263,10 +1353,61 @@ class EvidenceV2:
             diagonal_braces=int(structure["diagonal_lines"]),
             post_span_ratio=float(post_span_ratio),
         )
+        body = None
+        body_roi = None
+        if (self.p.body_fallback_enable and texture_top > 0.0 and state != 1
+                and texture_top > window[1] + 0.05 * wh):
+            by0 = max(int(window[1]), int(round(texture_top)))
+            by1 = min(int(window[3]), int(round(
+                texture_top + self.p.body_bottom_ratio * (window[3] - texture_top))))
+            if by1 > by0:
+                body_roi = (window[0], by0, window[2], by1)
+                bst = detect_structure_v2(
+                    gray, body_roi,
+                    min_post_len_ratio=self.p.min_post_len_ratio,
+                    cluster_gap_px=9.0, scale=scale,
+                )
+                bpos = bst.get("post_positions") or []
+                bspan = (
+                    (max(bpos) - min(bpos)) / max(1.0, float(body_roi[2] - body_roi[0]))
+                    if len(bpos) >= 2 else 0.0
+                )
+                bground, bblocks = ground_like_ratio(
+                    gray, body_roi, bst.get("lines", []),  # type: ignore[arg-type]
+                    block_px=self.p.ground_block_px,
+                    density_lo=self.p.ground_density_lo,
+                    density_hi=self.p.ground_density_hi,
+                )
+                bopacity = 1.0 - bground if bblocks > 0 else 0.0
+                bh = (by1 - by0) / max(scale, 1e-6)
+                if (bh >= self.p.body_min_roi_px
+                        and int(bst["post_count"]) >= self.p.min_door_posts
+                        and bspan >= self.p.min_post_span_ratio
+                        and bopacity >= self.p.body_min_opacity
+                        and int(bst["diagonal_lines"]) >= self.p.min_diagonal_braces):
+                    state = 1
+                    conf = min(1.0, 0.55 + 0.25 * min(1.0, bst["post_count"] / 8.0)
+                               + 0.15 * bopacity)
+                    hits = min(1.0, 0.40 + 0.05 * bst["post_count"] + 0.20 * bopacity)
+                    reason = "body_fallback_wall"
+                    gap_px = 0.0
+                    body = {
+                        "posts": int(bst["post_count"]),
+                        "diagonal": int(bst["diagonal_lines"]),
+                        "opacity": bopacity,
+                    }
         gap_m = (
             None if gap_px is None or px_per_m is None or px_per_m <= 0.0
             else gap_px / px_per_m
         )
+        if body is not None:
+            gap_m = 0.0
+        if (body is None and texture_top > 0.0 and state == 2 and posts == 0
+                and box.y1 > texture_top + 0.02 * wh):
+            state = 255
+            conf = 0.0
+            hits = 0.0
+            reason = "ambiguous_empty_vehicle"
         commit = self.tracker.update(
             ts,
             state=state,
@@ -1287,24 +1428,27 @@ class EvidenceV2:
             view=self.p.view,
             box_bottom_y=box.y1 / max(scale, 1e-6),
             box_top_y=box_top,
+            texture_top_y=(
+                None if texture_top <= 0.0 else texture_top / max(scale, 1e-6)
+            ),
             box_h_px=box_h_px,
             px_per_m=px_per_m,
             scale_ok=px_per_m is not None,
             bed_top_y=None if bed is None else bed.y0 / max(scale, 1e-6),
             gap_px=gap_px,
             gap_m=gap_m,
-            door_posts=posts,
+            door_posts=(body["posts"] if body else posts),
             post_spacing_px=(
                 None if spacing_median is None else float(spacing_median) / max(scale, 1e-6)
             ),
             post_spacing_cv=None if spacing_cv is None else float(spacing_cv),
             rect_doors=int(structure["rect_doors"]),
-            diagonal_braces=int(structure["diagonal_lines"]),
-            wall_opacity=opacity,
-            deck_edge=bool(deck_edge),
-            under_deck=bool(under_deck),
+            diagonal_braces=(body["diagonal"] if body else int(structure["diagonal_lines"])),
+            wall_opacity=(body["opacity"] if body else opacity),
+            deck_edge=bool(deck_edge) and body is None,
+            under_deck=bool(under_deck) and body is None,
             wheel_count=int(wheels),
-            ground_ratio=ground,
+            ground_ratio=(1.0 - body["opacity"]) if body else ground,
             phase=phase,
             committed=bool(commit.committed),
             commit_reason=commit.reason,
@@ -1317,11 +1461,16 @@ class EvidenceV2:
                 else ("" if state in (0, 1, 2) else reason)
             ),
             below_roi=(
-                int(round(below_work[0] / scale)), int(round(below_work[1] / scale)),
-                int(round(below_work[2] / scale)), int(round(below_work[3] / scale)),
+                (int(round(body_roi[0] / scale)), int(round(body_roi[1] / scale)),
+                 int(round(body_roi[2] / scale)), int(round(body_roi[3] / scale)))
+                if body else
+                (int(round(below_work[0] / scale)), int(round(below_work[1] / scale)),
+                 int(round(below_work[2] / scale)), int(round(below_work[3] / scale)))
             ),
             diagnostics={
                 "class_reason": reason,
+                "texture_top": None if texture_top <= 0.0 else round(texture_top / scale, 2),
+                "body_fallback": bool(body),
                 "box_band": [round(box.y0 / scale, 2), round(box.y1 / scale, 2)],
                 "bed_band": None if bed is None else [round(bed.y0 / scale, 2), round(bed.y1 / scale, 2)],
                 "under_deck": bool(under_deck),

+ 57 - 0
tests/test_evidence_v2.py

@@ -21,6 +21,7 @@ from portcv.logic.evidence_v2 import (
     Band,
     EvidenceV2,
     EvidenceV2Params,
+    find_texture_top,
     pick_box_and_bed,
 )
 from portcv.service.pipeline import VisionPipeline
@@ -32,6 +33,9 @@ def bed_scene(*, gap_px: int = 18, box_bottom: int = 392) -> np.ndarray:
     h, w = 720, 1280
     image = np.full((h, w), 120, dtype=np.uint8)
     image[40:box_bottom, :] = 185
+    # 箱体竖波纹(真实集装箱有;也让 P0-Q4 顶部纹理门不把箱顶误当天空)
+    for x in range(60, 1240, 48):
+        image[50:box_bottom - 4, x:x + 3] = 176
     image[box_bottom:box_bottom + 12, :] = 55
     # gap_px 是“箱底下沿(暗带下沿)→ 墙顶亮带”的物理间隙。
     wall_top = box_bottom + 12 + gap_px
@@ -55,6 +59,8 @@ def flat_scene(*, gap_px: int = 4) -> np.ndarray:
     h, w = 720, 1280
     image = np.full((h, w), 120, dtype=np.uint8)
     image[40:392, :] = 185
+    for x in range(60, 1240, 48):
+        image[50:388, x:x + 3] = 176
     image[392:404, :] = 55
     deck_top = 404 + gap_px
     image[deck_top:deck_top + 5, :] = 225
@@ -101,6 +107,8 @@ def ground_scene(*, low: int = 95, high: int = 115, noise: int = 4) -> np.ndarra
     h, w = 720, 1280
     image = np.full((h, w), 120, dtype=np.uint8)
     image[40:392, :] = 185
+    for x in range(60, 1240, 48):
+        image[50:388, x:x + 3] = 176
     image[392:404, :] = 55  # 箱底暗带
     rng = np.random.default_rng(20261118)
     ramp = np.linspace(low, high, h - 404).reshape(-1, 1)
@@ -223,6 +231,55 @@ class EvidenceClassificationTests(unittest.TestCase):
         self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1])
 
 
+def sky_wire_scene() -> np.ndarray:
+    """P0-Q4:天空电线 + 空 C70 车体(512×512,无下采样)。"""
+    h = w = 512
+    image = np.full((h, w), 200, dtype=np.uint8)
+    for y in (20, 52, 84, 116):
+        image[y:y + 2, :] = 30
+    image[165:405, :] = 95
+    for x in range(30, 480, 18):
+        image[175:400, x:x + 5] = 45
+    for x in range(30, 480, 50):
+        cv2.rectangle(image, (x, 185), (x + 40, 380), 60, 3)
+        image[188:377, x + 3:x + 37] = 110
+    for dy in range(5, 235, 8):
+        y = 165 + dy
+        image[y:y + 2, 20:492] = 80
+    for x in range(40, 470, 70):
+        cv2.line(image, (x, 190), (x + 80, 330), 30, 7)
+    image[405:, :] = 140
+    return image
+
+
+class TextureTopTests(unittest.TestCase):
+    """P0-Q4:天空电线不能把“车体顶”骗到天上。"""
+
+    def test_sky_wires_are_above_vehicle_top(self):
+        image = sky_wire_scene()
+        window = (int(0.24 * 512), int(0.02 * 512), int(0.78 * 512), int(0.95 * 512))
+        top = find_texture_top(image, window, EvidenceV2Params())
+        self.assertGreater(top, 120, "车体顶应落在电线以下")
+        self.assertLess(top, 220, "车体顶不应落到车体中部")
+
+    def test_empty_c70_body_fallback_is_state1(self):
+        ev = EvidenceV2(EvidenceV2Params(require_commit=False))
+        result = ev.analyze(sky_wire_scene(), ts=0.0)
+        self.assertEqual(result.state, 1, result.to_dict())
+        self.assertGreater(result.texture_top_y or 0.0, 120.0)
+        self.assertEqual(
+            result.diagnostics.get("class_reason"), "body_fallback_wall",
+            result.to_dict(),
+        )
+
+    def test_plain_sky_has_no_vehicle_top(self):
+        image = np.full((720, 1280), 200, dtype=np.uint8)
+        for y in (40, 90, 140):
+            image[y:y + 2, :] = 30
+        window = (int(0.24 * 1280), int(0.02 * 720), int(0.78 * 1280), int(0.95 * 720))
+        self.assertLess(find_texture_top(image, window, EvidenceV2Params()), 0)
+
+
 class GroundStackSafetyTests(unittest.TestCase):
     """P0-Q3:地面/堆料/堆叠箱不得被判成 1(敞车)或 2(平车)。"""