"""合成帧源:没有相机/视频也能跑通整条链路(CI、自检、演示、PLC 联调)。 接口与 :class:`~portcv.io.capture.FrameGrabber` 保持一致(``start/stop/latest/fresh/fps/ frame_id/describe``),因此可以直接注入 :class:`~portcv.service.runner.RunService` 替换真实抓帧器——这也是 ``portcv selftest`` 与单元测试能"零硬件"跑全链路的原因。 画面里会画一个来回移动的矩形,配合 ``run.preview`` 一眼就能看出服务是否在跑。 """ from __future__ import annotations import threading import time from typing import Dict, Optional, Tuple import numpy as np from ..config import Config from .capture import Frame __all__ = ["SyntheticGrabber"] class SyntheticGrabber: """按固定帧率生成假画面的抓帧器(后台线程 + 只保留最新帧)。""" def __init__( self, cfg: Optional[Config] = None, fps: float = 25.0, size: Tuple[int, int] = (1280, 720), stale_frame_s: float = 0.6, image: Optional[np.ndarray] = None, ) -> None: source = cfg.section("source") if cfg is not None else {} self.fps_target = max(0.5, float(fps)) if cfg is not None and source.get("width") and source.get("height"): size = (int(source["width"]), int(source["height"])) self.size = (int(size[0]), int(size[1])) self.stale_frame_s = float( stale_frame_s if cfg is None else source.get("stale_frame_s", stale_frame_s) ) self.use_fixed_image = image is not None self._image = image if image is not None else self._make_background() self._lock = threading.Lock() self._stop = threading.Event() self._thread: Optional[threading.Thread] = None self._frame: Optional[Frame] = None self._frame_id = 0 self._fps = 0.0 self._last_ts = 0.0 self._phase = 0.0 # ------------------------------------------------------------ 画面生成 def _make_background(self) -> np.ndarray: width, height = self.size rows = np.linspace(40, 200, height, dtype=np.uint8).reshape(height, 1) cols = np.linspace(40, 120, width, dtype=np.uint8).reshape(1, width) base = np.clip(rows.astype(np.int16) + cols.astype(np.int16), 0, 255).astype(np.uint8) return np.dstack([base, base, base]).copy() def _render(self) -> np.ndarray: if self.use_fixed_image: return self._image image = self._image.copy() height, width = image.shape[:2] band_y = int(height * 0.62) image[band_y:, :] = 90 # 车厢/地面 self._phase = (self._phase + 0.04) % 1.0 cx = int(width * (0.2 + 0.6 * self._phase)) half = int(width * 0.16) half_h = int(height * 0.14) cy = band_y - half_h x1, x2 = max(0, cx - half), min(width - 1, cx + half) y1, y2 = max(0, cy - half_h), min(height - 1, cy + half_h) image[y1:y2, x1:x2] = (60, 140, 200) # 集装箱 return image # ------------------------------------------------------------ 生命周期 def start(self) -> "SyntheticGrabber": if self._thread is not None: return self self._thread = threading.Thread(target=self._loop, name="synthetic-grabber", daemon=True) self._thread.start() return self def stop(self, timeout: float = 2.0) -> None: self._stop.set() if self._thread is not None: self._thread.join(timeout=timeout) self._thread = None def _loop(self) -> None: period = 1.0 / self.fps_target while not self._stop.is_set(): started = time.time() image = self._render() now = time.time() self._frame_id += 1 delta = now - self._last_ts if self._last_ts else period self._last_ts = now inst = 1.0 / delta if delta > 0 else self.fps_target self._fps = inst if self._fps <= 0 else 0.8 * self._fps + 0.2 * inst with self._lock: self._frame = Frame(image=image, ts=now, frame_id=self._frame_id) self._stop.wait(max(0.0, period - (time.time() - started))) # ------------------------------------------------------------ 兼容接口 @property def latest(self) -> Optional[Frame]: with self._lock: return self._frame @property def fresh(self) -> bool: frame = self.latest return frame is not None and (time.time() - frame.ts) <= self.stale_frame_s def read(self, timeout: float = 1.0) -> Optional[Frame]: deadline = time.time() + max(0.0, timeout) while True: frame = self.latest if frame is not None: return frame if time.time() >= deadline: return None time.sleep(0.005) @property def fps(self) -> float: return float(self._fps) @property def frame_id(self) -> int: return int(self._frame_id) @property def opened(self) -> bool: return True def describe(self) -> Dict[str, object]: return { "source_type": "synthetic", "size": list(self.size), "target_fps": self.fps_target, "fps": round(self.fps, 2), "frame_id": self.frame_id, }