| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163 |
- """单帧处理流水线:推理 → 场景判定 → 时序防抖。
- 把这三步封在一起的好处:**同一份逻辑**既能被常驻服务使用,也能被自检/回放工具
- 逐帧调用(:mod:`portcv.cli` 的 ``selftest`` / ``replay``),测试里也只需要构造一个
- :class:`VisionPipeline` 就能覆盖全链路。
- """
- from __future__ import annotations
- import logging
- from typing import Dict, Optional, Tuple
- from ..config import Config
- from ..detect import Detector, build_detector
- from ..detect.postproc import draw_boxes
- from ..io.capture import Frame
- from ..logic import SceneClassifier, TemporalVoter
- from ..logic.evidence_v2 import EvidenceV2
- from ..schema import Decision, Observation
- __all__ = ["VisionPipeline"]
- _LOG = logging.getLogger(__name__)
- class VisionPipeline:
- """推理 + 判定流水线(线程内使用,非线程安全)。"""
- def __init__(self, cfg: Config, detector: Optional[Detector] = None) -> None:
- self.cfg = cfg
- self.detector: Detector = detector or build_detector(cfg)
- self.classifier = SceneClassifier(cfg)
- self.voter = TemporalVoter.from_config(cfg)
- # P1b/P1c:显式启用后才替换逐帧判定链路;默认保持既有行为。
- self.evidence_v2 = (
- EvidenceV2.from_config(cfg)
- if bool(cfg.get_path("evidence_v2.enabled", False))
- else None
- )
- self._plc_arrival_pending = False
- self._loaded = False
- self._warmup_frames = 0
- self.frames = 0
- self.last_ms = 0.0
- if (self.evidence_v2 is not None
- and bool(cfg.get_path("evidence_v2.commit.use_plc_arrival", False))):
- # 说清楚"为什么配了也不生效":PLC 命令区目前没有"开始下放/到位/
- # 吊具松开"位(docs/plc_interface.md §7 第 11 条待确认),因此除了
- # 显式调用 note_plc_arrival() 之外没有信号源。
- _LOG.warning(
- "evidence_v2.commit.use_plc_arrival=true,但 PLC 命令区尚无"
- "到位/吊具松开信号(plc_interface §7 #11);未调用 "
- "note_plc_arrival() 时本开关等价于 off,commit 仍只看 gap_px/gap_m"
- )
- # ------------------------------------------------------------ 生命周期
- def load(self) -> None:
- if self._loaded:
- return
- self.detector.load()
- self._loaded = True
- def warmup(self, frames: Optional[int] = None) -> int:
- """预热推理后端;返回实际预热帧数。``run.warmup_frames=0`` 表示跳过。"""
- count = int(frames if frames is not None else self.cfg.get_path("run.warmup_frames", 3))
- if count <= 0:
- return 0
- self.load()
- self.detector.warmup(count)
- self._warmup_frames = count
- return count
- def close(self) -> None:
- try:
- self.detector.close()
- except Exception: # pragma: no cover - 释放失败不影响退出
- pass
- self._loaded = False
- # ------------------------------------------------------------ 主入口
- def step(self, frame: Frame) -> Tuple[Observation, Decision]:
- """处理一帧,返回 ``(单帧观测, 时序判决)``。"""
- boxes = self.detector.timed_infer(frame.image)
- if self.evidence_v2 is not None:
- observation = self.evidence_v2.classify(
- frame.image,
- ts=frame.ts,
- frame_id=frame.frame_id,
- plc_arrived=self._plc_arrival_pending,
- detections=boxes,
- )
- self._plc_arrival_pending = False
- else:
- observation = self.classifier.classify(
- boxes,
- frame.size,
- ts=frame.ts,
- frame_id=frame.frame_id,
- )
- decision = self.voter.update(observation)
- self.frames += 1
- self.last_ms = float(self.detector.infer_ms)
- return observation, decision
- def current(self) -> Decision:
- """不喂新帧,取当前判决(用于心跳/按需识别之间的空档期)。"""
- return self.voter.current()
- def reset(self) -> None:
- """PLC 复位命令:清空投票窗口与当前状态。"""
- self.voter.reset()
- if self.evidence_v2 is not None:
- self.evidence_v2.reset()
- self._plc_arrival_pending = False
- def note_plc_arrival(self, arrived: bool = True) -> None:
- """可选 PLC “到位/吊具松开”信号:下一帧 commit 门可用它替代间隙门。"""
- self._plc_arrival_pending = bool(arrived)
- def annotate(self, frame: Frame, observation: Optional[Observation] = None, decision: Optional[Decision] = None):
- """在帧上画框/ROI/状态,返回同一张图(联调预览与难例存档用)。"""
- boxes = observation.detections if observation is not None else []
- roi = self.classifier.roi_polygon(*frame.size)
- texts = []
- if decision is not None:
- texts.append("state=%d %s conf=%.2f seq=%d" % (
- int(decision.state), decision.label, decision.confidence, int(decision.seq)
- ))
- return draw_boxes(frame.image, boxes, roi, texts)
- # ------------------------------------------------------------ 属性
- @property
- def ready(self) -> bool:
- return bool(self._loaded and self._warmup_frames > 0)
- @property
- def warmup_frames(self) -> int:
- return int(self._warmup_frames)
- def describe(self) -> Dict[str, object]:
- info: Dict[str, object] = dict(self.detector.describe())
- info.update(
- {
- "scene_mode": (
- "evidence_v2" if self.evidence_v2 is not None else self.classifier.mode
- ),
- "roi": [[round(x, 4), round(y, 4)] for x, y in self.cfg.roi],
- "evidence_v2": (
- self.evidence_v2.last.to_dict() if self.evidence_v2 is not None else None
- ),
- "decision": dict(self.cfg.section("decision")),
- "loaded": self._loaded,
- "warmup_frames": self._warmup_frames,
- "frames": self.frames,
- }
- )
- return info
|