Просмотр исходного кода

fix(portcv): 收紧 v2 平车判据,地面/堆料不再判 2/1

为什么改:
- v2 把"箱底紧贴的厚亮面"当成车面:内置合成 ground 场景被发布为
  2(flatbed)(flags=0x00C7, RESULT_VALID+STABLE);上层箱坐在下层箱上
  会被瓦楞骗成 1(敞车)。
- 客户口径:2 的误报优先级最高,宁可 255 不可错判;0 类真实负样本尚未到位,
  先把"地面/堆料不判 1/2"钉死。

改了什么:
- evidence_v2:2 增加"薄车面边梁(contact_max_h_ratio)+ 车面下方暗带
  (under_deck_*)"双门;1 增加门板立柱间距下限 min_post_spacing_px,
  且只在贴合形态(gap<=1px 或无 bed)要求 min_diagonal_braces 条斜撑。
- C++ flat_contact:min_contact_h 由 3% 降到 1.5%(至少 4px),让侧视 X70
  的 8~9px 车面边梁能命中;厚亮面由 contact_max_h_ratio 排除。
- Python/C++/configs/default/edge-v2-front 同步新键;新增 Python 3 项
  (GroundStackSafetyTests)与 C++ 4 项负样本回归;文档同步。

验证:
- python -m unittest discover -s tests -t . -q -> 232 OK (skipped=1)
- ctest --test-dir build-cmake/windows-zig-release -> 8/8
- portcv_edge_v2_selftest -> 52 passed / 0 failed
- python scripts/check_configs.py -> 5/5;gen_cpp_constants.py --check -> OK
- 合成 ground:内部 255 / 发布 0 保持(修前 2+commit);A/B 合成正样本仍 1/2

关联:
- docs/route_v2.md §4.2/§4.4/§4.6/§7.1/§9.3
- docs/edge_evidence.md §7.2 ⑥
kwass 5 дней назад
Родитель
Сommit
15d5bc4104

+ 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`,跑 330 项单测)需每人执行一次
+提交钩子(`.githooks/pre-commit`,跑 333 项单测)需每人执行一次
 `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 / 48 / 104)
+ctest --test-dir build --output-on-failure     # 八个自检全绿(200 / 269 / 110 / 231 / 112 / 54 / 52 / 104)
 
-# 一条命令跑完"冻结点"回归(ctest + Python 330 单测 + v1/v2 现场回放),失败即非 0 退出
+# 一条命令跑完"冻结点"回归(ctest + Python 333 单测 + v1/v2 现场回放),失败即非 0 退出
 python scripts/regression_freeze.py --build-dir build
 
 # 跑起来(PLC 用 MB_CLIENT 轮询 1502 端口读 12 个字结果区)

+ 6 - 0
configs/default.json

@@ -155,6 +155,8 @@
     "flat_max_door_posts": 4,
     "max_post_spacing_cv": 6.0,
     "min_post_len_ratio": 0.3,
+    "min_post_spacing_px": 24.0,
+    "min_diagonal_braces": 1,
     "min_wall_opacity": 0.35,
     "max_flat_gap_px": 40.0,
     "wall_edge_density_ref": 0.14,
@@ -165,6 +167,10 @@
     "min_flat_ground_ratio": 0.4,
     "min_zero_ground_ratio": 0.65,
     "deck_min_len_ratio": 0.3,
+    "contact_max_h_ratio": 0.12,
+    "under_deck_dark_delta": 12.0,
+    "under_deck_min_h_ratio": 0.01,
+    "under_deck_search_h_ratio": 0.1,
     "box_height_m": 2.591,
     "px_per_m": 0.0,
     "min_scale_px": 60.0,

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

@@ -6,6 +6,7 @@
     "source.type=images 是 A/B 回放模板;真机改成 rtsp 并填 uri。",
     "require_commit=true:commit 不成立时内部输出 255,PublishGate 保持上一稳定值。",
     "allow_state2=true:平车 2 已打开提交;顶层与 commit 两个开关串联,任一 false 都会回退为只识别、不提交。",
+    "P0-Q3:平车 2 必须是『薄车面边梁 + 车面下方暗带』;地面/下层箱顶/月台的厚亮面不判 2(宁可 255)。",
     "px_per_m=0 表示用箱体竖棱自标尺;现场若已标定可填固定值(A/B 实测约 115.6)。"
   ],
   "run": {
@@ -70,6 +71,8 @@
     "flat_max_door_posts": 4,
     "max_post_spacing_cv": 6.0,
     "min_post_len_ratio": 0.3,
+    "min_post_spacing_px": 24.0,
+    "min_diagonal_braces": 1,
     "min_wall_opacity": 0.35,
     "wall_edge_density_ref": 0.14,
     "wall_edge_density_span": 0.04,
@@ -79,6 +82,10 @@
     "min_flat_ground_ratio": 0.4,
     "min_zero_ground_ratio": 0.65,
     "deck_min_len_ratio": 0.3,
+    "contact_max_h_ratio": 0.12,
+    "under_deck_dark_delta": 12.0,
+    "under_deck_min_h_ratio": 0.01,
+    "under_deck_search_h_ratio": 0.1,
     "max_flat_gap_px": 40.0,
     "box_height_m": 2.591,
     "px_per_m": 0.0,

+ 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` | **48 通过 / 0 失败** | edge-v2 证据链:零间隙接触、侧视 flatbed、`allow_state2` 回退、空帧/无图 abstain;**P0-0 吊具高悬 / 夹箱门**(合成高悬帧 6 帧 0 commit、注入路径、远距 ROI 弃权、门关闭对照) |
+| `portcv_edge_v2_selftest` | **52 通过 / 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`。

+ 24 - 4
cpp/include/portcv/edge_v2.hpp

@@ -1,10 +1,10 @@
 // P1b/P1c:前视 v2 结构证据 + commit 门(C++ 版,零外部依赖)。
 //
 // 与 Python `portcv/logic/evidence_v2.py` / `commit.py` 同参数、同字段:
-//   * 1(敞车)= 箱底以下门板立柱阵列 + 不透明侧墙;
-//   * 2(平车)= 门板立柱 ≤4 + 车面边梁;
+//   * 1(敞车)= 箱底以下门板立柱阵列 + 不透明侧墙(贴合形态还需"八"字斜撑);
+//   * 2(平车)= 门板立柱 ≤4 + 薄车面边梁 + 边梁下方暗带(车底空隙/阴影);
 //   * 0(其他)= 只有连续地面;
-//   * 看不清 → 255;`allow_state2=false` 时 2 只识别、不提交(现场联锁/回退用)。
+//   * 看不清 / 地面堆料 / 堆叠箱 → 255;`allow_state2=false` 时 2 只识别、不提交(现场联锁/回退用)。
 //
 // 与 v1 `edge_evidence.*` 的关系:
 //   * v1 冻结、不再调参;本文件是新的 runtime 路径(`--backend edge-v2`);
@@ -52,6 +52,14 @@ struct EdgeV2Params {
     int flat_max_door_posts = 4;
     double max_post_spacing_cv = 6.0;
     double min_post_len_ratio = 0.30;
+    /// P0-Q3:门板立柱间距下限(**原图像素**)。容器侧壁瓦楞 10~20 px,
+    /// C70 门板 63~185 px(docs/edge_evidence.md §4.1)→ 低于该值不构成门板阵列。
+    /// 没有这条时,"上层箱坐在下层箱上"会把下层箱瓦楞当车斗门板 → 误判 1。
+    double min_post_spacing_px = 24.0;
+    /// P0-Q3:`1`(敞车)必须有"八"字斜撑/三角撑证据(docs/edge_evidence.md §4.1)。
+    /// 容器侧壁只有瓦楞、没有斜撑 → 防"上层箱坐在下层箱上"被判成敞车。
+    /// 0 = 关闭该门(只用于对照实验,现场不要关)。
+    int min_diagonal_braces = 1;
     double min_wall_opacity = 0.35;
     double wall_edge_density_ref = 0.14;
     double wall_edge_density_span = 0.04;
@@ -62,6 +70,15 @@ struct EdgeV2Params {
     double min_zero_ground_ratio = 0.65;
     double deck_min_len_ratio = 0.30;
     double max_flat_gap_px = 40.0;
+    /// P0-Q3:`2`(平车)必须是"薄车面边梁 + 车面下方暗带"。
+    /// 箱底紧贴的亮带若比 contact_max_h_ratio × 估箱高更厚,它不是车面边梁,
+    /// 而是地面 / 下层箱顶 / 月台 / 货台等大平面 → 不当作车面、不判 2。
+    double contact_max_h_ratio = 0.12;
+    /// 车面亮带下方必须在 under_deck_search_h_ratio × 画幅内找到一条更暗的
+    /// under_deck_min_h_ratio × 画幅高的带(车底空隙/阴影);找不到 → 不判 2。
+    double under_deck_dark_delta = 12.0;
+    double under_deck_min_h_ratio = 0.01;
+    double under_deck_search_h_ratio = 0.10;
     double box_height_m = 2.591;
     double px_per_m = 0.0;             ///< 0 = 用箱体竖棱自标尺
     double min_scale_px = 60.0;
@@ -172,6 +189,7 @@ struct EvidenceV2Result {
     int edge_pixels = 0;    ///< Canny 边缘像素数(诊断)
     double wall_opacity = 0.0;
     bool deck_edge = false;
+    bool under_deck = false;   ///< 车面亮带下方找到"车底空隙/阴影"暗带(P0-Q3)
     int wheel_count = 0;
     double ground_ratio = 0.0;
     std::string phase = "T1";
@@ -229,7 +247,9 @@ private:
     ClassifyResult classify(int posts, std::optional<double> spacing_cv, double opacity,
                             double ground, bool deck, int wheels,
                             std::optional<double> gap_px, bool motion_ok,
-                            const std::string& view, double below_roi_h_px) const;
+                            const std::string& view, double below_roi_h_px,
+                            bool under_deck, double post_spacing_px,
+                            int diagonal_braces) const;
 
     EdgeV2Params p_;
     V2CommitTracker tracker_;

+ 33 - 2
cpp/src/app_config.cpp

@@ -435,6 +435,8 @@ bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
         integer("evidence_v2.flat_max_door_posts", &v->flat_max_door_posts),
         num("evidence_v2.max_post_spacing_cv", &v->max_post_spacing_cv),
         num("evidence_v2.min_post_len_ratio", &v->min_post_len_ratio),
+        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_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),
@@ -444,6 +446,10 @@ bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
         num("evidence_v2.min_flat_ground_ratio", &v->min_flat_ground_ratio),
         num("evidence_v2.min_zero_ground_ratio", &v->min_zero_ground_ratio),
         num("evidence_v2.deck_min_len_ratio", &v->deck_min_len_ratio),
+        num("evidence_v2.contact_max_h_ratio", &v->contact_max_h_ratio),
+        num("evidence_v2.under_deck_dark_delta", &v->under_deck_dark_delta),
+        num("evidence_v2.under_deck_min_h_ratio", &v->under_deck_min_h_ratio),
+        num("evidence_v2.under_deck_search_h_ratio", &v->under_deck_search_h_ratio),
         num("evidence_v2.max_flat_gap_px", &v->max_flat_gap_px),
         num("evidence_v2.box_height_m", &v->box_height_m),
         num("evidence_v2.px_per_m", &v->px_per_m),
@@ -662,6 +668,26 @@ bool validate(const AppConfig* cfg, std::string* error) {
     if (v2.min_wall_opacity < 0.0 || v2.min_wall_opacity > 1.0) {
         return bad("evidence_v2.min_wall_opacity 必须 ∈ [0,1]");
     }
+    if (v2.min_post_spacing_px < 0.0) {
+        return bad("evidence_v2.min_post_spacing_px 不能为负(0=不启用该门)");
+    }
+    if (v2.min_diagonal_braces < 0) {
+        return bad("evidence_v2.min_diagonal_braces 不能为负(0=不启用该门)");
+    }
+    // P0-Q3:2(平车)的贴合亮带厚度/车面下方暗带参数。写错会让门永不触发,
+    // 比报错更危险(地面堆料会被判成平车),所以一律启动即失败。
+    if (!(v2.contact_max_h_ratio > 0.0 && v2.contact_max_h_ratio <= 0.5)) {
+        return bad("evidence_v2.contact_max_h_ratio 必须 ∈ (0, 0.5]");
+    }
+    if (v2.under_deck_dark_delta < 0.0) {
+        return bad("evidence_v2.under_deck_dark_delta 不能为负");
+    }
+    if (!(v2.under_deck_min_h_ratio > 0.0 && v2.under_deck_min_h_ratio <= 0.1)) {
+        return bad("evidence_v2.under_deck_min_h_ratio 必须 ∈ (0, 0.1]");
+    }
+    if (!(v2.under_deck_search_h_ratio > 0.0 && v2.under_deck_search_h_ratio <= 0.5)) {
+        return bad("evidence_v2.under_deck_search_h_ratio 必须 ∈ (0, 0.5]");
+    }
     // 太小会让"远距小箱"重新参与 1 的判定(B 片段实测误发布 1);太大则正常
     // 车距也判不出 1。A 实测 ROI≈201 px、B 误判帧 44~68 px,取 90 px 留出双向余量。
     if (v2.min_bed_roi_px < 24) { return bad("evidence_v2.min_bed_roi_px 至少 24"); }
@@ -867,10 +893,15 @@ std::string describe_app_config(const AppConfig& cfg) {
     const V2CommitParams& vc = cfg.evidence_commit;
     append_line(&out,
                 "v2证据: view=%s work_width=%d posts=[%d, %d] wall_opacity>=%.2f "
-                "ground=[%.2f, %.2f] 箱底ROI>=%dpx\n",
+                "ground=[%.2f, %.2f] 箱底ROI>=%dpx 门板间距>=%.0fpx 斜撑>=%d\n",
                 v2.view.c_str(), v2.work_width, v2.min_door_posts, v2.max_door_posts,
                 v2.min_wall_opacity, v2.ground_density_lo, v2.ground_density_hi,
-                v2.min_bed_roi_px);
+                v2.min_bed_roi_px, v2.min_post_spacing_px, v2.min_diagonal_braces);
+    append_line(&out,
+                "v2平车门: 贴合亮带<=%.2f×估箱高 车面下方暗带>=%.0f灰阶 "
+                "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落位: require_commit=%d gap_m<=%.2f gap_px<=%.1f stable=%d structure=%d "
                 "allow_state2=%d\n",

+ 88 - 9
cpp/src/edge_v2.cpp

@@ -257,6 +257,7 @@ std::string EvidenceV2Result::evidence_summary() const {
                       " 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 += " 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") +
@@ -536,7 +537,9 @@ EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing
                                         double opacity, double ground, bool deck, int wheels,
                                         std::optional<double> gap_px, bool motion_ok,
                                         const std::string& view,
-                                        double below_roi_h_px) const {
+                                        double below_roi_h_px,
+                                        bool under_deck, double post_spacing_px,
+                                        int diagonal_braces) const {
     ClassifyResult r;
     if (view == "unknown") {
         r.reason = "view_unknown";
@@ -560,6 +563,17 @@ EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing
         posts >= relaxed_min_posts && opacity >= 0.65 &&
         (!spacing_cv.has_value() || *spacing_cv <= 1.0);
     const bool posts_ok = posts >= p_.min_door_posts || relaxed_post_array;
+    // P0-Q3:门板立柱间距下限(原图像素)。容器侧壁瓦楞 10~20 px,
+    // C70 门板 63~185 px → 低于下限不构成门板阵列(防"上层箱坐在下层箱上"→ 1)。
+    // post_spacing_px <= 0 表示不可用,不用它拒绝。
+    const bool post_spacing_ok =
+        post_spacing_px <= 0.0 || post_spacing_px >= p_.min_post_spacing_px;
+    // P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。
+    // 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权;
+    // 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。
+    const bool contact_bed = !gap_px.has_value() || *gap_px <= 1.0;
+    const bool doors_ok =
+        !contact_bed || diagonal_braces >= p_.min_diagonal_braces;
     // 冲突时:A 的真实门板阵列可能只剩 min_posts-1 根(见上),同时又误检到
     // 车面边梁;此时按“门板阵列”优先(Python 对应帧 deck=False,不会冲突)。
     const bool prefer_bed_on_conflict =
@@ -567,6 +581,7 @@ EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing
     const bool bed_evidence =
         posts_ok && posts <= p_.max_door_posts &&
         opacity >= p_.min_wall_opacity && post_array_regular &&
+        post_spacing_ok && doors_ok &&
         (!gap_px.has_value() || *gap_px <= p_.max_bed_gap_px) &&
         (!spacing_cv.has_value() || *spacing_cv <= p_.max_post_spacing_cv);
     // 敞车(1)需要真的看得见"门板立柱阵列":箱底以下的动态 ROI 太矮时,
@@ -576,7 +591,7 @@ EdgeV2::ClassifyResult EdgeV2::classify(int posts, std::optional<double> spacing
     const bool bed_roi_ok = below_roi_h_px >= static_cast<double>(p_.min_bed_roi_px);
     const bool bed_strong = bed_evidence && bed_roi_ok;
     const bool flat_strong =
-        posts <= p_.flat_max_door_posts && deck &&
+        posts <= p_.flat_max_door_posts && deck && under_deck &&
         (!gap_px.has_value() || *gap_px <= p_.max_flat_gap_px);
     if (bed_strong && flat_strong && !prefer_bed_on_conflict) {
         r.reason = "conflict_1_2";
@@ -686,6 +701,17 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
         }
     }
 
+    // P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/
+    // 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里
+    // `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。
+    const double est_h = std::max(60.0, box.y0 - 0.05 * work.height);
+    bool thick_contact = false;
+    if (bed.height() > 0.0 && bed.y0 <= box.y1 + 1.0 &&
+        bed.height() > p_.contact_max_h_ratio * est_h) {
+        thick_contact = true;
+        bed = V2Band{};
+    }
+
     double vertical_run = 0.0;
     const std::optional<double> px_per_m =
         scale_from_vertical(work, box, window, scale, &vertical_run);
@@ -725,7 +751,7 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
         hoist_flag = hoist_cues.hoist_high || spreader_cues.contact;
     }
 
-    const double est_h = std::max(60.0, box.y0 - 0.05 * work.height);
+    // (est_h 在"贴合亮带厚度门"处已算好,此处复用。)
     // 箱底贴近画面底边时,若仍跳过 7% 箱高,动态 ROI 会整段落到画面外,
     // 平车车面边梁/地板线看不到(近距 192 px 帧:箱底 y=170,底部只剩
     // 21 px)。此时只留 2 px 保护带,与 Python 同口径。
@@ -845,10 +871,13 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
     // 侧视平车(X70A)的箱底与车面直接贴合:车面边梁就在箱底下沿,
     // 动态 ROI 从箱底下方 7% 箱高开始,边梁会落在 ROI 之外,Hough 水平线
     // 通道看不到它(实拍图 deck=False、gap 被错取成 62.9 px → weak_evidence)。
-    // 这里补一条“贴合车面”证据:箱底下沿紧邻一条**足够厚**的亮带(车面,
-    // 不是 A 箱底下沿 5~8 px 的窄亮边),且门板数 ≤4、下半幅不是连续地面。
-    // 只有三者同时成立才把 gap 归零并置 deck;A/B 的窄边和误框都不会命中。
-    const double min_contact_h = std::max(6.0, 0.03 * work.height);
+    // 这里补一条“贴合车面”证据:箱底下沿紧邻一条**薄亮边**(车面边梁;
+    // 地面/下层箱顶/月台是厚亮面,由 contact_max_h_ratio 排除),
+    // 且门板数 ≤4、下半幅不是连续地面。
+    // P0-Q3:薄边门限取 1.5% 画幅(至少 4 px)。旧值 3% 在 720p 下要 ≥21.6 px,
+    // 会把侧视 X70 的 8~9 px 车面边梁排除,只剩厚亮面(地面/箱顶)能命中 ——
+    // 方向刚好反了。A 的 5~8 px 箱底下侧梁仍低于门限,不会误判。
+    const double min_contact_h = std::max(4.0, 0.015 * work.height);
     V2Band contact_band;
     for (const V2Band& b : bright) {
         if (b.y0 >= box.y1 - 1.0 && b.y0 < box.y1 + 1.0 &&
@@ -856,8 +885,14 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
             contact_band = b;
         }
     }
+    // P0-Q3:贴合亮带也必须是"薄边"。地面/下层箱顶/月台是厚亮面,
+    // 只靠"箱底紧邻亮带"会把地面堆料判成平车(现场合成 ground 场景实测过)。
+    if (contact_band.height() > 0.0 &&
+        contact_band.height() > p_.contact_max_h_ratio * est_h) {
+        contact_band = V2Band{};
+    }
     const bool flat_contact =
-        contact_band.height() > 0.0 &&
+        !thick_contact && contact_band.height() > 0.0 &&
         static_cast<int>(posts.size()) <= p_.flat_max_door_posts &&
         opacity >= p_.min_wall_opacity &&
         // 近距/落位帧车面本身占满动态 ROI,分块“地面样”会偏低,
@@ -869,6 +904,46 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
         deck_edge = true;
     }
 
+    // P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。
+    // 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。
+    // 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。
+    bool under_deck = false;
+    if (bed.height() > 0.0) {
+        const auto row_mean = [&](int x0, int x1, int y0, int y1) -> double {
+            x0 = std::max(0, std::min(x0, work.width));
+            x1 = std::max(x0, std::min(x1, work.width));
+            y0 = std::max(0, std::min(y0, work.height));
+            y1 = std::max(y0, std::min(y1, work.height));
+            if (x1 <= x0 || y1 <= y0) { return 0.0; }
+            double sum = 0.0;
+            long long n = 0;
+            for (int y = y0; y < y1; ++y) {
+                for (int x = x0; x < x1; ++x) {
+                    sum += static_cast<double>(work.at(x, y));
+                    ++n;
+                }
+            }
+            return n > 0 ? sum / static_cast<double>(n) : 0.0;
+        };
+        const double band_mean = row_mean(
+            window[0], window[2], static_cast<int>(std::lround(bed.y0)),
+            static_cast<int>(std::lround(bed.y1)));
+        const int probe_h = std::max(
+            2, static_cast<int>(std::lround(p_.under_deck_min_h_ratio * work.height)));
+        const int search_h = std::max(
+            probe_h + 1,
+            static_cast<int>(std::lround(p_.under_deck_search_h_ratio * work.height)));
+        const int probe_y0 = std::max(0, static_cast<int>(std::lround(bed.y1)));
+        const int probe_y1 = std::min(work.height - 1, probe_y0 + search_h);
+        double darkest = std::numeric_limits<double>::max();
+        for (int y = probe_y0; y + probe_h <= probe_y1; ++y) {
+            darkest = std::min(darkest, row_mean(window[0], window[2], y, y + probe_h));
+        }
+        under_deck = darkest < std::numeric_limits<double>::max() &&
+                     darkest <= band_mean - p_.under_deck_dark_delta;
+    }
+    deck_edge = deck_edge && under_deck;
+
     std::optional<double> gap_px;
     if (bed.height() > 0.0) {
         gap_px = std::max(0.0, (bed.y0 - box.y1) / std::max(scale, 1e-6));
@@ -878,9 +953,12 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
         gap_m = *gap_px / *px_per_m;
     }
 
+    const double post_spacing_px_orig =
+        spacing_median.has_value() ? *spacing_median / std::max(scale, 1e-6) : 0.0;
     const ClassifyResult cls = classify(
         static_cast<int>(posts.size()), spacing_cv, opacity, ground, deck_edge, 0, gap_px,
-        still, p_.view, crop.height / std::max(scale, 1e-6));
+        still, p_.view, crop.height / std::max(scale, 1e-6), under_deck,
+        post_spacing_px_orig, diagonal);
     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);
@@ -904,6 +982,7 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
     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;

+ 58 - 8
cpp/tests/selftest_edge_v2.cpp

@@ -81,16 +81,18 @@ portcv::GrayImage flat_scene(int gap_px = 4) {
 }
 
 portcv::GrayImage flat_contact_scene() {
-    // 侧视 X70A:箱底与车面直接贴合(gap=0),车面亮带紧贴箱底;
+    // 侧视 X70A:箱底与车面直接贴合(gap=0),车面边梁紧贴箱底;
     // 动态 ROI 从箱底下方开始,因此边梁本身落在 ROI 外。用于防止
     // “贴合时跳过相邻亮带 → gap 误取 60+ px → 255”的回归。
+    // P0-Q3:边梁按**薄边**建(8 px)+ 下方暗带(车底空隙/阴影)——
+    // 与现场 746×192 侧视帧同形态;厚亮面(地面/下层箱顶)由负样本覆盖。
     portcv::GrayImage img(1280, 720, 120);
     fill_rect(&img, 0, 40, 1280, 392, 185);
     fill_rect(&img, 0, 392, 1280, 404, 55);
-    fill_rect(&img, 0, 404, 1280, 470, 150);
-    fill_rect(&img, 0, 470, 1280, 500, 70);
+    fill_rect(&img, 0, 404, 1280, 412, 225);
+    fill_rect(&img, 0, 412, 1280, 442, 30);
     // 地面用均匀灰(本用例只验证“贴合车面”与 gap 取值;真实地面纹理另测)。
-    fill_rect(&img, 0, 500, 1280, 720, 110);
+    fill_rect(&img, 0, 442, 1280, 720, 110);
     return img;
 }
 
@@ -105,6 +107,37 @@ portcv::GrayImage hoist_scene() {
     return img;
 }
 
+/// 箱直接坐地:箱底以下是低对比、连续的地面(P0-Q3 负样本)。
+portcv::GrayImage ground_scene() {
+    portcv::GrayImage img(1280, 720, 120);
+    fill_rect(&img, 0, 40, 1280, 392, 185);
+    fill_rect(&img, 0, 392, 1280, 404, 55);
+    for (int y = 404; y < 720; ++y) {
+        for (int x = 0; x < 1280; ++x) {
+            img.set(x, y, static_cast<uint8_t>(100 + ((x * 7 + y * 3) % 12)));
+        }
+    }
+    return img;
+}
+
+/// 箱底紧贴一块**厚亮面**(地面/下层箱顶/月台)——旧版 flat_contact 会判 2。
+portcv::GrayImage thick_contact_scene() {
+    portcv::GrayImage img = ground_scene();
+    fill_rect(&img, 0, 404, 1280, 450, 165);
+    return img;
+}
+
+/// 上层箱坐在下层箱上:下层箱顶亮面 + 侧壁瓦楞(无斜撑)——旧版会判 1。
+portcv::GrayImage stacked_scene() {
+    portcv::GrayImage img = ground_scene();
+    fill_rect(&img, 0, 404, 1280, 450, 165);
+    fill_rect(&img, 0, 450, 1280, 720, 140);
+    for (int x = 60; x < 1280; x += 118) {
+        fill_rect(&img, x, 450, x + 6, 700, 95);
+    }
+    return img;
+}
+
 portcv::V2CommitParams fast_commit() {
     portcv::V2CommitParams p;
     p.stable_frames = 3;
@@ -198,10 +231,7 @@ int main() {
     {
         EdgeV2 ev(p, fast_commit());
         const auto r = ev.analyze(bed_scene(18), 0.0);
-        std::printf("       A: %s roi=[%d,%d,%d,%d] edges=%d segs=%d vrun=%d box_bottom=%.1f bed_top=%.1f\n",
-                    r.evidence_summary().c_str(), r.below_roi[0], r.below_roi[1],
-                    r.below_roi[2], r.below_roi[3], r.edge_pixels, r.line_segments,
-                    r.vertical_runs, r.box_bottom_y.value_or(-1.0), r.bed_top_y.value_or(-1.0));
+        std::printf("       A: %s diag=%d\n", r.evidence_summary().c_str(), r.diagonal_braces);
         check(r.state == 1, "A-like synthetic -> state 1");
         check(r.door_posts >= 5, "A-like has >=5 door posts");
         check(!r.hoist_high, "A-like is not flagged hoist_high");
@@ -224,6 +254,26 @@ int main() {
         check(r.gap_px.has_value() && *r.gap_px <= 2.0,
               "contact flatbed gap stays at box bottom (<=2px)");
     }
+    // ---------------- P0-Q3:地面/堆料/堆叠箱负样本 ----------------
+    {
+        EdgeV2 ev(p, fast_commit());
+        const auto r = ev.analyze(ground_scene(), 0.0);
+        std::printf("       ground: %s\n", r.evidence_summary().c_str());
+        check(r.state != 1 && r.state != 2, "box on ground is never 1/2");
+    }
+    {
+        EdgeV2 ev(p, fast_commit());
+        const auto r = ev.analyze(thick_contact_scene(), 0.0);
+        std::printf("       thick-contact: %s\n", r.evidence_summary().c_str());
+        check(r.state != 1 && r.state != 2, "thick contact plane is not flatbed");
+        check(!r.deck_edge, "thick contact plane does not set deck_edge");
+    }
+    {
+        EdgeV2 ev(p, fast_commit());
+        const auto r = ev.analyze(stacked_scene(), 0.0);
+        std::printf("       stacked: %s\n", r.evidence_summary().c_str());
+        check(r.state != 1 && r.state != 2, "stacked container is not bed/flatbed");
+    }
     // ---------------- 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 48 通过 / 0 失败(含 P0-0 吊具高悬 / 夹箱门)
+#        portcv_edge_v2_selftest 52 通过 / 0 失败(含 P0-0 吊具高悬 / 夹箱门、P0-Q3 地面/堆料负样本)
 #
 #   不想逐条敲?一条命令跑完四层(ctest + Python 单测 + v1/v2 现场回放):
 #        python scripts/regression_freeze.py --build-dir build

+ 21 - 0
docs/edge_evidence.md

@@ -599,6 +599,27 @@ python scripts/replay_check.py runs/v2gate_B4.jsonl --images runs/_v2gate_B4
   `gaussian3x3`;`abstain_reason` 区分了两种原因(Python 一律 `hoist_high`),判据不变。
 * A/B 正样本实测命中 **0/109 帧**(不误弃权),合成高悬帧 6 帧 **0 commit**。
 
+**⑥ P0-Q3 地面/堆料误判(2026-11-18,已收紧)**
+
+* 现象:内置合成 `source.type=synth --source-uri ground`(箱直接坐地)在 v2 下被
+  `flat_contact` 判成 `2`(`bed` 亮带 = 地面亮面、`gap=0`)并 **commit**;
+  `portcv_run` 最终快照 `state=2 flags=0x00C7`(`RESULT_VALID+STABLE`)。
+* 处置(**只收紧,不放宽**):
+  * `2` 的车面亮带必须是**薄边**(`contact_max_h_ratio=0.12 × 估箱高`);
+  * 亮带下方必须有**更暗的带**(`under_deck_*`,≥12 灰阶)——即车底空隙/阴影;
+  * `1` 增加门板立柱间距下限 `min_post_spacing_px=24`(容器瓦楞 10~20 px),
+    且**贴合形态**(`gap≤1 px`)需 `min_diagonal_braces=1` 条斜撑。
+* 结果:合成 `ground` 由 `2` → **`255`**(`deck=0 under_deck=0`),
+  A/B 合成正样本仍分别 `1/2`;新增 Python 3 项 + C++ 4 项负样本回归
+  (`portcv_edge_v2_selftest` 52/0)。
+* **代价(必须写进验收)**:远距/遮挡/贴底帧的 `2` 召回会下降(更多 `255`),
+  B 现场片段需按新门复跑后再决定 `allow_state2`;`0` 类真实负样本仍缺,
+  本修复只保证"地面/堆料不判 1/2",不等于 `0` 的召回验收。
+* **仍未覆盖**:箱**已坐进敞车车斗内**(箱底低于墙顶、近侧墙遮挡)的合成
+  `gondola` 场景仍可能给出 `2`(`posts=2 opacity=0.71 gap=0 under_deck=1`)。
+  这是 `docs/route_v2.md` §6.4 #2 已声明的未验证形态;现场应依赖 **T1 窗口**
+  (箱还在围挡上方时判定)或 PLC "到位/吊具松开"信号,不能只靠落位后的单帧。
+
 ---
 
 ## 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 单测(330 项,约 6 s) |
+| 提交钩子 | `.githooks/pre-commit`:跑 L1 单测(333 项,约 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 单元测试(330 项)
+# 2) L1 单元测试(333 项)
 python -m unittest discover -s tests -q
 
 # 3) L2 契约自检(C++ 侧 8 组 1128 项断言)

+ 16 - 2
docs/route_v2.md

@@ -280,6 +280,17 @@ PLC 若只看 `state`,会把“保持的 0”误当成“已确认不在车上
 * 敞车(有墙):若同时出现门板/墙,判 `1`,不判 `2`。
 * 箱在地面:地面连续、无边梁+转向架 → `0`。
 
+> **P0-Q3 实现补充(2026-11-18)**:代码里的 `2` 还要求两条**硬门**:
+> ① 车面亮带是**薄边**(≤ `contact_max_h_ratio` × 估箱高,默认 0.12)——
+> 地面 / 下层箱顶 / 月台 / 货台是厚亮面,直接排除;
+> ② 亮带下方 `under_deck_search_h_ratio` × 画幅内存在一条**更暗的带**
+> (车底空隙 / 阴影,≥ `under_deck_dark_delta` 灰阶)。
+> 两条任一不成立 → 内部 `255`,**不判 2**。这是**收紧**:地面堆料不再判 2,
+> 代价是部分远距 / 遮挡帧弃权(宁可 255)。
+> `1` 侧同时增加:门板立柱间距 ≥ `min_post_spacing_px`(默认 24 px,
+> 容器瓦楞 10~20 px 不够)、**贴合形态**(`gap ≤1 px`)必须有 `min_diagonal_braces`
+> 条斜撑(容器瓦楞没有斜撑)。
+
 ### 4.3 `0`(其他)主证据:没有铁路车体结构
 
 * 箱底以下只有地面/堆场/卡车/其他箱,**没有**:
@@ -301,6 +312,7 @@ PLC 若只看 `state`,会把“保持的 0”误当成“已确认不在车上
 | --- | --- | --- |
 | `1` 与 `2` 证据同时强 | 冲突 → 255 | 保持上一稳定值;flags 0/0 |
 | 只有 `2` 的弱证据(边梁但无车轮/地面) | 255(安全铁律) | 保持;**绝不落 2** |
+| 箱在地面/堆料/下层箱顶(贴合亮面但无车底空隙) | 255(P0-Q3) | 保持;**绝不落 2** |
 | 只有 `1` 的弱证据(单根立柱/单块门板) | 255 | 保持;不硬判 1 |
 | 箱体/车体被遮挡、运动模糊 | 255 | 保持;`MOTION`/`STABLE=0` |
 | 视角未知 | 255 | 保持;不混用阈值 |
@@ -344,6 +356,7 @@ P1 的 `commit` 模块必须结合:
 | `wall.rect_doors` / `diagonal_braces` | 口/八 候选数 |
 | `wall.opacity` | 箱底以下不透明墙占比(C1 的 v2 版) |
 | `flat.deck_edge` / `flat.wheel_count` / `flat.ground_ratio` | 车面边梁/车轮/地面 |
+| `flat.under_deck` | 车面亮带下方是否有暗带(P0-Q3;`2` 的硬门) |
 | `phase` / `commit` | T1/T2/T3、commit 是否成立 |
 | `abstain_reason` | 内部 255 的原因(不写 PLC) |
 
@@ -542,11 +555,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` **229 OK**(2026-11-03)、`portcv_v2_selftest` **54/0**、`ctest` **8/8**。
+> `python -m unittest discover` **333 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` **48/48**(含 P0-0 吊具高悬 / 夹箱门与"远距 ROI 弃权"回归)。
+> `portcv_edge_v2_selftest` **52/52**(含 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 帧,见
@@ -736,6 +749,7 @@ else:
 
 | 日期 | 变更 |
 | --- | --- |
+| 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`"门。新增地面/堆料/堆叠箱负样本: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 条件通过 |
 | 2026-10-19 | **C++ `edge_v2` 对齐完成**:修复 ROI 过平滑(去掉 INTER_AREA 前的中值/高斯、`horizontal_bands` 改回 Python 的 3×3 高斯 + 行均值中心差分)、竖棱游程通道长度门 0.60×ROI、平车杂波规则性门、车面边梁断线合并;A1 49/50 判 1、B 无 false 1(9 帧判 2)、B1 20/20 弃权;C++ 17/17、Python 142 OK |

+ 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` | **48 通过 / 0 失败**(含 P0-0 吊具高悬 / 夹箱门、远距 ROI 弃权、`allow_state2` 回退) |
+| v2 证据自检 | `portcv_edge_v2_selftest` | **52 通过 / 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 330、v1 回放 4 份(`A_s2` 按白名单恰好 1 条已知 FAIL)、v2 回放 2 份;缺产物 / 多一条失败即非 0 退出,绝不静默跳过(`runs/_freeze.txt`) |
+| **冻结点回归(一条命令)** | `python scripts/regression_freeze.py` | **8 组全绿**:ctest 8/8、unittest 333、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 项全部通过(当时口径;当前主线为 330 项,见 `docs/stability_soak.md`)。
+- 单测 `python -m unittest discover -s tests -t .` 共 184 项全部通过(当时口径;当前主线为 333 项,见 `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 .` | **330 项全绿**(本机 6.0 s,2026-11-16 复核) |
+| Python 回归 | `python -m unittest discover -s tests -t .` | **333 项全绿**(本机 ~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` 48/0(合成高悬帧 6 帧 0 commit、注入路径、门关闭对照)+ `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` 52/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` → **229 项通过**(含新增 `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` → **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` 用例)。
 > 真实视频回归因原始 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` 等为**一次性调参/看图脚本,明确列为非交付物**,不得写进验收步骤。
 

+ 8 - 0
portcv/config.py

@@ -115,6 +115,8 @@ DEFAULTS: Dict[str, Any] = {
         "flat_max_door_posts": 4,
         "max_post_spacing_cv": 6.0,
         "min_post_len_ratio": 0.30,
+        "min_post_spacing_px": 24.0,  # P0-Q3:门板立柱间距下限(原图像素);容器瓦楞 10~20 px
+        "min_diagonal_braces": 1,     # P0-Q3:敞车必须有"八"字斜撑;容器瓦楞没有
         "min_wall_opacity": 0.35,
         "max_flat_gap_px": 40.0,
         "wall_edge_density_ref": 0.14,
@@ -125,6 +127,12 @@ DEFAULTS: Dict[str, Any] = {
         "min_flat_ground_ratio": 0.40,
         "min_zero_ground_ratio": 0.65,
         "deck_min_len_ratio": 0.30,
+        # P0-Q3:2(平车)必须是"薄车面边梁 + 车面下方暗带";
+        # 箱底紧贴的亮带太厚(地面/下层箱顶/月台)→ 不当作车面、不判 2。
+        "contact_max_h_ratio": 0.12,
+        "under_deck_dark_delta": 12.0,
+        "under_deck_min_h_ratio": 0.01,
+        "under_deck_search_h_ratio": 0.10,
         "box_height_m": 2.591,
         "px_per_m": 0.0,              # 0 = 用箱体竖棱自标尺
         "min_scale_px": 60.0,

+ 125 - 7
portcv/logic/evidence_v2.py

@@ -5,9 +5,11 @@
 ``docs/route_v2.md`` §2–§4 与 P0 实测(``docs/evidence/p0_v2``):
 
 * **1(敞车)**:箱底以下是一整面不透明侧墙,门板立柱 ``8–14`` 根、
-  立柱间距有规律,斜撑/矩形门可作加分;
+  立柱间距有规律,斜撑/矩形门可作加分;**贴合形态**(箱底与墙顶/箱顶贴住)
+  必须有"八"字斜撑,防"上层箱坐在下层箱上"被判 1;
 * **2(平车)**:箱底以下只有薄车面边梁,下方透空,能看到地面/植被;
-  门板立柱 ``0–4`` 根;
+  门板立柱 ``0–4`` 根;**边梁必须是薄边,且下方有车底空隙/阴影暗带**,
+  否则地面/堆料/下层箱顶会被误判 2;
 * **0(其他)**:只有连续地面,既无门板阵列也无可信车面边梁。
 
 与 v1 的区别
@@ -93,6 +95,14 @@ class EvidenceV2Params:
     flat_max_door_posts: int = 4
     max_post_spacing_cv: float = 6.0
     min_post_len_ratio: float = 0.30
+    # P0-Q3:门板立柱间距下限(**原图像素**)。容器侧壁瓦楞周期通常 10~20 px,
+    # C70 门板立柱 63~185 px(docs/edge_evidence.md §4.1)→ 低于该值不构成门板阵列。
+    # 没有这条时,"上层箱坐在下层箱上"会把下层箱的瓦楞当成车斗门板 → 误判 1。
+    min_post_spacing_px: float = 24.0
+    # P0-Q3:`1`(敞车)还必须有"八"字斜撑/三角撑证据(docs/edge_evidence.md §4.1)。
+    # 容器侧壁只有瓦楞、没有斜撑 → 防"上层箱坐在下层箱上"被判成敞车。
+    # 0 = 关闭该门(只用于对照实验,现场不要关)。
+    min_diagonal_braces: int = 1
     min_wall_opacity: float = 0.35
     max_flat_gap_px: float = 40.0
     wall_edge_density_ref: float = 0.14
@@ -103,6 +113,15 @@ class EvidenceV2Params:
     min_flat_ground_ratio: float = 0.40
     min_zero_ground_ratio: float = 0.65
     deck_min_len_ratio: float = 0.30
+    # P0-Q3:`2`(平车)必须是"薄车面边梁 + 车面下方暗带"。
+    # 箱底紧贴的亮带若比 contact_max_h_ratio × 估箱高更厚,它不是车面边梁,
+    # 而是地面 / 下层箱顶 / 月台 / 货台等大平面 → 不当作车面、不判 2。
+    contact_max_h_ratio: float = 0.12
+    # 车面亮带下方必须在 under_deck_search_h_ratio × 画幅内找到一条更暗的
+    # under_deck_min_h_ratio × 画幅高的带(车底空隙/阴影);找不到 → 不判 2。
+    under_deck_dark_delta: float = 12.0
+    under_deck_min_h_ratio: float = 0.01
+    under_deck_search_h_ratio: float = 0.10
     box_height_m: float = 2.591
     px_per_m: float = 0.0
     min_scale_px: float = 60.0
@@ -134,6 +153,18 @@ class EvidenceV2Params:
             raise ValueError("below_height_ratio 必须为正")
         if self.min_door_posts < 1:
             raise ValueError("min_door_posts 至少 1")
+        if not 0.0 < self.contact_max_h_ratio <= 0.5:
+            raise ValueError("contact_max_h_ratio 必须在 (0,0.5]")
+        if self.under_deck_dark_delta < 0.0:
+            raise ValueError("under_deck_dark_delta 不能为负")
+        if not 0.0 < self.under_deck_min_h_ratio <= 0.1:
+            raise ValueError("under_deck_min_h_ratio 必须在 (0,0.1]")
+        if not 0.0 < self.under_deck_search_h_ratio <= 0.5:
+            raise ValueError("under_deck_search_h_ratio 必须在 (0,0.5]")
+        if self.min_post_spacing_px < 0.0:
+            raise ValueError("min_post_spacing_px 不能为负")
+        if self.min_diagonal_braces < 0:
+            raise ValueError("min_diagonal_braces 不能为负")
         if self.box_height_m <= 0.0:
             raise ValueError("box_height_m 必须为正")
 
@@ -161,6 +192,8 @@ class EvidenceV2Params:
             flat_max_door_posts=int(raw.get("flat_max_door_posts", 4)),
             max_post_spacing_cv=float(raw.get("max_post_spacing_cv", 6.0)),
             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_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)),
             wall_edge_density_ref=float(raw.get("wall_edge_density_ref", 0.14)),
@@ -171,6 +204,10 @@ class EvidenceV2Params:
             min_flat_ground_ratio=float(raw.get("min_flat_ground_ratio", 0.40)),
             min_zero_ground_ratio=float(raw.get("min_zero_ground_ratio", 0.65)),
             deck_min_len_ratio=float(raw.get("deck_min_len_ratio", 0.30)),
+            contact_max_h_ratio=float(raw.get("contact_max_h_ratio", 0.12)),
+            under_deck_dark_delta=float(raw.get("under_deck_dark_delta", 12.0)),
+            under_deck_min_h_ratio=float(raw.get("under_deck_min_h_ratio", 0.01)),
+            under_deck_search_h_ratio=float(raw.get("under_deck_search_h_ratio", 0.10)),
             box_height_m=float(raw.get("box_height_m", 2.591)),
             px_per_m=float(raw.get("px_per_m", 0.0)),
             min_scale_px=float(raw.get("min_scale_px", 60.0)),
@@ -210,6 +247,7 @@ class EvidenceV2Result:
     diagonal_braces: int = 0
     wall_opacity: float = 0.0
     deck_edge: bool = False
+    under_deck: bool = False
     wheel_count: int = 0
     ground_ratio: float = 0.0
     phase: CommitPhase = CommitPhase.T1
@@ -252,11 +290,13 @@ 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 gap=%s commit=%s hoist=%d" % (
+        reason = "v2:%s view=%s posts=%d opacity=%.2f deck=%d under_deck=%d gap=%s commit=%s hoist=%d" % (
             "ok" if ok else "abstain",
             self.view.value,
             int(self.door_posts),
             float(self.wall_opacity),
+            int(bool(self.deck_edge)),
+            int(bool(self.under_deck)),
             "n/a" if self.gap_px is None else "%.0fpx" % self.gap_px,
             self.commit_reason,
             int(bool(self.hoist_high)),
@@ -292,6 +332,7 @@ class EvidenceV2Result:
             "diagonal_braces": int(self.diagonal_braces),
             "wall_opacity": round(float(self.wall_opacity), 3),
             "deck_edge": bool(self.deck_edge),
+            "under_deck": bool(self.under_deck),
             "wheel_count": int(self.wheel_count),
             "ground_ratio": round(float(self.ground_ratio), 3),
             "phase": self.phase.value,
@@ -325,6 +366,19 @@ def _to_gray(image: np.ndarray) -> np.ndarray:
     return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
 
+def _row_mean(gray: np.ndarray, x0: int, x1: int, y0: int, y1: int) -> float:
+    """``[x0,x1) × [y0,y1)`` 的灰度均值(越界自动钳制;空框返回 0)。"""
+
+    h, w = gray.shape[:2]
+    xa = max(0, min(int(x0), w))
+    xb = max(xa, min(int(x1), w))
+    ya = max(0, min(int(y0), h))
+    yb = max(ya, min(int(y1), h))
+    if xb <= xa or yb <= ya:
+        return 0.0
+    return float(gray[ya:yb, xa:xb].mean())
+
+
 def horizontal_bands(
     gray: np.ndarray,
     roi: Tuple[int, int, int, int],
@@ -855,25 +909,50 @@ class EvidenceV2:
         gap_px: Optional[float],
         motion_ok: bool,
         view: ViewMode,
+        under_deck: bool = False,
+        post_spacing_px: Optional[float] = None,
+        diagonal_braces: int = 0,
     ) -> Tuple[int, float, float, str]:
-        """返回 ``(state, confidence, structure_hits, reason)``。"""
+        """返回 ``(state, confidence, structure_hits, reason)``。
+
+        ``under_deck``:车面亮带下方是否找到"车底空隙/阴影"暗带(P0-Q3)。
+        ``post_spacing_px``:门板立柱间距(**原图像素**);容器瓦楞 10~20 px,
+        C70 门板 63~185 px。``None``/``<=0`` 表示不可用(不因此拒绝)。
+        """
 
         if view == ViewMode.UNKNOWN:
             return int(SceneState.UNKNOWN), 0.0, 0.0, "view_unknown"
         if not motion_ok:
             return int(SceneState.UNKNOWN), 0.0, 0.0, "motion"
 
+        spacing_ok = (
+            post_spacing_px is None
+            or float(post_spacing_px) <= 0.0
+            or float(post_spacing_px) >= self.p.min_post_spacing_px
+        )
+        # P0-Q3:只在"箱底与车面/箱顶贴合"(gap<=1px)时才要求"八"字斜撑。
+        # 真实 C70 在 T1 窗口箱底高于墙顶(A ≈25 px),不应因斜撑不可见被弃权;
+        # 而"上层箱坐在下层箱上/箱直接坐地"是贴合形态,必须有门板结构才判 1。
+        contact_bed = gap_px is None or float(gap_px) <= 1.0
+        doors_ok = (not contact_bed) or (
+            int(diagonal_braces) >= self.p.min_diagonal_braces
+        )
         bed_strong = (
             self.p.min_door_posts <= posts <= self.p.max_door_posts
             and opacity >= self.p.min_wall_opacity
             and (gap_px is None or gap_px <= self.p.max_bed_gap_px)
             and (spacing_cv is None or spacing_cv <= self.p.max_post_spacing_cv)
+            and spacing_ok
+            and doors_ok
         )
-        # 平车:没有门板阵列 + 箱底下有可见车面边梁。地面比例只作置信度加分:
-        # B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。
+        # 平车:没有门板阵列 + 箱底下有可见车面边梁 + 边梁下方有"车底空隙/阴影"。
+        # `under_deck` 是 P0-Q3 加的硬门:地面/堆场/下层箱顶只有亮面,
+        # 找不到这条暗带 → 不判 2(宁可 255,绝不允许把地面堆料当平车)。
+        # 地面比例只作置信度加分:B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。
         flat_strong = (
             posts <= self.p.flat_max_door_posts
             and deck
+            and under_deck
             and (gap_px is None or gap_px <= self.p.max_flat_gap_px)
         )
 
@@ -989,6 +1068,16 @@ class EvidenceV2:
             below = [b for b in bright if b.y0 >= box.y1 - 1.0]
             bed = min(below, key=lambda b: b.y0) if below else None
 
+        # P0-Q3:箱底紧贴的亮带若"太厚",它不是车面边梁,而是地面/下层箱顶/
+        # 月台/货台等大平面。把它当车面会在地面堆料场景误判 2(验收口径里
+        # `2` 的误报优先级最高)。厚度门以"估箱高"为基准,避免受分辨率影响。
+        est_h = max(60.0, box.y0 - 0.05 * wh)
+        thick_contact = False
+        if bed is not None and bed.y0 <= box.y1 + 1.0:
+            if (bed.y1 - bed.y0) > self.p.contact_max_h_ratio * est_h:
+                thick_contact = True
+                bed = None
+
         px_per_m, vertical_run = self._scale_from_vertical(gray, box, window, scale)
         box_h_px = None
         if px_per_m is not None:
@@ -1065,7 +1154,7 @@ class EvidenceV2:
                 hoist_cues["source"] = "image_rows"
 
         # 动态 ROI:y 从本帧箱底下沿开始,绝不复用 P0 固定 y=475..619。
-        est_h = max(60.0, box.y0 - 0.05 * wh)
+        # (est_h 在"贴合亮带厚度门"处已算好,此处复用。)
         # 起点要越过箱体下侧梁/车体上缘的强横线:从箱底下方约 7% 箱高开始。
         # 但若箱底已经贴近画面底边,剩余高度不足以再跳过 7%,就只留 2 px
         # 保护带。否则整段动态 ROI 会落到画面外,平车的车面边梁/地板线
@@ -1117,6 +1206,26 @@ class EvidenceV2:
             for seg in structure.get("horizontal", [])  # type: ignore[union-attr]
         )
         wheels = self._wheel_count(gray, below_work, scale)
+        # P0-Q3:`2` 必须"薄车面边梁 + 车面下方暗带(车底空隙/阴影)"。
+        # 地面/堆场/下层箱顶只有连续亮面,找不到这条暗带 → deck 不成立 → 不判 2。
+        # 这里是**收紧**:找不到暗带时宁可 255,也不猜成平车(验收口径:误报优先)。
+        under_deck = False
+        if bed is not None and (bed.y1 - bed.y0) > 0.0:
+            band_mean = _row_mean(gray, window[0], window[2], bed.y0, bed.y1)
+            probe_h = max(2, int(round(self.p.under_deck_min_h_ratio * wh)))
+            search_h = max(probe_h + 1, int(round(self.p.under_deck_search_h_ratio * wh)))
+            probe_y0 = max(0, int(round(bed.y1)))
+            probe_y1 = min(wh - 1, probe_y0 + search_h)
+            darkest = None
+            for y in range(probe_y0, max(probe_y0 + 1, probe_y1 - probe_h + 1)):
+                value = _row_mean(gray, window[0], window[2], y, y + probe_h)
+                if darkest is None or value < darkest:
+                    darkest = value
+            under_deck = (
+                darkest is not None
+                and darkest <= band_mean - self.p.under_deck_dark_delta
+            )
+        deck_edge = bool(deck_edge and under_deck)
         gap_px = None
         if bed is not None:
             gap_px = max(0.0, (bed.y0 - box.y1) / max(scale, 1e-6))
@@ -1131,6 +1240,12 @@ class EvidenceV2:
             gap_px=gap_px,
             motion_ok=motion_ok,
             view=self.p.view,
+            under_deck=under_deck,
+            post_spacing_px=(
+                None if spacing_median is None
+                else float(spacing_median) / max(scale, 1e-6)
+            ),
+            diagonal_braces=int(structure["diagonal_lines"]),
         )
         gap_m = (
             None if gap_px is None or px_per_m is None or px_per_m <= 0.0
@@ -1171,6 +1286,7 @@ class EvidenceV2:
             diagonal_braces=int(structure["diagonal_lines"]),
             wall_opacity=opacity,
             deck_edge=bool(deck_edge),
+            under_deck=bool(under_deck),
             wheel_count=int(wheels),
             ground_ratio=ground,
             phase=phase,
@@ -1192,6 +1308,8 @@ class EvidenceV2:
                 "class_reason": reason,
                 "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),
+                "thick_contact": bool(thick_contact),
                 "vertical_run_px": None if vertical_run is None else round(vertical_run / scale, 2),
                 "motion_diff": round(motion_diff, 2),
                 "motion_ratio": round(motion_ratio, 3),

+ 65 - 0
tests/test_evidence_v2.py

@@ -92,6 +92,48 @@ def make(params: EvidenceV2Params, tracker: CommitTracker | None = None) -> Evid
     return EvidenceV2(params, tracker)
 
 
+def ground_scene(*, low: int = 95, high: int = 115, noise: int = 4) -> np.ndarray:
+    """箱直接坐地:箱底以下是低对比、连续的地面(水泥地/砂石)。
+
+    P0-Q3 回归用:这种画面**绝不能**被判成 2(平车)或 1(敞车)。
+    """
+
+    h, w = 720, 1280
+    image = np.full((h, w), 120, dtype=np.uint8)
+    image[40:392, :] = 185
+    image[392:404, :] = 55  # 箱底暗带
+    rng = np.random.default_rng(20261118)
+    ramp = np.linspace(low, high, h - 404).reshape(-1, 1)
+    jitter = rng.integers(-noise, noise + 1, size=(h - 404, w))
+    image[404:, :] = np.clip(ramp + jitter, 0, 255).astype(np.uint8)
+    return image
+
+
+def thick_contact_scene() -> np.ndarray:
+    """箱底紧贴一块**厚亮面**(地面/下层箱顶/月台),下方仍是地面。
+
+    旧版 C++ `flat_contact` 会把这块厚亮面当车面 → 2;本用例锁住该回归。
+    """
+
+    image = ground_scene()
+    image[404:450, :] = 165  # 46 px 厚亮面(估箱高 ≈356 px → 0.13 > 0.12)
+    return image
+
+
+def stacked_scene() -> np.ndarray:
+    """上层箱坐在下层箱上:下层箱顶亮面 + 侧壁瓦楞(无斜撑)。
+
+    旧版会把瓦楞当门板立柱、把箱顶亮面当车面 → 1;本用例要求 0/255。
+    """
+
+    image = ground_scene()
+    image[404:450, :] = 165  # 下层箱顶面
+    image[450:, :] = 140     # 下层箱侧壁
+    for x in range(60, 1280, 118):  # 瓦楞竖棱(≈10 根)
+        image[450:700, x:x + 6] = 95
+    return image
+
+
 class BandSelectionTests(unittest.TestCase):
     def test_pick_box_and_bed_uses_nearest_bright_below(self):
         box, bed = pick_box_and_bed(
@@ -181,6 +223,29 @@ class EvidenceClassificationTests(unittest.TestCase):
         self.assertNotEqual(r_low.below_roi[1], r_high.below_roi[1])
 
 
+class GroundStackSafetyTests(unittest.TestCase):
+    """P0-Q3:地面/堆料/堆叠箱不得被判成 1(敞车)或 2(平车)。"""
+
+    def _classify(self, image: np.ndarray):
+        ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=False))
+        return ev.analyze(image, ts=0.0)
+
+    def test_box_on_ground_is_never_bed_or_flatbed(self):
+        result = self._classify(ground_scene())
+        self.assertNotIn(result.state, (1, 2), result.to_dict())
+
+    def test_thick_contact_plane_is_not_flatbed(self):
+        # 箱底紧贴一块厚亮面(地面/下层箱顶/月台)→ 旧版 flat_contact 会判 2
+        result = self._classify(thick_contact_scene())
+        self.assertNotIn(result.state, (1, 2), result.to_dict())
+        self.assertFalse(result.deck_edge, result.to_dict())
+
+    def test_container_stacked_on_container_is_not_bed(self):
+        # 下层箱的瓦楞不是车斗门板;下层箱顶也不是车面
+        result = self._classify(stacked_scene())
+        self.assertNotIn(result.state, (1, 2), result.to_dict())
+
+
 class CommitIntegrationTests(unittest.TestCase):
     def test_uncommitted_result_maps_to_internal_255(self):
         ev = make(EvidenceV2Params(px_per_m=115.6, require_commit=True))