base.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """检测器抽象基类。
  2. 所有后端(mock / onnxruntime / rknn / tensorrt / deepstream)都实现同一接口,
  3. 上层 :mod:`portcv.service` 因此与硬件无关:换板子只换 ``run.backend``。
  4. """
  5. from __future__ import annotations
  6. import time
  7. from typing import Dict, List, Optional, Sequence
  8. import numpy as np
  9. from ..config import Config
  10. from ..schema import Box
  11. __all__ = ["Detector"]
  12. class Detector:
  13. """检测器接口。``infer`` 必须返回原图坐标系下的 :class:`Box` 列表。"""
  14. name = "base"
  15. def __init__(self, cfg: Config) -> None:
  16. self.cfg = cfg
  17. self.labels: List[str] = cfg.labels
  18. self.input_size = cfg.input_size
  19. self.input_format: str = str(cfg.get_path("model.input_format", "rgb_float"))
  20. self.conf: float = float(cfg.get_path("model.conf", 0.35))
  21. self.iou: float = float(cfg.get_path("model.iou", 0.5))
  22. self.max_det: int = int(cfg.get_path("model.max_det", 60))
  23. self.nms_free: bool = bool(cfg.get_path("model.nms_free", False))
  24. self.quantized: bool = bool(cfg.get_path("model.quantized", False))
  25. self._infer_ms: float = 0.0
  26. # -- 子类实现 ---------------------------------------------------------
  27. def infer(self, frame: np.ndarray) -> List[Box]:
  28. raise NotImplementedError
  29. def load(self) -> None:
  30. """加载模型/引擎(幂等)。"""
  31. def close(self) -> None:
  32. """释放资源。"""
  33. # -- 通用 -------------------------------------------------------------
  34. def warmup(self, frames: int = 3) -> None:
  35. """预热:触发一次图/引擎构建,避免首帧耗时影响节拍。"""
  36. width, height = self.input_size
  37. dummy = np.zeros((height, width, 3), dtype=np.uint8)
  38. for _ in range(max(1, int(frames))):
  39. self.infer(dummy)
  40. @property
  41. def infer_ms(self) -> float:
  42. return self._infer_ms
  43. def timed_infer(self, frame: np.ndarray) -> List[Box]:
  44. """带计时的推理。"""
  45. start = time.perf_counter()
  46. boxes = self.infer(frame)
  47. self._infer_ms = (time.perf_counter() - start) * 1000.0
  48. return boxes
  49. def describe(self) -> Dict[str, object]:
  50. return {
  51. "backend": self.name,
  52. "labels": list(self.labels),
  53. "input_size": list(self.input_size),
  54. "input_format": self.input_format,
  55. "conf": self.conf,
  56. "iou": self.iou,
  57. "nms_free": self.nms_free,
  58. "quantized": self.quantized,
  59. }
  60. # -- 工具 -------------------------------------------------------------
  61. def pick_output(self, outputs: Sequence[np.ndarray]) -> Optional[np.ndarray]:
  62. """从多个输出里挑出检测头张量(兼容导出时附带的多路输出)。"""
  63. nc = len(self.labels)
  64. candidates = []
  65. for out in outputs:
  66. arr = np.asarray(out)
  67. while arr.ndim > 3:
  68. arr = arr[0]
  69. if arr.ndim < 2:
  70. continue
  71. for axis in (1, 0):
  72. if axis < arr.ndim and int(arr.shape[axis]) in (4 + nc, 5 + nc, 6):
  73. candidates.append(arr)
  74. break
  75. if not candidates:
  76. return None
  77. # 取元素最多的那个(通常是真实检测头)
  78. return max(candidates, key=lambda a: int(a.size))