| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372 |
- """P1c:落位(commit)相位判定。
- 为什么需要单独的 commit 门
- ---------------------------
- ``evidence_v2`` 回答的是“这一帧看起来像 1 还是 2”;PLC 真正需要的是
- “**箱已经落到位,可以按这个车型执行落箱工艺**”。两者不能混为一谈:
- * A 片段(C70 敞车 + 罐箱)在 clip 结束时仍差 ≈0.2 m,但单帧间隙只有
- 9–12 px,按 0.10 m 的单一阈值可能误命中;
- * B 片段(X70 平车)落位帧间隙只有 3 px,必须允许提交。
- 因此本模块用**组合条件**而不是单一阈值:
- 1. ``gap_m <= gap_m_max``(默认 0.10 m);
- 2. **安全硬门** ``gap_px <= gap_px_hard_max``(默认 8 px)——前视模式箱底
- 像素本身有 ±5 px 不确定度,0.10 m 在 115 px/m 下约 11.5 px;加这条
- 可以确保 A 的 9–12 px 不会提交,同时 B 的 3 px 仍能通过;
- 3. 最近 ``stable_frames`` 帧状态一致、结构证据持续成立;
- 4. 运动门控通过,间隙没有明显回升;
- 5. 可选 PLC “到位 / 吊具松开”信号可**替代**间隙门(但仍需结构与稳定帧)。
- ``allow_state2`` 默认 **True**(现场验收后已打开):平车 `2` 与 `1` 一样进入
- commit;置 false 可回退为“只识别、不提交”。顶层 ``evidence_v2.allow_state2``
- 与 ``evidence_v2.commit.allow_state2`` 串联,任一 false 都会关闭提交。
- 本模块不依赖 OpenCV / numpy,只做状态机;图像特征由
- :mod:`portcv.logic.evidence_v2` 提供。
- """
- from __future__ import annotations
- from collections import deque
- from dataclasses import dataclass
- from typing import Deque, Optional, Tuple
- from ..config import Config
- __all__ = [
- "CommitParams",
- "CommitState",
- "CommitTracker",
- "DEFAULT_GAP_M_MAX",
- "DEFAULT_GAP_PX_HARD_MAX",
- ]
- #: 路线文档锁定的间隙门(米)。
- DEFAULT_GAP_M_MAX = 0.10
- #: 前视箱底像素不确定度对应的安全硬门(≈0.07 m @ 115 px/m)。
- DEFAULT_GAP_PX_HARD_MAX = 8.0
- #: 箱底与车面直接贴合(flat_contact 归零)的容差;该分支不要求 px_per_m。
- CONTACT_GAP_PX = 1.0
- @dataclass(frozen=True)
- class CommitParams:
- """commit 门参数(对应配置段 ``evidence_v2.commit.*``)。"""
- gap_m_max: float = DEFAULT_GAP_M_MAX
- gap_px_hard_max: float = DEFAULT_GAP_PX_HARD_MAX
- stable_frames: int = 5
- structure_frames: int = 5
- min_structure_hits: float = 0.60
- max_gap_rise_m: float = 0.01
- allow_state1: bool = True
- allow_state2: bool = True
- # P0-Q9:空车 state=3 是否允许提交。false = 只识别、不提交(与 allow_state2 同构)。
- allow_state3: bool = True
- require_motion_ok: bool = True
- require_view_known: bool = True
- use_plc_arrival: bool = True
- def __post_init__(self) -> None:
- if self.gap_m_max < 0.0:
- raise ValueError("gap_m_max 不能为负")
- if self.gap_px_hard_max < 0.0:
- raise ValueError("gap_px_hard_max 不能为负")
- if self.stable_frames < 1:
- raise ValueError("stable_frames 至少为 1")
- if self.structure_frames < 1:
- raise ValueError("structure_frames 至少为 1")
- if not 0.0 <= self.min_structure_hits <= 1.0:
- raise ValueError("min_structure_hits 必须在 0..1")
- @classmethod
- def from_config(cls, cfg: Config) -> "CommitParams":
- section = cfg.section("evidence_v2")
- raw = section.get("commit") or {}
- # 与 C++ `apply_evidence_v2` 同口径:顶层与 commit 两个开关串联,任一 false 即关闭。
- allow_state2 = bool(raw.get("allow_state2", True)) and bool(
- section.get("allow_state2", True)
- )
- allow_state3 = bool(raw.get("allow_state3", True)) and bool(
- section.get("allow_state3", True)
- )
- return cls(
- gap_m_max=float(raw.get("gap_m_max", DEFAULT_GAP_M_MAX)),
- gap_px_hard_max=float(raw.get("gap_px_hard_max", DEFAULT_GAP_PX_HARD_MAX)),
- stable_frames=int(raw.get("stable_frames", 5)),
- structure_frames=int(raw.get("structure_frames", 5)),
- min_structure_hits=float(raw.get("min_structure_hits", 0.60)),
- max_gap_rise_m=float(raw.get("max_gap_rise_m", 0.01)),
- allow_state1=bool(raw.get("allow_state1", True)),
- allow_state2=allow_state2,
- allow_state3=allow_state3,
- require_motion_ok=bool(raw.get("require_motion_ok", True)),
- require_view_known=bool(raw.get("require_view_known", True)),
- use_plc_arrival=bool(raw.get("use_plc_arrival", True)),
- )
- @dataclass(frozen=True)
- class CommitState:
- """``CommitTracker.update()`` 的输出(可直接写进 evidence 诊断)。"""
- committed: bool
- phase: str # T1 / T2 / T3
- reason: str
- gap_m: Optional[float] = None
- gap_px: Optional[float] = None
- stable_frames: int = 0
- structure_frames: int = 0
- gap_slope_m_per_s: Optional[float] = None
- plc_arrival: bool = False
- hoist_high: bool = False
- def to_dict(self) -> dict:
- return {
- "committed": bool(self.committed),
- "phase": self.phase,
- "reason": self.reason,
- "gap_m": None if self.gap_m is None else round(float(self.gap_m), 4),
- "gap_px": None if self.gap_px is None else round(float(self.gap_px), 2),
- "stable_frames": int(self.stable_frames),
- "structure_frames": int(self.structure_frames),
- "gap_slope_m_per_s": (
- None if self.gap_slope_m_per_s is None
- else round(float(self.gap_slope_m_per_s), 4)
- ),
- "plc_arrival": bool(self.plc_arrival),
- "hoist_high": bool(self.hoist_high),
- }
- @dataclass
- class _Sample:
- ts: float
- state: int
- gap_m: Optional[float]
- gap_px: Optional[float]
- structure_ok: bool
- motion_ok: bool
- class CommitTracker:
- """有状态的 commit 判定器(线程内使用、非线程安全)。"""
- def __init__(self, params: Optional[CommitParams] = None) -> None:
- self.p = params or CommitParams()
- self._samples: Deque[_Sample] = deque(maxlen=256)
- self._last_ts = 0.0
- self._last = CommitState(False, "T1", "init")
- @classmethod
- def from_config(cls, cfg: Config) -> "CommitTracker":
- return cls(CommitParams.from_config(cfg))
- @property
- def params(self) -> CommitParams:
- return self.p
- @property
- def last(self) -> CommitState:
- return self._last
- def reset(self) -> None:
- self._samples.clear()
- self._last_ts = 0.0
- self._last = CommitState(False, "T1", "reset")
- # ---------------------------------------------------------------- 主入口
- def update(
- self,
- ts: float,
- *,
- state: int,
- gap_m: Optional[float],
- gap_px: Optional[float],
- structure_hits: float = 1.0,
- motion_ok: bool = True,
- view_known: bool = True,
- plc_arrived: bool = False,
- plc_spreader_released: bool = False,
- hoist_high: bool = False,
- ) -> CommitState:
- """喂入一帧证据,返回是否允许提交。
- ``state`` 是 ``evidence_v2`` 的**单帧分类结果**(0/1/2/255);
- ``structure_hits`` 是该帧结构证据强度(0..1),不是像素计数。
- ``hoist_high`` 表示画面出现吊具/钢缆/臂架高悬特征:箱体尚未落位,
- 无论间隙看起来多小都不得提交(安全门优先于所有几何门)。
- """
- now = float(ts)
- if now < self._last_ts:
- now = self._last_ts
- self._last_ts = now
- state = int(state)
- structure_ok = float(structure_hits) >= self.p.min_structure_hits
- arrival = bool(
- self.p.use_plc_arrival and (plc_arrived or plc_spreader_released)
- )
- # 安全门:吊具/钢缆/臂架仍在画面上方,说明箱体未落位。即使视觉
- # 把箱侧壁误当成车斗门板、算出“零间隙”,也不得累计 commit 帧。
- # 这一分支不写 _samples,避免高悬消失后立刻复用之前的窗口。
- if hoist_high:
- self._last = CommitState(
- False, "T3", "hoist_high", gap_m, gap_px, 0, 0, None, arrival, True
- )
- return self._last
- if state not in (0, 1, 2, 3):
- self._last = CommitState(
- False, "T3" if not motion_ok else "T1", "state_unknown",
- gap_m, gap_px, 0, 0, None, arrival,
- )
- return self._last
- if state == 1 and not self.p.allow_state1:
- self._last = CommitState(False, "T1", "state1_disabled",
- gap_m, gap_px, 0, 0, None, arrival)
- return self._last
- if state == 2 and not self.p.allow_state2:
- # 平车在 PLC 签字前只识别、不提交;仍记录窗口,便于诊断。
- self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
- self._last = CommitState(False, "T1", "state2_disabled",
- gap_m, gap_px, 0, 0, None, arrival)
- return self._last
- if state == 3 and not self.p.allow_state3:
- # 空车 3 同理:只识别、不提交(现场可先观察再打开)。
- self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
- self._last = CommitState(False, "T1", "state3_disabled",
- gap_m, gap_px, 0, 0, None, arrival)
- return self._last
- self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
- if not motion_ok and self.p.require_motion_ok:
- self._last = CommitState(False, "T3", "motion", gap_m, gap_px,
- 0, 0, None, arrival)
- return self._last
- if not view_known and self.p.require_view_known:
- self._last = CommitState(False, "T1", "view_unknown", gap_m, gap_px,
- 0, 0, None, arrival)
- return self._last
- # 0 是“其他/不在车上”,不需要间隙门;仍需稳定帧与正面证据。
- gap_ok = True
- if state in (1, 2):
- if arrival:
- gap_ok = True
- else:
- contact = gap_px is not None and float(gap_px) <= CONTACT_GAP_PX
- gap_ok = (
- gap_px is not None
- and float(gap_px) <= self.p.gap_px_hard_max
- and (
- contact
- or (
- gap_m is not None
- and float(gap_m) <= self.p.gap_m_max
- )
- )
- )
- window = self._window(max(self.p.stable_frames, self.p.structure_frames))
- stable_n = self._same_state_run(state)
- structure_n = sum(1 for s in window if s.structure_ok)
- gap_n = sum(1 for s in window if self._gap_ok(s, arrival))
- slope = self._gap_slope(window)
- stable_enough = stable_n >= self.p.stable_frames
- structure_enough = structure_n >= self.p.structure_frames
- gap_enough = gap_n >= self.p.stable_frames
- not_rising = slope is None or slope <= self.p.max_gap_rise_m
- phase = "T2" if gap_ok else "T1"
- committed = bool(
- gap_ok and stable_enough and structure_enough and gap_enough and not_rising
- )
- reason_parts = []
- if not gap_ok:
- reason_parts.append("gap")
- if not stable_enough:
- reason_parts.append("stable=%d/%d" % (stable_n, self.p.stable_frames))
- if not structure_enough:
- reason_parts.append("structure=%d/%d" % (structure_n, self.p.structure_frames))
- if not gap_enough:
- reason_parts.append("gap_window=%d/%d" % (gap_n, self.p.stable_frames))
- if not not_rising:
- reason_parts.append("gap_rising")
- reason = "commit" if committed else (
- "wait:" + ",".join(reason_parts) if reason_parts else "wait"
- )
- if arrival and committed:
- reason = "commit:plc_arrival"
- self._last = CommitState(
- committed=committed,
- phase=phase,
- reason=reason,
- gap_m=gap_m,
- gap_px=gap_px,
- stable_frames=int(stable_n),
- structure_frames=int(structure_n),
- gap_slope_m_per_s=slope,
- plc_arrival=arrival,
- )
- return self._last
- # ---------------------------------------------------------------- 内部
- def _append(
- self,
- ts: float,
- state: int,
- gap_m: Optional[float],
- gap_px: Optional[float],
- structure_ok: bool,
- motion_ok: bool,
- ) -> None:
- self._samples.append(
- _Sample(ts, int(state), gap_m, gap_px, bool(structure_ok), bool(motion_ok))
- )
- def _window(self, n: int) -> Tuple[_Sample, ...]:
- if n <= 0:
- return tuple()
- return tuple(list(self._samples)[-n:])
- def _same_state_run(self, state: int) -> int:
- count = 0
- for sample in reversed(self._samples):
- if sample.state != int(state):
- break
- count += 1
- return count
- def _gap_ok(self, sample: _Sample, arrival: bool) -> bool:
- if sample.state == 0 or arrival:
- return True
- if sample.gap_px is None or float(sample.gap_px) > self.p.gap_px_hard_max:
- return False
- # 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
- if float(sample.gap_px) <= CONTACT_GAP_PX:
- return True
- return bool(
- sample.gap_m is not None
- and float(sample.gap_m) <= self.p.gap_m_max
- )
- def _gap_slope(self, window: Tuple[_Sample, ...]) -> Optional[float]:
- points = [(s.ts, s.gap_m) for s in window if s.gap_m is not None]
- if len(points) < 2:
- return None
- t0, g0 = points[0]
- t1, g1 = points[-1]
- dt = float(t1) - float(t0)
- if dt <= 1e-6:
- return None
- return (float(g1) - float(g0)) / dt
|