"""检测器抽象基类。 所有后端(mock / onnxruntime / rknn / tensorrt / deepstream)都实现同一接口, 上层 :mod:`portcv.service` 因此与硬件无关:换板子只换 ``run.backend``。 """ from __future__ import annotations import time from typing import Dict, List, Optional, Sequence import numpy as np from ..config import Config from ..schema import Box __all__ = ["Detector"] class Detector: """检测器接口。``infer`` 必须返回原图坐标系下的 :class:`Box` 列表。""" name = "base" def __init__(self, cfg: Config) -> None: self.cfg = cfg self.labels: List[str] = cfg.labels self.input_size = cfg.input_size self.input_format: str = str(cfg.get_path("model.input_format", "rgb_float")) self.conf: float = float(cfg.get_path("model.conf", 0.35)) self.iou: float = float(cfg.get_path("model.iou", 0.5)) self.max_det: int = int(cfg.get_path("model.max_det", 60)) self.nms_free: bool = bool(cfg.get_path("model.nms_free", False)) self.quantized: bool = bool(cfg.get_path("model.quantized", False)) self._infer_ms: float = 0.0 # -- 子类实现 --------------------------------------------------------- def infer(self, frame: np.ndarray) -> List[Box]: raise NotImplementedError def load(self) -> None: """加载模型/引擎(幂等)。""" def close(self) -> None: """释放资源。""" # -- 通用 ------------------------------------------------------------- def warmup(self, frames: int = 3) -> None: """预热:触发一次图/引擎构建,避免首帧耗时影响节拍。""" width, height = self.input_size dummy = np.zeros((height, width, 3), dtype=np.uint8) for _ in range(max(1, int(frames))): self.infer(dummy) @property def infer_ms(self) -> float: return self._infer_ms def timed_infer(self, frame: np.ndarray) -> List[Box]: """带计时的推理。""" start = time.perf_counter() boxes = self.infer(frame) self._infer_ms = (time.perf_counter() - start) * 1000.0 return boxes def describe(self) -> Dict[str, object]: return { "backend": self.name, "labels": list(self.labels), "input_size": list(self.input_size), "input_format": self.input_format, "conf": self.conf, "iou": self.iou, "nms_free": self.nms_free, "quantized": self.quantized, } # -- 工具 ------------------------------------------------------------- def pick_output(self, outputs: Sequence[np.ndarray]) -> Optional[np.ndarray]: """从多个输出里挑出检测头张量(兼容导出时附带的多路输出)。""" nc = len(self.labels) candidates = [] for out in outputs: arr = np.asarray(out) while arr.ndim > 3: arr = arr[0] if arr.ndim < 2: continue for axis in (1, 0): if axis < arr.ndim and int(arr.shape[axis]) in (4 + nc, 5 + nc, 6): candidates.append(arr) break if not candidates: return None # 取元素最多的那个(通常是真实检测头) return max(candidates, key=lambda a: int(a.size))