pipeline.py 5.5 KB

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