Преглед на файлове

feat: accept lower door-frame evidence for empty gondola

siz преди 31 минути
родител
ревизия
90cae008d1

+ 28 - 0
.gitignore

@@ -66,6 +66,34 @@ _gen/
 *.pgm
 *.ppm
 
+# 本地图片、视频、PDF:测试素材/参考资料,体积大,不入库
+*.jpg
+*.jpeg
+*.png
+*.bmp
+*.gif
+*.webp
+*.tif
+*.tiff
+*.heic
+*.pdf
+*.mp4
+*.mov
+*.avi
+*.mkv
+*.flv
+*.wmv
+*.webm
+*.m4v
+*.mpg
+*.mpeg
+*.rmvb
+*.3gp
+
+# 本地测试素材目录:图片/视频/标签/配置统一不入库
+dataset/
+testvideo/
+
 # 编辑器
 .vscode/
 .idea/

+ 5 - 1
configs/README.md

@@ -111,7 +111,11 @@ C++:`cpp/include/portcv/capture.hpp`),默认值与语义一致:
 | `evidence_v2.empty_min_wall_h_ratio` | `0.25` | 可见墙高(占画幅)下限;罐箱载车只剩 ~13% → 挡掉 |
 | `evidence_v2.empty_min_post_len_ratio` | `0.30` | 门板竖棱最短长度 ÷ 墙高(严格门) |
 | `evidence_v2.empty_fallback_max_posts` | `4` | 低分辨率有界兜底:宽松门只接受 ≤4 根立柱且跨度 ≥0.70(防载车被聚成多根后误判) |
-| `evidence_v2.empty_min_diagonal_braces` | `1` | 空车判据的斜撑门(与 `min_diagonal_braces` 分开) |
+| `evidence_v2.empty_min_diagonal_braces` | `1` | 空车判据的斜撑门(上部“八”,与 `min_diagonal_braces` 分开) |
+| `evidence_v2.empty_min_rect_doors` | `1` | 下部“口”形门框计数下限;满足时可替代斜撑门 |
+| `evidence_v2.empty_rect_without_diagonal` | `true` | 允许“下口”替代“上八”;false = 恢复旧口径(必须有斜撑) |
+| `evidence_v2.empty_rect_min_wall_h_ratio` | `0.10` | 口主导路径的可见墙高下限(旧整墙路径仍用 `empty_min_wall_h_ratio=0.25`) |
+| `evidence_v2.empty_rect_min_texture_top_ratio` | `0.62` | 口主导路径要求车体顶线位于画面下半部,避免堆场/高箱矩形误判为空车 |
 | `evidence_v2.empty_top_margin_ratio` | `0.0` | 车体顶相对窗口顶的最小余量;0 = 车填满画面时也用整个窗口 |
 | `evidence_v2.allow_state3` | `true` | 空车 `3` 是否允许提交(与 `commit.allow_state3` **串联**,任一 false 即只识别不提交) |
 | `evidence_v2.empty_flatbed_enable` | `true` | 空平车(车面裸露)也判 `3`;false = 只判空敞车 |

+ 4 - 0
configs/default.json

@@ -181,6 +181,10 @@
     "empty_min_post_len_ratio": 0.3,
     "empty_fallback_max_posts": 4,
     "empty_min_diagonal_braces": 1,
+    "empty_min_rect_doors": 1,
+    "empty_rect_without_diagonal": true,
+    "empty_rect_min_wall_h_ratio": 0.10,
+    "empty_rect_min_texture_top_ratio": 0.62,
     "empty_flatbed_enable": true,
     "empty_flatbed_min_gap_px": 16.0,
     "empty_flatbed_max_plane_edge": 0.12,

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

@@ -108,6 +108,10 @@
     "empty_min_post_len_ratio": 0.3,
     "empty_fallback_max_posts": 4,
     "empty_min_diagonal_braces": 1,
+    "empty_min_rect_doors": 1,
+    "empty_rect_without_diagonal": true,
+    "empty_rect_min_wall_h_ratio": 0.10,
+    "empty_rect_min_texture_top_ratio": 0.62,
     "empty_flatbed_enable": true,
     "empty_flatbed_min_gap_px": 16.0,
     "empty_flatbed_max_plane_edge": 0.12,

+ 4 - 0
configs/edge-v2-rtsp.json

@@ -131,6 +131,10 @@
     "empty_min_post_len_ratio": 0.3,
     "empty_fallback_max_posts": 4,
     "empty_min_diagonal_braces": 1,
+    "empty_min_rect_doors": 1,
+    "empty_rect_without_diagonal": true,
+    "empty_rect_min_wall_h_ratio": 0.10,
+    "empty_rect_min_texture_top_ratio": 0.62,
     "empty_flatbed_enable": true,
     "empty_flatbed_min_gap_px": 16.0,
     "empty_flatbed_max_plane_edge": 0.12,

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

@@ -141,6 +141,13 @@ struct EdgeV2Params {
     int empty_fallback_max_posts = 4;
     /// 空车判据的斜撑门(与 `min_diagonal_braces` 分开,便于现场按车型单独放宽)。
     int empty_min_diagonal_braces = 1;
+    /// 现场口径:下部“口”形门框一定存在,可替代非必选的上部“八”字斜撑。
+    int empty_min_rect_doors = 1;
+    bool empty_rect_without_diagonal = true;
+    /// “口主导”路径放宽的可见墙高(旧整墙路径仍用 empty_min_wall_h_ratio)。
+    double empty_rect_min_wall_h_ratio = 0.10;
+    /// 口主导路径要求车体顶线位于画面下半部,避免堆场/高箱矩形误判为空车。
+    double empty_rect_min_texture_top_ratio = 0.62;
     /// P0-Q10:空平车(平车、车面裸露)→ 也输出 state=3。
     /// 与载车的本质差别:载车必然有箱底暗带紧贴(或很近)车面边梁;空平车的
     /// “箱底”是车底板远端边缘线,与近侧边梁之间隔着整片车面(纵深 >= min_gap_px)。

+ 15 - 0
cpp/src/app_config.cpp

@@ -469,6 +469,11 @@ bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
         num("evidence_v2.empty_min_post_len_ratio", &v->empty_min_post_len_ratio),
         integer("evidence_v2.empty_fallback_max_posts", &v->empty_fallback_max_posts),
         integer("evidence_v2.empty_min_diagonal_braces", &v->empty_min_diagonal_braces),
+        integer("evidence_v2.empty_min_rect_doors", &v->empty_min_rect_doors),
+        flag("evidence_v2.empty_rect_without_diagonal", &v->empty_rect_without_diagonal),
+        num("evidence_v2.empty_rect_min_wall_h_ratio", &v->empty_rect_min_wall_h_ratio),
+        num("evidence_v2.empty_rect_min_texture_top_ratio",
+            &v->empty_rect_min_texture_top_ratio),
         flag("evidence_v2.empty_flatbed_enable", &v->empty_flatbed_enable),
         num("evidence_v2.empty_flatbed_min_gap_px", &v->empty_flatbed_min_gap_px),
         num("evidence_v2.empty_flatbed_max_plane_edge", &v->empty_flatbed_max_plane_edge),
@@ -737,6 +742,16 @@ bool validate(const AppConfig* cfg, std::string* error) {
     if (v2.empty_min_diagonal_braces < 0) {
         return bad("evidence_v2.empty_min_diagonal_braces 不能为负(0=不启用该门)");
     }
+    if (v2.empty_min_rect_doors < 0) {
+        return bad("evidence_v2.empty_min_rect_doors 不能为负");
+    }
+    if (v2.empty_rect_min_wall_h_ratio < 0.0 || v2.empty_rect_min_wall_h_ratio > 0.5) {
+        return bad("evidence_v2.empty_rect_min_wall_h_ratio 必须 ∈ [0,0.5]");
+    }
+    if (v2.empty_rect_min_texture_top_ratio < 0.0 ||
+        v2.empty_rect_min_texture_top_ratio > 1.0) {
+        return bad("evidence_v2.empty_rect_min_texture_top_ratio 必须 ∈ [0,1]");
+    }
     if (v2.empty_flatbed_min_gap_px < 0.0) {
         return bad("evidence_v2.empty_flatbed_min_gap_px 不能为负");
     }

+ 43 - 8
cpp/src/edge_v2.cpp

@@ -230,6 +230,7 @@ struct BodyEvidence {
     double span_ratio = 0.0;
     double opacity = 0.0;
     int diagonal = 0;
+    int rect_doors = 0;   ///< 下部“口”形门框(横向门框边梁计数)
     double spcv = 0.0;   ///< P0-Q11:立柱间距变异系数(门板等距;杂物不等距)
     double height = 0.0;
 };
@@ -268,6 +269,16 @@ BodyEvidence measure_body(const GrayImage& work, int x0, int y0, int x1, int y1,
             ++diagonal;
         }
     }
+    // 下部“口”形门框:侧墙下半部的横向门框边梁计数。存在下口时不强制要求
+    // 上部“八”字斜撑或完整竖棱阵列(现场车型可能只有下口)。
+    const double rect_min_len = std::max(12.0, 0.10 * static_cast<double>(crop.width));
+    for (const Segment& s : all_segs) {
+        if (std::fabs(s.angle_deg) <= 20.0 &&
+            s.length >= rect_min_len &&
+            s.cy() >= 0.40 * static_cast<double>(crop.height)) {
+            ++out.rect_doors;
+        }
+    }
     const std::vector<double> posts =
         cluster_positions(post_x, std::max(3.0, 9.0 * scale));
     out.posts = static_cast<int>(posts.size());
@@ -352,6 +363,16 @@ EmptyEvidence detect_empty_vehicle(const GrayImage& work, const int window[4],
     out.roi[3] = wy1;
     out.body = measure_body(work, bx0, wy0, bx1, wy1, p, scale,
                             p.empty_min_post_len_ratio);
+    // 现场口径:下部门框(口)一定存在,上部斜撑(八)不一定有;下口可替代斜撑。
+    // 顶线必须落在画面下半部,避免把堆场/高箱矩形误当空车下口。
+    const double top_ratio = texture_top / std::max(1.0, wh);
+    bool rect_gate = p.empty_rect_without_diagonal &&
+                     out.body.rect_doors >= p.empty_min_rect_doors &&
+                     top_ratio >= p.empty_rect_min_texture_top_ratio;
+    const auto braces_ok = [&](const BodyEvidence& b) {
+        return b.diagonal >= p.empty_min_diagonal_braces || rect_gate;
+    };
+    bool rect_path = rect_gate;
     // 有界兜底:严格门数不到 → 用宽松门再量一次,但只接受“极少数立柱 + 大跨度”。
     // 见 `empty_fallback_max_posts` 注释(防 NX70A 平车+蓝箱被聚成 7 根后误判空车)。
     if (out.body.posts < p.empty_min_posts &&
@@ -362,10 +383,14 @@ EmptyEvidence detect_empty_vehicle(const GrayImage& work, const int window[4],
             loose.posts <= p.empty_fallback_max_posts &&
             loose.span_ratio >= 0.70 &&
             loose.opacity >= p.empty_min_opacity &&
-            loose.diagonal >= p.empty_min_diagonal_braces) {
+            braces_ok(loose)) {
             out.body = loose;
         }
     }
+    rect_gate = p.empty_rect_without_diagonal &&
+                out.body.rect_doors >= p.empty_min_rect_doors &&
+                top_ratio >= p.empty_rect_min_texture_top_ratio;
+    rect_path = rect_gate;
     out.present = true;
     const double body_h_orig = out.body.height / std::max(scale, 1e-6);
     if (body_h_orig < static_cast<double>(p.body_min_roi_px)) {
@@ -389,25 +414,29 @@ EmptyEvidence detect_empty_vehicle(const GrayImage& work, const int window[4],
                 out.body.posts <= p.max_door_posts &&
                 out.body.span_ratio >= p.min_post_span_ratio &&
                 out.body.opacity >= p.body_min_opacity &&
-                out.body.diagonal >= p.min_diagonal_braces;
-    if (out.wall_h_ratio < p.empty_min_wall_h_ratio) {
+                braces_ok(out.body);
+    const double min_wall = rect_path ? p.empty_rect_min_wall_h_ratio
+                                      : p.empty_min_wall_h_ratio;
+    if (out.wall_h_ratio < min_wall) {
         out.reason = "empty_wall_short";
         return out;
     }
-    if (out.body.posts < p.empty_min_posts || out.body.posts > p.max_door_posts) {
+    // “口主导”路径不再强制完整竖棱阵列/跨度/不透明度(只有下口的车型 posts 常为 0)。
+    if (!rect_path && (out.body.posts < p.empty_min_posts ||
+                       out.body.posts > p.max_door_posts)) {
         out.reason = "empty_posts";
         return out;
     }
-    if (out.body.span_ratio < p.empty_min_span_ratio) {
+    if (!rect_path && out.body.span_ratio < p.empty_min_span_ratio) {
         out.reason = "empty_span";
         return out;
     }
-    if (out.body.opacity < p.empty_min_opacity) {
+    if (!rect_path && out.body.opacity < p.empty_min_opacity) {
         out.reason = "empty_opacity";
         return out;
     }
-    if (out.body.diagonal < p.empty_min_diagonal_braces) {
-        out.reason = "empty_braces";
+    if (!braces_ok(out.body)) {
+        out.reason = "empty_braces_or_rect";
         return out;
     }
     out.ok = true;
@@ -415,6 +444,11 @@ EmptyEvidence detect_empty_vehicle(const GrayImage& work, const int window[4],
     out.confidence = std::min(
         1.0, 0.60 + 0.10 * std::min(1.0, out.body.posts / 8.0) + 0.20 * out.body.opacity);
     out.hits = std::min(1.0, 0.45 + 0.04 * out.body.posts + 0.25 * out.body.opacity);
+    if (rect_path) {
+        const double bonus = 0.03 * std::min(3, out.body.rect_doors);
+        out.confidence = std::max(out.confidence, std::min(1.0, 0.66 + bonus));
+        out.hits = std::max(out.hits, std::min(1.0, 0.62 + bonus));
+    }
     return out;
 }
 
@@ -1625,6 +1659,7 @@ EvidenceV2Result EdgeV2::analyze(const GrayImage& gray, double ts, bool plc_arri
     out.body_span = body.span_ratio;
     out.body_opacity = body.opacity;
     out.body_diagonal = body.diagonal;
+    out.rect_doors = body.rect_doors;
     out.body_spcv = body.spcv;
     out.box_bottom_y = box.y1 / std::max(scale, 1e-6);
     out.box_top_y = box_top;

+ 463 - 0
docs/portcv_python_vision_algorithm_review.md

@@ -0,0 +1,463 @@
+# PortCV Python 传统视觉算法:源码逻辑与问题评审
+
+> **结论**:当前 Python 版本确实以传统计算机视觉为主要实现路线,核心算法是 `EvidenceV2`。不需要训练 YOLO,也不依赖神经网络完成车斗、平车和非车载状态的分类。
+>
+> 但是,从源码分析和实际测试来看,现有实现有三个核心问题:
+>
+> 1. **箱底定位不够可靠。** 采用水平亮暗带推测箱底,容易把集装箱自身的横梁、文字和结构边缘识别为箱底。
+> 2. **车辆结构识别不完整。** 虽然已经计算立柱、矩形门、斜撑、车轮等特征,但真正参与分类决策的主要只有立柱、地面比例和水平边梁。
+> 3. **状态识别与落位确认耦合过紧。** 业务是识别三种状态,但当前程序重点在于判断集装箱是否已经落位,导致部分"可识别车型但尚未落位"的画面无法输出有效状态。
+>
+> 此外,实际复现发现两处需要优先修复的状态机问题,下面逐项分析。
+
+---
+
+## 一、Python 代码的完整调用链
+
+当前主链路为:
+
+```text
+RunService
+  └─ 获取摄像头图像 / 视频帧
+       └─ VisionPipeline.step()
+            └─ 选择 EvidenceV2 传统视觉分支
+                 └─ EvidenceV2.analyze()
+                      ├─ 水平亮暗带定位
+                      ├─ 动态 ROI 提取
+                      ├─ 立柱 / 车面检测
+                      ├─ 地面 / 运动分析
+                      └─ 根据结构特征生成 0 / 1 / 2 / 255 候选
+                           └─ CommitTracker
+                                └─ 间隙、运动与连续帧落位确认
+                                     └─ TemporalVoter
+                                          └─ 窗口投票 / 状态防抖
+                                               └─ PublishGate → PLC
+                                                    └─ 发布状态码、置信度和有效性标志
+```
+
+主要涉及五个 Python 文件:
+
+| 源码文件 | 代码位置 | 核心功能 |
+| --- | --- | --- |
+| `logic/evidence_v2.py` | 328–1207 行 | 图像特征提取和分类 |
+| `logic/commit.py` | 175–309 行 | 落位确认 |
+| `logic/decision.py` | 106–229 行 | 时序判决 |
+| `service/pipeline.py` | 69–92 行 | 组合调用 |
+| `service/publish_gate.py` | 118–209 行 | 输出有效性控制 |
+
+---
+
+## 二、EvidenceV2 如何识别三种状态?
+
+### 2.1 第一步:图像预处理
+
+`EvidenceV2.analyze()` 首先将输入图像转换为灰度,并按工作宽度缩放。
+
+```python
+gray0 = _to_gray(image)
+scale = min(1.0, float(self.p.work_width) / float(w))
+```
+
+默认 `work_width=960`。
+
+这样可以降低后续 Sobel、Canny 和 Hough 的计算量。
+
+代码没有使用神经网络特征,而是直接分析像素灰度与几何边缘。
+
+### 2.2 第二步:寻找集装箱底部和车体上缘
+
+核心函数:
+
+```python
+bright, dark = horizontal_bands(gray, window)
+box, bed = pick_box_and_bed(bright, dark, wh)
+```
+
+`horizontal_bands()` 首先计算灰度图的纵向 Sobel 梯度,然后按行求均值。
+
+\[
+G_y(y)=\frac{1}{W}\sum_{x=1}^{W} \operatorname{Sobel}_y(I(x,y))
+\]
+
+如果某个区域出现亮度从明到暗再到明的连续变化,就会形成一组水平暗带候选。
+
+程序将较强的暗带作为疑似箱底,再从其下方寻找最近的亮带作为车体上缘。
+
+**这一步是现有算法最大的精度瓶颈之一。**
+
+代码中的 `pick_box_and_bed()` 使用:
+
+```python
+strong = [b for b in upper if b.strength >= 0.45 * strongest]
+box = min(strong, key=lambda b: b.y0)
+```
+
+这意味着程序在足够强的候选暗带中,优先选择位置最靠上的一条。
+
+但是集装箱侧面可能存在多条强横线:
+
+- 箱体底部横梁;
+- 集装箱侧壁波纹;
+- 罐箱固定框架;
+- 文字或标志区域边缘;
+- 阴影边界。
+
+因此,该逻辑并不能保证选中的一定是真实箱底。
+
+仓库的现场评估报告也记录了这个问题:部分关键帧自动检测到的箱底位置与人工读数不一致。
+
+### 2.3 第三步:动态生成箱底以下 ROI
+
+代码位置:`evidence_v2.py:1067–1088`
+
+算法根据当前估计的箱底位置,计算一个位于其下方的分析区域。
+
+```python
+below_work = (x0w, y0w, x1w, y1w)
+```
+
+这样做的目的是避免直接分析集装箱侧壁,而是重点检查车体是否具有敞车侧墙或平车边梁。
+
+这个思路正确,而且比固定 ROI 更适合装卸过程中箱体上下移动的场景。
+
+不过,目前 ROI 只根据箱底位置确定,缺少对车厢实例的独立定位。因此,前景遮挡、车辆移动和箱底误检仍可能使 ROI 偏移。
+
+### 2.4 第四步:提取车体结构特征
+
+核心函数:
+
+```python
+structure = detect_structure_v2(
+    gray, below_work,
+    min_post_len_ratio=0.30,
+    cluster_gap_px=9.0,
+    scale=scale,
+)
+```
+
+其内部处理顺序为:
+
+```text
+CLAHE → Canny → HoughLinesP → 直线方向分类 → 立柱聚类 → 矩形轮廓统计
+```
+
+各特征在代码中的作用:
+
+| 特征 | 实现方法 | 是否直接参与分类 |
+| --- | --- | --- |
+| `post_count` | Hough 竖线聚类 | **是** |
+| `post_spacing_cv` | 立柱间距变异系数 | **是** |
+| `rect_doors` | 轮廓近似得到矩形数量 | 否 |
+| `diagonal_lines` | Hough 斜线计数 | 否 |
+| `deck_edge` | 水平线长度及位置 | **是** |
+| `wheel_count` | HoughCircles | 否 |
+| `ground_ratio` | 分块纹理与长直线排除 | **是** |
+| `wall_opacity` | 基于地面比例估计 | **是** |
+| `gap_px` | 箱底与车体上缘间距 | **是** |
+
+这里有一个明显的实现落差:
+
+**设计文档强调敞车的"八+口"结构,以及平车的车轮、转向架、地面组合证据,但实际分类函数没有直接使用矩形门、斜撑和车轮数量。**
+
+也就是说,目前传统视觉算法已经计算了这些信息,但没有充分利用。
+
+### 2.5 第五步:根据结构规则进行三分类
+
+核心函数:`EvidenceV2._classify()`,第 846–898 行。
+
+#### 状态 1:集装箱在车斗
+
+主要判断箱底以下是否存在密集立柱和不透明侧墙。
+
+```python
+bed_strong = (
+    5 <= posts <= 16
+    and opacity >= 0.35
+    and (gap_px is None or gap_px <= 40)
+    and (spacing_cv is None or spacing_cv <= 6.0)
+)
+```
+
+其中 `opacity` 实际主要采用 `1-ground_ratio` 得到,并不是通过物理遮挡分割计算的真实不透明度。
+
+#### 状态 2:集装箱在平板车
+
+主要依赖门板立柱少以及车面边梁存在。
+
+```python
+flat_strong = (
+    posts <= 4
+    and deck
+    and (gap_px is None or gap_px <= 40)
+)
+```
+
+地面比例只用于提升置信度,并不是必要条件。车轮检测结果虽然传入 `_classify()`,但未被使用。
+
+#### 状态 0:集装箱不在车上
+
+```python
+if posts <= 1 and ground >= 0.65 and not deck:
+    return NOT_ON_TRAIN
+```
+
+这实际上是在识别"没有明显铁路车体结构、存在地面纹理"的画面,并不是直接检测集装箱已经脱离车辆。
+
+这里还有一个关键问题:
+
+**当前算法的三种状态并不完全对称。**
+
+状态 1 和状态 2 侧重识别车辆结构;状态 0 则依赖缺少车辆结构和地面特征。这会造成悬吊集装箱、空白画面、车辆完全遮挡时的语义混淆。
+
+---
+
+## 三、CommitTracker 的作用
+
+代码:`logic/commit.py`
+
+这部分解决的是:
+
+**"图像看起来像在车上"与"是否已经完成落位"之间的区别。**
+
+当前配置要求:
+
+| 条件 | 数值 |
+| --- | --- |
+| 最大米制间隙 | 0.10 m |
+| 最大像素间隙 | 8 px |
+| 连续状态帧数 | 5 |
+| 连续结构证据帧数 | 5 |
+| 结构证据强度 | ≥ 0.60 |
+| 明显运动 | 阻止确认 |
+| 吊具高悬 | 阻止确认 |
+
+对于状态 1、2,间隙门、连续帧和运动条件满足后才允许 `committed=True`。
+
+对于状态 0,则不要求间隙门,但仍要求稳定的结构证据。
+
+这套设计用于**落位确认**有合理性,但与现在明确的"纯视觉三状态识别"需求存在差异。
+
+例如集装箱正在缓慢下降,画面已经明确显示下方为敞车,视觉分类候选可以是 `1`;但由于没有真正落位,`CommitTracker` 仍会阻止对外提交该状态。
+
+建议将两类结果拆开:
+
+| 输出 | 意义 |
+| --- | --- |
+| `scene_state` | 当前集装箱对应车斗、平车还是非车载状态 |
+| `contact_state` | 已落位、已脱离、无法确认 |
+
+这样传统视觉算法可以持续输出场景识别结果,而是否允许进入自动控制流程交给独立的接触确认与安全控制逻辑。
+
+---
+
+## 四、源码复核发现的实际问题
+
+以下不仅是推测,其中前三项已通过原始 Python 类构造输入复现。
+
+### P0-1:UNKNOWN 后仍可能继续发布有效状态
+
+代码位置:`logic/decision.py:114–157` 与 `publish_gate.py:148–161`
+
+在先前稳定识别状态 2 后,连续输入未知状态。实测结果:
+
+| 输入时间 | 本帧观测 | 对外状态 | RESULT_VALID |
+| --- | --- | --- | --- |
+| 1.9s | 2 | 2 | 1 |
+| 2.0s | 255 | 2 | 1 |
+| 2.1s | 255 | 2 | 1 |
+| 2.2s | 255 | 2 | 1 |
+| 2.3s | 255 | 2 | 1 |
+| 2.4s | 255 | 2 | 1 |
+| 2.5s | 255 | 2 | 0 |
+
+原因是 `TemporalVoter` 在保持期内仍认为旧状态稳定,而 `PublishGate` 没有直接获得本帧证据失效的信息。
+
+**建议**:允许保持上一状态码,但当前视觉证据失效时,应立即取消结果有效性,除非控制契约明确允许短时有效保持。
+
+### P0-2:吊具高悬或 UNKNOWN 会阻止本帧提交,但不会清空历史落位窗口
+
+代码位置:`logic/commit.py:208–222`
+
+复现过程:
+
+| 操作 | committed |
+| --- | --- |
+| 连续 5 帧满足平车落位条件 | True |
+| 插入 1 帧 `hoist_high=True` | False |
+| 下一帧恢复正常 | **True** |
+
+同样,插入一帧 `state=255` 后恢复,也可能立即重新提交。
+
+代码在这些异常分支直接 `return`,并没有清空 `_samples`。这与注释中"重新累计窗口"的意图不一致。
+
+**建议**:吊具高悬、证据中断或身份变化时,清空或失效化历史窗口;恢复后重新累计连续帧。
+
+### P0-3:时序投票没有严格执行 `min_votes=4`
+
+代码位置:`logic/decision.py:175–188`
+
+源码使用:
+
+```python
+required = min(self.min_votes, len(self._obs))
+```
+
+实测仅输入两帧状态 2,间隔 0.3 秒后,内部状态即可由 255 提交为 2,尽管此时 `stable=False`。
+
+这说明 `min_votes=4` 实际上是一个随现有窗口长度缩小的门槛,而不是严格四票要求。
+
+如果业务需要至少四次有效观测,应采用固定最低票数,并重新验证冷启动时延。
+
+### 其余算法问题
+
+| 优先级 | 问题 | 影响 |
+| --- | --- | --- |
+| P0 | 吊具高悬会阻止状态 0 的落位提交 | 悬吊集装箱可能长期输出 UNKNOWN |
+| P1 | `evidence-v2` 后端实际上解析为 `MockDetector` | 模拟检测框可能参与吊具判断 |
+| P1 | `max_post_spacing_cv=6.0` 约束很宽松 | 伪立柱较容易通过门控 |
+| P1 | 矩形门、斜撑、车轮仅用于诊断 | 多结构证据没有发挥作用 |
+| P1 | `px_per_m` 通过最长竖线推算 | 近距裁顶时物理尺度可能失真 |
+| P1 | 全图帧差作为运动门控 | 相机振动可能导致分类持续弃权 |
+| P1 | `reject_spreader_contact` 配置没有进入实际参数解析 | 配置与执行逻辑不一致 |
+| P1 | `note_plc_arrival()` 已定义,但未找到生产调用入口 | PLC 到位辅助功能尚未完整接入 |
+
+其中 `MockDetector` 需要单独解释:传统视觉分类不依赖模拟框,但 `VisionPipeline.step()` 仍然调用模拟检测器并将检测框传给 `EvidenceV2`;这些框可能用于吊具高悬判断。因此,当前代码还不是完全干净的"仅图像输入的传统视觉闭环"。
+
+---
+
+## 五、根据任务目标应如何优化 Python 版本
+
+建议继续沿用传统视觉,不需要转向 YOLO,但要调整算法重点。
+
+### 5.1 第一优先级:修正箱底定位
+
+当前使用"最靠上的强水平暗带",可靠性不足。
+
+建议保留 Sobel 和 Hough,但增加多候选约束:
+
+- 水平线段长度和连续性;
+- 箱底候选与车体上缘的空间顺序;
+- 连续视频中的边缘轨迹;
+- 箱底移动速度与相邻帧位移一致性;
+- 对文字、横梁和局部强纹理进行候选抑制。
+
+最关键的是:**不能只返回一个箱底候选,应保留多个候选并进行时序匹配,找不到可靠匹配就弃权。**
+
+### 5.2 第二优先级:构建真正的多结构证据融合
+
+不建议继续让 `post_count` 几乎主导敞车识别。
+
+推荐采用可解释的结构证据评分:
+
+\[
+S_{\text{bed}} = w_1 P + w_2 R + w_3 D + w_4 O
+\]
+
+其中:
+
+- \(P\):立柱阵列证据;
+- \(R\):矩形门板证据;
+- \(D\):斜撑证据;
+- \(O\):侧墙连续覆盖证据。
+
+对于平车:
+
+\[
+S_{\text{flat}} = v_1 E + v_2 G + v_3 W - v_4 P
+\]
+
+其中 \(E\) 是可信平车边梁,\(G\) 是车底透空/地面证据,\(W\) 是轮组辅助证据。
+
+这些权重不应凭经验固定,建议利用标注的真实视频统计特征分布后确定。
+
+保留 `UNKNOWN` 作为冲突或低证据拒判结果。
+
+### 5.3 第三优先级:重新定义状态 0
+
+这是需求匹配中的最大差异。
+
+要求的状态 0 是:
+
+**集装箱不在车斗,也不在平板车上。**
+
+它可能包括悬吊、地面放置、已经脱离车辆等情况。
+
+当前算法却主要依赖"地面纹理 + 没有车体边梁",缺少主动的箱车分离判断。
+
+纯视觉可以增加以下信息:
+
+```text
+箱底位置 → 车面位置 → 两者相对运动 → 分离间隙变化 → 连续帧确认
+```
+
+同时应保留无法判断的内部状态 255。例如箱体遮挡了车面、间隙不可见,就不能因为没有检测到平车边梁而认定不在车上。
+
+### 5.4 第四优先级:建立真正的多帧证据跟踪
+
+当前 `_motion()` 使用缩略图帧间差异与 Laplacian 特征强度判断运动,但未对正面吊摄像头自身移动进行补偿。
+
+建议使用已有 OpenCV 能力:
+
+- Shi-Tomasi 角点;
+- LK 光流;
+- RANSAC 仿射变换估计;
+- 车体背景运动补偿;
+- 箱底与车体关键边缘相对运动估计。
+
+这些都不需要训练神经网络。
+
+---
+
+## 六、测试结果及真实数据局限
+
+实际执行了 Python 传统视觉相关的 61 项单元测试:
+
+| 项目 | 结果 |
+| --- | --- |
+| 单元测试 | **61 / 61 通过** |
+| 现场负样本回归 | **SKIP**(素材未包含在压缩包内) |
+
+这些测试说明主要函数与合成输入上的逻辑可以运行,但不能证明真实视频三分类准确率。
+
+仓库自带的现场数据报告主要基于:
+
+| 数据 | 场景 | 状态 | 覆盖情况 |
+| --- | --- | --- | --- |
+| A | C70 敞车 + 20ft 罐箱 | 1 | 箱底下方侧墙明显 |
+| B | X70 平车 + 20ft 干箱 | 2 | 边梁和透空结构明显 |
+| C | 悬吊 / 地面 / 其他 | 0 | 缺少完整现场验证 |
+
+压缩包中存在 A/B 的标注截图和统计报告,但没有完整原始视频。因此目前只能确认部分帧的结构可分性,无法计算完整的准确率、召回率和误判率。
+
+---
+
+## 七、代码修改优先级
+
+建议按照下面的顺序开发,不要一开始全面重写 `EvidenceV2`。
+
+| 顺序 | 修改模块 | 具体任务 | 目的 |
+| --- | --- | --- | --- |
+| 1 | `decision.py` | 修复 UNKNOWN 有效性和投票门槛 | 解决状态机错误 |
+| 2 | `commit.py` | 异常后清空历史窗口 | 防止复用失效证据 |
+| 3 | `pipeline.py` | 移除生产路径的 Mock 检测框 | 保证纯视觉闭环 |
+| 4 | `evidence_v2.py` | 改进水平带与箱底定位 | 提升 ROI 准确性 |
+| 5 | `evidence_v2.py` | 增加多结构评分 | 提升敞车/平车区分 |
+| 6 | `evidence_v2.py` | 实现箱车分离判断 | 完善状态 0 |
+| 7 | `commit.py` | 场景识别与落位确认分离 | 满足实际三状态需求 |
+| 8 | `tests/` | 新增真实视频回归测试 | 量化性能 |
+
+---
+
+## 最终技术判断
+
+**现有 Python 项目最有价值的部分是 `EvidenceV2` 的"箱底以下结构分析"思路。** 已有现场证据说明该方向有可行性,不应因为暂时存在误判就推翻传统视觉路线。
+
+但现阶段的实现仍属于**规则型 POC,而非成熟的工业三状态识别算法**。它的分类条件过于依赖少数人工特征,缺少稳健的箱体定位、多结构联合判断和真正的箱车相对运动分析。
+
+对当前任务,建议采用以下最终结构:
+
+```text
+OpenCV 箱底定位 → 动态 ROI → 敞车/平车结构证据 → 箱车相对位置与运动 → 三状态判决 → 时序融合
+```
+
+将 `CommitTracker` 保留为独立落位验证模块,不再让它决定三种场景类别本身是否可以输出。这样既保留传统视觉路线,也更符合现在明确的业务目标。

+ 5 - 0
portcv/config.py

@@ -153,6 +153,11 @@ DEFAULTS: Dict[str, Any] = {
         "empty_fallback_max_posts": 4,
         # 空车斜撑门(与 min_diagonal_braces 分开;现场可按车型单独放宽)
         "empty_min_diagonal_braces": 1,
+        # 现场口径:下部“口”形门框一定存在,可替代非必选的上部“八”字斜撑
+        "empty_min_rect_doors": 1,
+        "empty_rect_without_diagonal": True,
+        "empty_rect_min_wall_h_ratio": 0.10,
+        "empty_rect_min_texture_top_ratio": 0.62,
         # P0-Q10:空平车(车面裸露)→ 也输出 3
         "empty_flatbed_enable": True,
         "empty_flatbed_min_gap_px": 16.0,

+ 1 - 1
portcv/detect/mock.py

@@ -79,6 +79,6 @@ class MockDetector(Detector):
         self._cursor = 0
 
     def describe(self) -> Dict[str, object]:
-        info = super().describe()
+        info: Dict[str, object] = super().describe()
         info["script_frames"] = len(self.script)
         return info

+ 45 - 8
portcv/logic/evidence_v2.py

@@ -154,6 +154,15 @@ class EvidenceV2Params:
     empty_fallback_max_posts: int = 4
     # 空车判据的斜撑门(与 `min_diagonal_braces` 分开,便于现场按车型单独放宽)。
     empty_min_diagonal_braces: int = 1
+    # 现场反馈:敞车车斗不一定有上部外扩的“八”字斜撑,但下部“口”形门框一定存在。
+    # 因此斜撑门可由“口”形矩形门计数替代;`empty_rect_without_diagonal=false` 时
+    # 恢复旧口径(必须有斜撑)。
+    empty_min_rect_doors: int = 1
+    empty_rect_without_diagonal: bool = True
+    # “口主导”路径放宽的可见墙高:只有下口、没有上八斜撑/完整竖棱时也认可。
+    empty_rect_min_wall_h_ratio: float = 0.10
+    # 口主导路径要求车体顶线位于画面下半部(避免把堆场/高箱矩形误当空车下口)。
+    empty_rect_min_texture_top_ratio: float = 0.62
     # ---- P0-Q10:空平车(平车、车面裸露)→ 也输出 state=3 ----
     # 平车没有侧墙,空载时直接看到**车底板**:薄车面边梁 + 车底透空 + 边梁上方是
     # 一片光滑亮面(车面),且**没有箱底暗带紧贴边梁**(载车的箱底阴影必然贴着边梁,
@@ -317,6 +326,11 @@ class EvidenceV2Params:
             empty_min_post_len_ratio=float(raw.get("empty_min_post_len_ratio", 0.30)),
             empty_fallback_max_posts=int(raw.get("empty_fallback_max_posts", 4)),
             empty_min_diagonal_braces=int(raw.get("empty_min_diagonal_braces", 1)),
+            empty_min_rect_doors=int(raw.get("empty_min_rect_doors", 1)),
+            empty_rect_without_diagonal=bool(raw.get("empty_rect_without_diagonal", True)),
+            empty_rect_min_wall_h_ratio=float(raw.get("empty_rect_min_wall_h_ratio", 0.10)),
+            empty_rect_min_texture_top_ratio=float(
+                raw.get("empty_rect_min_texture_top_ratio", 0.62)),
             empty_flatbed_enable=bool(raw.get("empty_flatbed_enable", True)),
             empty_flatbed_min_gap_px=float(raw.get("empty_flatbed_min_gap_px", 16.0)),
             empty_flatbed_max_plane_edge=float(
@@ -1268,6 +1282,19 @@ class EvidenceV2:
         roi = (bx0, wy0, bx1, wy1)
         b = self._measure_body(gray, roi, scale,
                               post_len_ratio=p.empty_min_post_len_ratio)
+        # 现场口径:下部“口”形门框(矩形门轮廓)一定存在,上部“八”字斜撑不一定有。
+        # 因此“口”计数可替代斜撑门;`empty_rect_without_diagonal=false` 恢复旧口径。
+        struct = detect_structure_v2(
+            gray, roi, min_post_len_ratio=p.empty_min_post_len_ratio, scale=scale)
+        rect_doors = int(struct.get("rect_doors", 0))
+        top_ratio = float(texture_top) / max(1.0, float(wh))
+        rect_gate = (p.empty_rect_without_diagonal
+                     and rect_doors >= p.empty_min_rect_doors
+                     and top_ratio >= p.empty_rect_min_texture_top_ratio)
+
+        def _braces_ok(body: Dict[str, float]) -> bool:
+            return (int(body["diagonal"]) >= p.empty_min_diagonal_braces or rect_gate)
+
         # 有界兜底:严格门数不到 → 用宽松门再量一次,但只接受“极少数立柱 + 大跨度”。
         # 见 `empty_fallback_max_posts` 注释(防 NX70A 平车+蓝箱被聚成 7 根后误判空车)。
         if (int(b["posts"]) < p.empty_min_posts
@@ -1277,13 +1304,16 @@ class EvidenceV2:
             if (p.empty_min_posts <= int(b2["posts"]) <= p.empty_fallback_max_posts
                     and float(b2["span"]) >= 0.70
                     and float(b2["opacity"]) >= p.empty_min_opacity
-                    and int(b2["diagonal"]) >= p.empty_min_diagonal_braces):
+                    and _braces_ok(b2)):
                 b = b2
+        rect_path = bool(rect_gate)
         stats = {
             "posts": int(b["posts"]),
             "span": float(b["span"]),
             "opacity": float(b["opacity"]),
             "diagonal": int(b["diagonal"]),
+            "rect_doors": rect_doors,
+            "rect_path": rect_path,
             "height": float(b["height"]),
             "wall_h_ratio": wall_h_ratio,
         }
@@ -1307,23 +1337,26 @@ class EvidenceV2:
             p.body_min_posts <= b["posts"] <= p.max_door_posts
             and b["span"] >= p.min_post_span_ratio
             and b["opacity"] >= p.body_min_opacity
-            and b["diagonal"] >= p.min_diagonal_braces
+            and _braces_ok(b)
         )
         out["basic"] = bool(basic)
-        if wall_h_ratio < p.empty_min_wall_h_ratio:
+        min_wall = p.empty_rect_min_wall_h_ratio if rect_path else p.empty_min_wall_h_ratio
+        if wall_h_ratio < min_wall:
             out["reason"] = "empty_wall_short"
             return out
-        if not (p.empty_min_posts <= b["posts"] <= p.max_door_posts):
+        # “口主导”路径:下部门框已提供车体结构证据,不再强制要求完整竖棱阵列
+        # (170514 这类只有下口、没有上八的敞车,严格竖棱数常为 0)。
+        if not rect_path and not (p.empty_min_posts <= b["posts"] <= p.max_door_posts):
             out["reason"] = "empty_posts"
             return out
-        if b["span"] < p.empty_min_span_ratio:
+        if not rect_path and b["span"] < p.empty_min_span_ratio:
             out["reason"] = "empty_span"
             return out
-        if b["opacity"] < p.empty_min_opacity:
+        if not rect_path and b["opacity"] < p.empty_min_opacity:
             out["reason"] = "empty_opacity"
             return out
-        if b["diagonal"] < p.empty_min_diagonal_braces:
-            out["reason"] = "empty_braces"
+        if not _braces_ok(b):
+            out["reason"] = "empty_braces_or_rect"
             return out
         out["ok"] = True
         out["reason"] = "empty_vehicle"
@@ -1331,6 +1364,10 @@ class EvidenceV2:
             1.0, 0.60 + 0.10 * min(1.0, b["posts"] / 8.0) + 0.20 * b["opacity"]
         )
         out["hits"] = min(1.0, 0.45 + 0.04 * b["posts"] + 0.25 * b["opacity"])
+        if rect_path:
+            # 口主导时 posts/opacity 可能为 0;给足 structure_hits 才能过 commit 门。
+            out["confidence"] = max(out["confidence"], min(1.0, 0.66 + 0.03 * min(rect_doors, 3)))
+            out["hits"] = max(out["hits"], min(1.0, 0.62 + 0.03 * min(rect_doors, 3)))
         return out
 
     @staticmethod

+ 127 - 0
scripts/analyze_web_cc.py

@@ -0,0 +1,127 @@
+"""用 EvidenceV2 对采集的车型图片做结构特征分析(诊断,不参与训练)。
+
+输出每张图的:立柱数 post_count、立柱间距 cv、地面比例 ground、边梁 deck、
+箱底/车面带数、候选状态。用于判断侧面车型图的特征分布与算法口径差异。
+
+用法:
+    python scripts/analyze_web_cc.py [--out report.csv]
+"""
+from __future__ import annotations
+
+import argparse
+import csv
+import glob
+import os
+import sys
+
+import cv2
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+
+from portcv.config import load_config
+from portcv.io.capture import imread_any
+from portcv.logic.evidence_v2 import (
+    EvidenceV2, horizontal_bands, pick_box_and_bed, detect_structure_v2,
+    ground_like_ratio, _to_gray,
+)
+
+STATE_NAME = {0: "NOT_ON_TRAIN", 1: "BED", 2: "FLATBED", 255: "UNKNOWN"}
+
+
+def main() -> int:
+    ap = argparse.ArgumentParser()
+    ap.add_argument("--out", default=os.path.join(ROOT, "dataset", "web_cc", "analysis.csv"))
+    args = ap.parse_args()
+
+    cfg = load_config(os.path.join(ROOT, "configs", "edge-v2-front.json"))
+    ev = EvidenceV2.from_config(cfg)
+    p = ev.p
+
+    files = glob.glob(os.path.join(ROOT, "dataset", "web_cc", "*", "*"))
+    files = [f for f in files if f.lower().endswith((".jpg", ".jpeg", ".png"))]
+    files.sort()
+
+    rows = []
+    for f in files:
+        image = imread_any(os.path.abspath(f).replace("\\", "/"))
+        if image is None:
+            continue
+        wtype = os.path.basename(os.path.dirname(f))  # 业务类别:敞车/平车/其他
+        # 从新文件名 "C70E_001.jpg" 解析车型前缀
+        import re as _re
+        m = _re.match(r"^([A-Z]+\d*[A-Z]*)_\d+", os.path.basename(f))
+        car_type = m.group(1) if m else wtype
+        gray0 = _to_gray(image)
+        h, w = gray0.shape[:2]
+        scale = min(1.0, float(p.work_width) / float(w))
+        gray = cv2.resize(gray0, (int(round(w * scale)), int(round(h * scale))),
+                          interpolation=cv2.INTER_AREA) if scale < 1 else gray0.copy()
+        wh, ww = gray.shape[:2]
+        window = (int(p.window[0] * ww), int(p.window[1] * wh),
+                  int(p.window[2] * ww), int(p.window[3] * wh))
+        max_h = max(6, int(p.band_max_h_ratio * wh))
+        min_h = max(1, int(p.band_min_h * scale))
+        bright, dark = horizontal_bands(gray, window, min_h=min_h, max_h=max_h)
+        box_hint = max(80.0, 0.40 * wh)
+        box, bed = pick_box_and_bed(
+            bright, dark, wh,
+            box_bottom_max_ratio=p.box_bottom_max_ratio,
+            bed_search_px=max(24.0, p.bed_search_ratio * box_hint),
+        )
+        if box is None:
+            rows.append(dict(type=car_type, group=wtype, file=os.path.basename(f), post_count=-1,
+                             spacing_cv="", ground="", deck="", state="NO_BOX"))
+            continue
+        # 车体 ROI:箱底以下(侧面车型图没有箱,这里仅诊断箱底误检位置)
+        est_h = max(60.0, box.y0 - 0.05 * wh)
+        start = max(2.0, p.below_start_ratio * est_h)
+        y0w = min(wh - 2, int(box.y1 + start))
+        below_h = max(p.below_min_height_px * scale,
+                      min(p.below_height_ratio * est_h, 0.30 * wh))
+        y1w = min(wh - 1, max(y0w + int(below_h), int(box.y1 + 0.10 * est_h)))
+        x0w, x1w = max(0, int(0.05 * ww)), min(ww - 1, int(0.95 * ww))
+        below = (x0w, y0w, x1w, max(y0w + 8, y1w))
+        structure = detect_structure_v2(gray, below,
+                                        min_post_len_ratio=p.min_post_len_ratio,
+                                        cluster_gap_px=9.0, scale=scale)
+        ground, _ = ground_like_ratio(gray, below, structure["lines"],
+                                      block_px=p.ground_block_px,
+                                      density_lo=p.ground_density_lo,
+                                      density_hi=p.ground_density_hi)
+        posts = int(structure["post_count"])
+        opacity = max(0.0, min(1.0, 1.0 - ground))
+        # 复用配置阈值做候选判定(仅诊断)
+        bed_strong = (p.min_door_posts <= posts <= getattr(p, "vehicle_max_posts", 16)
+                      and opacity >= p.min_wall_opacity)
+        flat_strong = (posts <= p.flat_max_door_posts)
+        state = 1 if bed_strong else (2 if flat_strong else 0)
+        rows.append(dict(
+            type=car_type, group=wtype, file=os.path.basename(f),
+            post_count=posts,
+            spacing_cv="" if structure["post_spacing_cv"] is None else round(structure["post_spacing_cv"], 2),
+            ground=round(ground, 3),
+            deck=len(structure["horizontal"]),
+            state=STATE_NAME[state],
+        ))
+
+    with open(args.out, "w", newline="", encoding="utf-8-sig") as fh:
+        w = csv.DictWriter(fh, fieldnames=["type", "group", "file", "post_count", "spacing_cv", "ground", "deck", "state"])
+        w.writeheader()
+        w.writerows(rows)
+
+    print("analyzed:", len(rows), "->", args.out)
+    # 按车型汇总立柱数
+    by_type: dict = {}
+    for r in rows:
+        if r["post_count"] >= 0:
+            by_type.setdefault(r["type"], []).append(int(r["post_count"]))
+    for t in sorted(by_type):
+        v = by_type[t]
+        print("%-6s n=%2d  posts min=%2d max=%2d avg=%.1f" % (
+            t, len(v), min(v), max(v), sum(v) / len(v)))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 212 - 0
scripts/download_wagon_images.py

@@ -0,0 +1,212 @@
+"""从 Wikimedia Commons 采集铁路货车车型图片(CC/公共领域授权)。
+
+用途:为正面吊车型识别补充多车型样本(C70/C64K/C70E/C80 敞车、X70/NX70 平车)。
+只下载 Commons 上的自由授权图片,逐张记录作者与许可到 LICENSES.csv。
+
+用法:
+    python scripts/download_wagon_images.py [--out DIR] [--max-per-type N] [--dry-run]
+
+依赖:仅标准库(urllib / json / csv / re)。
+"""
+from __future__ import annotations
+
+import argparse
+import csv
+import html
+import json
+import os
+import re
+import sys
+import time
+import urllib.parse
+import urllib.request
+
+API = "https://commons.wikimedia.org/w/api.php"
+UA = "PortCV-WagonDataCollector/1.0 (research; contact: local)"
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+# 车型 → Wikimedia Commons 分类(这些分类下的图片按文件名前缀再细分车型)
+CATEGORIES = [
+    "Category:Open railway wagons of China",
+    "Category:Container railway wagons of China",
+    "Category:Flat railway wagons of China",
+    "Category:Covered railway wagons of China",     # 棚车 P62/P64 → 状态0负样本
+    "Category:Chawu Railway Station",               # 更多 C80B / X70 现场图
+]
+
+# 从文件名提取车型标签(按优先级匹配,先匹配到的为准)
+# 业务映射:敞车(C*)→状态1,平车(X*/NX*)→状态2,棚车(P*)→状态0负样本
+TYPE_PATTERNS = [
+    ("C70E", re.compile(r"\bC70E\b", re.I)),
+    ("C70H", re.compile(r"\bC70H\b", re.I)),
+    ("C70", re.compile(r"\bC70\b", re.I)),
+    ("C64K", re.compile(r"\bC64K\b", re.I)),
+    ("C64", re.compile(r"\bC64\b", re.I)),
+    ("C80", re.compile(r"\bC80[A-Z]?\b", re.I)),
+    ("NX70", re.compile(r"\bNX70[A-Z]?\b", re.I)),
+    ("NX17", re.compile(r"\bNX17[A-Z]?\b", re.I)),
+    ("X70", re.compile(r"\bX70\b", re.I)),
+    ("X160", re.compile(r"\bX160[A-Z]?\b", re.I)),
+    ("P62", re.compile(r"\bP62[A-Z]?\b", re.I)),     # 棚车负样本
+    ("P64", re.compile(r"\bP64[A-Z]?\b", re.I)),     # 棚车负样本
+]
+
+
+def api_get(params: dict, retries: int = 3):
+    params = dict(params)
+    params["format"] = "json"
+    url = API + "?" + urllib.parse.urlencode(params)
+    last = None
+    for i in range(retries):
+        try:
+            req = urllib.request.Request(url, headers={"User-Agent": UA})
+            with urllib.request.urlopen(req, timeout=30) as r:
+                return json.load(r)
+        except Exception as exc:  # pragma: no cover
+            last = exc
+            time.sleep(1.5 * (i + 1))
+    raise RuntimeError("API 请求失败: %s" % last)
+
+
+def category_files(category: str):
+    """返回分类下所有 File: 页面标题(处理续页)。"""
+    out, cont = [], {}
+    while True:
+        params = {
+            "action": "query",
+            "list": "categorymembers",
+            "cmtitle": category,
+            "cmtype": "file",
+            "cmlimit": "200",
+        }
+        params.update(cont)
+        data = api_get(params)
+        out.extend(m["title"] for m in data.get("query", {}).get("categorymembers", []))
+        if "continue" not in data:
+            break
+        cont = data["continue"]
+    return out
+
+
+def file_info(titles):
+    """批量取图片原图 URL + 授权元数据(每批 50 个)。"""
+    out = []
+    for i in range(0, len(titles), 50):
+        batch = titles[i : i + 50]
+        data = api_get(
+            {
+                "action": "query",
+                "titles": "|".join(batch),
+                "prop": "imageinfo",
+                "iiprop": "url|extmetadata",
+                "iiurlwidth": "1280",  # Commons 允许的缩略图宽度,原图直链会被 429
+            }
+        )
+        for page in data.get("query", {}).get("pages", {}).values():
+            ii = (page.get("imageinfo") or [{}])[0]
+            out.append((page.get("title", ""), ii))
+    return out
+
+
+def strip_html(s: str) -> str:
+    s = html.unescape(s or "")
+    return re.sub(r"<[^>]+>", "", s).strip()
+
+
+def meta_value(ii: dict, key: str) -> str:
+    return strip_html((ii.get("extmetadata", {}).get(key, {}) or {}).get("value", ""))
+
+
+def classify(title: str):
+    name = title[5:] if title.lower().startswith("file:") else title
+    for label, pat in TYPE_PATTERNS:
+        if pat.search(name):
+            return label
+    return "other"
+
+
+def safe_name(title: str) -> str:
+    name = title[5:] if title.lower().startswith("file:") else title
+    return re.sub(r'[\\/:*?"<>|]', "_", name)
+
+
+def main() -> int:
+    ap = argparse.ArgumentParser()
+    ap.add_argument("--out", default=os.path.join(ROOT, "dataset", "web_cc"))
+    ap.add_argument("--max-per-type", type=int, default=30)
+    ap.add_argument("--dry-run", action="store_true")
+    args = ap.parse_args()
+
+    titles = []
+    for cat in CATEGORIES:
+        print("category:", cat, file=sys.stderr)
+        titles.extend(category_files(cat))
+    titles = list(dict.fromkeys(titles))
+    print("total files:", len(titles), file=sys.stderr)
+
+    records = file_info(titles)
+    counts: dict = {}
+    rows = []
+
+    for title, ii in records:
+        label = classify(title)
+        if label == "other":
+            continue
+        if counts.get(label, 0) >= args.max_per_type:
+            continue
+        # 优先用缩略图 URL(thumburl),Commons 对它不限流;没有则用原图
+        url = ii.get("thumburl") or ii.get("url")
+        if not url:
+            continue
+        license_name = meta_value(ii, "LicenseShortName")
+        author = meta_value(ii, "Artist")
+        counts[label] = counts.get(label, 0) + 1
+        rows.append(
+            {
+                "type": label,
+                "title": title,
+                "url": url,  # 实际下载的是缩略图 URL
+                "source_page": ii.get("descriptionurl", ""),
+                "license": license_name,
+                "author": author[:200],
+            }
+        )
+
+    print("selected:", len(rows), "by type:", counts, file=sys.stderr)
+
+    if args.dry_run:
+        for r in rows:
+            print("%-8s %-12s %s" % (r["type"], r["license"], r["title"]))
+        return 0
+
+    os.makedirs(args.out, exist_ok=True)
+    with open(os.path.join(args.out, "LICENSES.csv"), "w", newline="", encoding="utf-8-sig") as fh:
+        w = csv.DictWriter(fh, fieldnames=["type", "title", "url", "source_page", "license", "author"])
+        w.writeheader()
+        for r in rows:
+            folder = os.path.join(args.out, r["type"])
+            os.makedirs(folder, exist_ok=True)
+            path = os.path.join(folder, safe_name(r["title"]))
+            if not os.path.exists(path):
+                ok = False
+                for attempt in range(3):
+                    try:
+                        req = urllib.request.Request(url=r["url"], headers={"User-Agent": UA})
+                        with urllib.request.urlopen(req, timeout=60) as resp, open(path, "wb") as out:
+                            out.write(resp.read())
+                        print("saved", r["type"], os.path.basename(path), file=sys.stderr)
+                        ok = True
+                        break
+                    except Exception as exc:  # pragma: no cover
+                        print("retry %d" % attempt, r["title"], exc, file=sys.stderr)
+                        time.sleep(2 * (attempt + 1))
+                if not ok:
+                    continue
+            w.writerow(r)
+            time.sleep(1.0)  # 限速,避免再次触发 429
+    print("done. output:", args.out, file=sys.stderr)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 73 - 0
scripts/extract_video_frames.py

@@ -0,0 +1,73 @@
+"""视频关键帧提取:每 N 帧保存一帧图像(Windows 中文路径安全版)。
+
+由于 cv2.imwrite 在 Windows 下不支持中文路径,输出目录统一用 ASCII 名
+(v01, v02 ...),视频原名与目录的对应关系写入 manifest.csv。
+
+用法:
+    python scripts/extract_video_frames.py [--every 10] [--out DIR] [--videos V1 V2 ...]
+"""
+from __future__ import annotations
+
+import argparse
+import csv
+import glob
+import os
+import sys
+
+import cv2
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def main() -> int:
+    ap = argparse.ArgumentParser()
+    ap.add_argument("--every", type=int, default=10, help="每隔多少帧保存一帧")
+    ap.add_argument("--out", default=os.path.join(ROOT, "dataset", "video_frames"))
+    ap.add_argument("--videos", nargs="*", default=None, help="指定视频;默认 dataset/*.mp4")
+    args = ap.parse_args()
+
+    videos = args.videos or sorted(glob.glob(os.path.join(ROOT, "dataset", "*.mp4")))
+    os.makedirs(args.out, exist_ok=True)
+
+    manifest = []
+    for vi, video in enumerate(videos, 1):
+        ap_path = os.path.abspath(video).replace("\\", "/")
+        cap = cv2.VideoCapture(ap_path)
+        if not cap.isOpened():
+            print("OPEN_FAIL", video, file=sys.stderr)
+            continue
+        vdir = "v%02d" % vi  # ASCII 目录名,规避 cv2.imwrite 中文路径问题
+        outdir = os.path.join(args.out, vdir)
+        os.makedirs(outdir, exist_ok=True)
+
+        fps = cap.get(cv2.CAP_PROP_FPS)
+        saved, idx = 0, 0
+        while True:
+            ok, frame = cap.read()
+            if not ok or frame is None:
+                break
+            if idx % args.every == 0:
+                # 路径全程 ASCII,imwrite 安全
+                path = os.path.join(outdir, "frame_%06d.jpg" % idx).replace("\\", "/")
+                cv2.imwrite(path, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
+                saved += 1
+            idx += 1
+        cap.release()
+        manifest.append({
+            "dir": vdir,
+            "source": os.path.basename(video),
+            "frames": idx,
+            "fps": "%.2f" % fps,
+            "extracted": saved,
+        })
+        print("%s -> %-60s frames=%d saved=%d" % (vdir, os.path.basename(video)[:60], idx, saved))
+
+    with open(os.path.join(args.out, "manifest.csv"), "w", newline="", encoding="utf-8-sig") as fh:
+        w = csv.DictWriter(fh, fieldnames=["dir", "source", "frames", "fps", "extracted"])
+        w.writeheader()
+        w.writerows(manifest)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 90 - 0
scripts/organize_web_cc.py

@@ -0,0 +1,90 @@
+"""把 web_cc 按业务类别重组:敞车 / 平车 / 其他(棚车负样本)。
+
+重命名规则:车型_001.jpg、车型_002.jpg ...
+例:C70E_001.jpg、X70_001.jpg、P62_001.jpg
+
+- 敞车(状态1):C64, C64K, C70, C70E, C70H, C80
+- 平车(状态2):X70, NX70, X160
+- 其他(状态0负样本):P62, P64
+
+同步更新 LICENSES.csv 与 analysis.csv 中的文件名/路径。
+用法:python scripts/organize_web_cc.py
+"""
+from __future__ import annotations
+
+import csv
+import os
+import shutil
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+BASE = os.path.join(ROOT, "dataset", "web_cc")
+
+GROUPS = {
+    "敞车": ["C70E", "C70H", "C70", "C64K", "C64", "C80"],
+    "平车": ["NX70", "X70", "X160"],
+    "其他": ["P62", "P64"],
+}
+TYPE2GROUP = {t: g for g, types in GROUPS.items() for t in types}
+EXTS = (".jpg", ".jpeg", ".png")
+
+
+def main() -> int:
+    moved = {}  # old basename -> new rel path
+    for group, types in GROUPS.items():
+        gdir = os.path.join(BASE, group)
+        os.makedirs(gdir, exist_ok=True)
+        for t in types:
+            src_dir = os.path.join(BASE, t)
+            if not os.path.isdir(src_dir):
+                continue
+            files = sorted(f for f in os.listdir(src_dir) if f.lower().endswith(EXTS))
+            for i, f in enumerate(files, 1):
+                ext = os.path.splitext(f)[1].lower()
+                new_name = "%s_%03d%s" % (t, i, ext)
+                src = os.path.join(src_dir, f)
+                dst = os.path.join(gdir, new_name)
+                if os.path.abspath(src) != os.path.abspath(dst):
+                    shutil.move(src, dst)
+                moved[f] = os.path.join(group, new_name).replace("\\", "/")
+                print("%-10s -> %s/%s" % (f[:10], group, new_name), file=sys.stderr)
+            if not os.listdir(src_dir):
+                os.rmdir(src_dir)
+
+    # 同步 LICENSES.csv
+    lic_path = os.path.join(BASE, "LICENSES.csv")
+    if os.path.isfile(lic_path):
+        with open(lic_path, encoding="utf-8-sig") as fh:
+            rows = list(csv.DictReader(fh))
+        for r in rows:
+            old = os.path.basename(r["url"])
+            # 从 title 提取原文件名更可靠
+            title = r.get("title", "")
+            old_name = title[5:] if title.lower().startswith("file:") else title
+            r["organized_path"] = moved.get(old_name, "")
+        with open(lic_path, "w", newline="", encoding="utf-8-sig") as fh:
+            w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
+            w.writeheader()
+            w.writerows(rows)
+
+    # 同步 analysis.csv
+    ana_path = os.path.join(BASE, "analysis.csv")
+    if os.path.isfile(ana_path):
+        with open(ana_path, encoding="utf-8-sig") as fh:
+            rows = list(csv.DictReader(fh))
+        for r in rows:
+            r["organized_path"] = moved.get(r["file"], "")
+        with open(ana_path, "w", newline="", encoding="utf-8-sig") as fh:
+            w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
+            w.writeheader()
+            w.writerows(rows)
+
+    print("moved %d files" % len(moved))
+    for g in GROUPS:
+        n = len([f for f in os.listdir(os.path.join(BASE, g)) if f.lower().endswith(EXTS)])
+        print("  %s: %d" % (g, n))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 61 - 0
scripts/vis_detector_boxes.py

@@ -0,0 +1,61 @@
+"""单图打印 detector.timed_infer() 输出并可视化检测框。
+
+用法:
+    python scripts/vis_detector_boxes.py [image] [backend] [config]
+"""
+import os
+import sys
+
+import cv2
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+
+from portcv.config import load_config
+from portcv.detect import build_detector, draw_boxes
+
+
+def main() -> int:
+    img_file = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
+        ROOT, "dataset", "test_data", "32660093_235245226128_2.jpg"
+    )
+    backend = sys.argv[2] if len(sys.argv) > 2 else ""
+    cfg_file = sys.argv[3] if len(sys.argv) > 3 else os.path.join(ROOT, "configs", "default.json")
+
+    cfg = load_config(cfg_file)
+    detector = build_detector(cfg, backend=backend)
+    print("detector:", detector.describe())
+
+    image = cv2.imread(img_file)
+    if image is None:
+        print("cannot read image:", img_file)
+        return 1
+    h, w = image.shape[:2]
+    print("image:", img_file, "size:", w, "x", h)
+
+    boxes = detector.timed_infer(image)
+    print("infer_ms: %.3f" % detector.infer_ms)
+    print("boxes count:", len(boxes))
+    for i, box in enumerate(boxes):
+        print("box[%d]: %s" % (i, box.to_dict()))
+
+    vis = image.copy()
+    roi_px = [(int(x * w), int(y * h)) for x, y in cfg.roi]
+    texts = [
+        "backend=%s" % detector.name,
+        "infer_ms=%.2f boxes=%d" % (detector.infer_ms, len(boxes)),
+    ]
+    draw_boxes(vis, boxes, roi=roi_px, texts=texts)
+
+    out_dir = os.path.join(ROOT, "runs", "detector_vis")
+    os.makedirs(out_dir, exist_ok=True)
+    out_path = os.path.join(
+        out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg"
+    )
+    cv2.imwrite(out_path, vis)
+    print("saved:", out_path)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 86 - 0
scripts/vis_detector_boxes_batch.py

@@ -0,0 +1,86 @@
+"""批量打印 detector.timed_infer() 输出并可视化检测框。
+
+用法:
+    python scripts/vis_detector_boxes_batch.py [image_dir] [backend] [config] [out_dir]
+"""
+import os
+import sys
+import time
+
+import cv2
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+
+from portcv.config import load_config
+from portcv.detect import build_detector, draw_boxes
+
+IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
+
+
+def iter_images(root: str):
+    for name in sorted(os.listdir(root)):
+        if name.lower().endswith(IMAGE_EXTS):
+            yield os.path.join(root, name)
+
+
+def main() -> int:
+    img_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
+        ROOT, "dataset", "railcar-final-v1.v1i.yolov11", "test", "images"
+    )
+    backend = sys.argv[2] if len(sys.argv) > 2 else ""
+    cfg_file = sys.argv[3] if len(sys.argv) > 3 else os.path.join(ROOT, "configs", "default.json")
+    out_dir = sys.argv[4] if len(sys.argv) > 4 else os.path.join(ROOT, "runs", "detector_vis_batch")
+
+    cfg = load_config(cfg_file)
+    detector = build_detector(cfg, backend=backend)
+    os.makedirs(out_dir, exist_ok=True)
+
+    print("detector:", detector.describe())
+    print("image_dir:", img_dir)
+    print("out_dir:", out_dir)
+
+    images = list(iter_images(img_dir))
+    print("images count:", len(images))
+
+    total_boxes = 0
+    total_ms = 0.0
+    failed = 0
+
+    for idx, img_file in enumerate(images, 1):
+        image = cv2.imread(img_file)
+        if image is None:
+            print("[%d/%d] READ_FAIL %s" % (idx, len(images), img_file))
+            failed += 1
+            continue
+        h, w = image.shape[:2]
+
+        boxes = detector.timed_infer(image)
+        infer_ms = detector.infer_ms
+        total_boxes += len(boxes)
+        total_ms += infer_ms
+
+        print("[%d/%d] %s  size=%dx%d  infer_ms=%.3f  boxes=%d" % (
+            idx, len(images), os.path.basename(img_file), w, h, infer_ms, len(boxes)
+        ))
+        for i, box in enumerate(boxes):
+            print("    box[%d]: %s" % (i, box.to_dict()))
+
+        vis = image.copy()
+        roi_px = [(int(x * w), int(y * h)) for x, y in cfg.roi]
+        draw_boxes(vis, boxes, roi=roi_px, texts=[
+            "backend=%s" % detector.name,
+            "boxes=%d infer_ms=%.2f" % (len(boxes), infer_ms),
+        ])
+        out_path = os.path.join(out_dir, os.path.splitext(os.path.basename(img_file))[0] + "_boxes.jpg")
+        cv2.imwrite(out_path, vis)
+
+    print("---- summary ----")
+    print("images=%d failed=%d total_boxes=%d avg_infer_ms=%.3f" % (
+        len(images), failed, total_boxes, total_ms / max(1, len(images) - failed)
+    ))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())