pipeline.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """单帧处理流水线:推理 → 场景判定 → 时序防抖。
  2. 把这三步封在一起的好处:**同一份逻辑**既能被常驻服务使用,也能被自检/回放工具
  3. 逐帧调用(:mod:`portcv.cli` 的 ``selftest`` / ``replay``),测试里也只需要构造一个
  4. :class:`VisionPipeline` 就能覆盖全链路。
  5. """
  6. from __future__ import annotations
  7. import logging
  8. from typing import Dict, Optional, Tuple
  9. from ..config import Config
  10. from ..detect import Detector, build_detector
  11. from ..detect.postproc import draw_boxes
  12. from ..io.capture import Frame
  13. from ..logic import SceneClassifier, TemporalVoter
  14. from ..logic.evidence_v2 import EvidenceV2
  15. from ..schema import Decision, Observation
  16. __all__ = ["VisionPipeline"]
  17. _LOG = logging.getLogger(__name__)
  18. class VisionPipeline:
  19. """推理 + 判定流水线(线程内使用,非线程安全)。"""
  20. def __init__(self, cfg: Config, detector: Optional[Detector] = None) -> None:
  21. self.cfg = cfg
  22. self.detector: Detector = detector or build_detector(cfg)
  23. self.classifier = SceneClassifier(cfg)
  24. self.voter = TemporalVoter.from_config(cfg)
  25. # P1b/P1c:显式启用后才替换逐帧判定链路;默认保持既有行为。
  26. self.evidence_v2 = (
  27. EvidenceV2.from_config(cfg)
  28. if bool(cfg.get_path("evidence_v2.enabled", False))
  29. else None
  30. )
  31. self._plc_arrival_pending = False
  32. self._loaded = False
  33. self._warmup_frames = 0
  34. self.frames = 0
  35. self.last_ms = 0.0
  36. if (self.evidence_v2 is not None
  37. and bool(cfg.get_path("evidence_v2.commit.use_plc_arrival", False))):
  38. # 说清楚"为什么配了也不生效":PLC 命令区目前没有"开始下放/到位/
  39. # 吊具松开"位(docs/plc_interface.md §7 第 11 条待确认),因此除了
  40. # 显式调用 note_plc_arrival() 之外没有信号源。
  41. _LOG.warning(
  42. "evidence_v2.commit.use_plc_arrival=true,但 PLC 命令区尚无"
  43. "到位/吊具松开信号(plc_interface §7 #11);未调用 "
  44. "note_plc_arrival() 时本开关等价于 off,commit 仍只看 gap_px/gap_m"
  45. )
  46. # ------------------------------------------------------------ 生命周期
  47. def load(self) -> None:
  48. if self._loaded:
  49. return
  50. self.detector.load()
  51. self._loaded = True
  52. def warmup(self, frames: Optional[int] = None) -> int:
  53. """预热推理后端;返回实际预热帧数。``run.warmup_frames=0`` 表示跳过。"""
  54. count = int(frames if frames is not None else self.cfg.get_path("run.warmup_frames", 3))
  55. if count <= 0:
  56. return 0
  57. self.load()
  58. self.detector.warmup(count)
  59. self._warmup_frames = count
  60. return count
  61. def close(self) -> None:
  62. try:
  63. self.detector.close()
  64. except Exception: # pragma: no cover - 释放失败不影响退出
  65. pass
  66. self._loaded = False
  67. # ------------------------------------------------------------ 主入口
  68. def step(self, frame: Frame) -> Tuple[Observation, Decision]:
  69. """处理一帧,返回 ``(单帧观测, 时序判决)``。"""
  70. boxes = self.detector.timed_infer(frame.image)
  71. if self.evidence_v2 is not None:
  72. observation = self.evidence_v2.classify(
  73. frame.image,
  74. ts=frame.ts,
  75. frame_id=frame.frame_id,
  76. plc_arrived=self._plc_arrival_pending,
  77. detections=boxes,
  78. )
  79. self._plc_arrival_pending = False
  80. else:
  81. observation = self.classifier.classify(
  82. boxes,
  83. frame.size,
  84. ts=frame.ts,
  85. frame_id=frame.frame_id,
  86. )
  87. decision = self.voter.update(observation)
  88. self.frames += 1
  89. self.last_ms = float(self.detector.infer_ms)
  90. return observation, decision
  91. def current(self) -> Decision:
  92. """不喂新帧,取当前判决(用于心跳/按需识别之间的空档期)。"""
  93. return self.voter.current()
  94. def reset(self) -> None:
  95. """PLC 复位命令:清空投票窗口与当前状态。"""
  96. self.voter.reset()
  97. if self.evidence_v2 is not None:
  98. self.evidence_v2.reset()
  99. self._plc_arrival_pending = False
  100. def note_plc_arrival(self, arrived: bool = True) -> None:
  101. """可选 PLC “到位/吊具松开”信号:下一帧 commit 门可用它替代间隙门。"""
  102. self._plc_arrival_pending = bool(arrived)
  103. def annotate(self, frame: Frame, observation: Optional[Observation] = None, decision: Optional[Decision] = None):
  104. """在帧上画框/ROI/状态,返回同一张图(联调预览与难例存档用)。"""
  105. boxes = observation.detections if observation is not None else []
  106. roi = self.classifier.roi_polygon(*frame.size)
  107. texts = []
  108. if decision is not None:
  109. texts.append("state=%d %s conf=%.2f seq=%d" % (
  110. int(decision.state), decision.label, decision.confidence, int(decision.seq)
  111. ))
  112. return draw_boxes(frame.image, boxes, roi, texts)
  113. # ------------------------------------------------------------ 属性
  114. @property
  115. def ready(self) -> bool:
  116. return bool(self._loaded and self._warmup_frames > 0)
  117. @property
  118. def warmup_frames(self) -> int:
  119. return int(self._warmup_frames)
  120. def describe(self) -> Dict[str, object]:
  121. info: Dict[str, object] = dict(self.detector.describe())
  122. info.update(
  123. {
  124. "scene_mode": (
  125. "evidence_v2" if self.evidence_v2 is not None else self.classifier.mode
  126. ),
  127. "roi": [[round(x, 4), round(y, 4)] for x, y in self.cfg.roi],
  128. "evidence_v2": (
  129. self.evidence_v2.last.to_dict() if self.evidence_v2 is not None else None
  130. ),
  131. "decision": dict(self.cfg.section("decision")),
  132. "loaded": self._loaded,
  133. "warmup_frames": self._warmup_frames,
  134. "frames": self.frames,
  135. }
  136. )
  137. return info