synthetic.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """合成帧源:没有相机/视频也能跑通整条链路(CI、自检、演示、PLC 联调)。
  2. 接口与 :class:`~portcv.io.capture.FrameGrabber` 保持一致(``start/stop/latest/fresh/fps/
  3. frame_id/describe``),因此可以直接注入 :class:`~portcv.service.runner.RunService`
  4. 替换真实抓帧器——这也是 ``portcv selftest`` 与单元测试能"零硬件"跑全链路的原因。
  5. 画面里会画一个来回移动的矩形,配合 ``run.preview`` 一眼就能看出服务是否在跑。
  6. """
  7. from __future__ import annotations
  8. import threading
  9. import time
  10. from typing import Dict, Optional, Tuple
  11. import numpy as np
  12. from ..config import Config
  13. from .capture import Frame
  14. __all__ = ["SyntheticGrabber"]
  15. class SyntheticGrabber:
  16. """按固定帧率生成假画面的抓帧器(后台线程 + 只保留最新帧)。"""
  17. def __init__(
  18. self,
  19. cfg: Optional[Config] = None,
  20. fps: float = 25.0,
  21. size: Tuple[int, int] = (1280, 720),
  22. stale_frame_s: float = 0.6,
  23. image: Optional[np.ndarray] = None,
  24. ) -> None:
  25. source = cfg.section("source") if cfg is not None else {}
  26. self.fps_target = max(0.5, float(fps))
  27. if cfg is not None and source.get("width") and source.get("height"):
  28. size = (int(source["width"]), int(source["height"]))
  29. self.size = (int(size[0]), int(size[1]))
  30. self.stale_frame_s = float(
  31. stale_frame_s if cfg is None else source.get("stale_frame_s", stale_frame_s)
  32. )
  33. self.use_fixed_image = image is not None
  34. self._image = image if image is not None else self._make_background()
  35. self._lock = threading.Lock()
  36. self._stop = threading.Event()
  37. self._thread: Optional[threading.Thread] = None
  38. self._frame: Optional[Frame] = None
  39. self._frame_id = 0
  40. self._fps = 0.0
  41. self._last_ts = 0.0
  42. self._phase = 0.0
  43. # ------------------------------------------------------------ 画面生成
  44. def _make_background(self) -> np.ndarray:
  45. width, height = self.size
  46. rows = np.linspace(40, 200, height, dtype=np.uint8).reshape(height, 1)
  47. cols = np.linspace(40, 120, width, dtype=np.uint8).reshape(1, width)
  48. base = np.clip(rows.astype(np.int16) + cols.astype(np.int16), 0, 255).astype(np.uint8)
  49. return np.dstack([base, base, base]).copy()
  50. def _render(self) -> np.ndarray:
  51. if self.use_fixed_image:
  52. return self._image
  53. image = self._image.copy()
  54. height, width = image.shape[:2]
  55. band_y = int(height * 0.62)
  56. image[band_y:, :] = 90 # 车厢/地面
  57. self._phase = (self._phase + 0.04) % 1.0
  58. cx = int(width * (0.2 + 0.6 * self._phase))
  59. half = int(width * 0.16)
  60. half_h = int(height * 0.14)
  61. cy = band_y - half_h
  62. x1, x2 = max(0, cx - half), min(width - 1, cx + half)
  63. y1, y2 = max(0, cy - half_h), min(height - 1, cy + half_h)
  64. image[y1:y2, x1:x2] = (60, 140, 200) # 集装箱
  65. return image
  66. # ------------------------------------------------------------ 生命周期
  67. def start(self) -> "SyntheticGrabber":
  68. if self._thread is not None:
  69. return self
  70. self._thread = threading.Thread(target=self._loop, name="synthetic-grabber", daemon=True)
  71. self._thread.start()
  72. return self
  73. def stop(self, timeout: float = 2.0) -> None:
  74. self._stop.set()
  75. if self._thread is not None:
  76. self._thread.join(timeout=timeout)
  77. self._thread = None
  78. def _loop(self) -> None:
  79. period = 1.0 / self.fps_target
  80. while not self._stop.is_set():
  81. started = time.time()
  82. image = self._render()
  83. now = time.time()
  84. self._frame_id += 1
  85. delta = now - self._last_ts if self._last_ts else period
  86. self._last_ts = now
  87. inst = 1.0 / delta if delta > 0 else self.fps_target
  88. self._fps = inst if self._fps <= 0 else 0.8 * self._fps + 0.2 * inst
  89. with self._lock:
  90. self._frame = Frame(image=image, ts=now, frame_id=self._frame_id)
  91. self._stop.wait(max(0.0, period - (time.time() - started)))
  92. # ------------------------------------------------------------ 兼容接口
  93. @property
  94. def latest(self) -> Optional[Frame]:
  95. with self._lock:
  96. return self._frame
  97. @property
  98. def fresh(self) -> bool:
  99. frame = self.latest
  100. return frame is not None and (time.time() - frame.ts) <= self.stale_frame_s
  101. def read(self, timeout: float = 1.0) -> Optional[Frame]:
  102. deadline = time.time() + max(0.0, timeout)
  103. while True:
  104. frame = self.latest
  105. if frame is not None:
  106. return frame
  107. if time.time() >= deadline:
  108. return None
  109. time.sleep(0.005)
  110. @property
  111. def fps(self) -> float:
  112. return float(self._fps)
  113. @property
  114. def frame_id(self) -> int:
  115. return int(self._frame_id)
  116. @property
  117. def opened(self) -> bool:
  118. return True
  119. def describe(self) -> Dict[str, object]:
  120. return {
  121. "source_type": "synthetic",
  122. "size": list(self.size),
  123. "target_fps": self.fps_target,
  124. "fps": round(self.fps, 2),
  125. "frame_id": self.frame_id,
  126. }