mock.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Mock 检测器:无模型也能跑通全链路(联调 PLC、验证状态机、跑回归测试)。
  2. 脚本用 **归一化坐标**(0..1)描述,``infer`` 时按实际帧尺寸展开,因此与分辨率无关。
  3. 默认脚本按"车斗 → 平板车 → 只有箱(不在车上)→ 空场景"循环,方便现场演示三种反馈值。
  4. """
  5. from __future__ import annotations
  6. from typing import Dict, List, Optional, Sequence, Tuple
  7. import numpy as np
  8. from ..config import Config
  9. from ..schema import Box
  10. from .base import Detector
  11. __all__ = ["MockDetector", "build_demo_script"]
  12. #: 每个剧本元素:(类别名, 归一化 x1, y1, x2, y2, 分数)
  13. ScriptFrame = List[Tuple[str, float, float, float, float, float]]
  14. def build_demo_script() -> List[ScriptFrame]:
  15. """默认演示剧本,覆盖 1 / 2 / 0 / UNKNOWN 四种情况。"""
  16. return [
  17. # 车斗:集装箱坐在带斗车厢上
  18. [
  19. ("container", 0.30, 0.28, 0.72, 0.62, 0.91),
  20. ("bed", 0.27, 0.62, 0.75, 0.88, 0.86),
  21. ],
  22. # 平板车:集装箱坐在平板车上
  23. [
  24. ("container", 0.32, 0.30, 0.70, 0.60, 0.89),
  25. ("flatbed", 0.28, 0.60, 0.74, 0.84, 0.83),
  26. ],
  27. # 只有集装箱(被吊起/在卡车上)→ 0
  28. [
  29. ("container", 0.34, 0.22, 0.68, 0.50, 0.88),
  30. ],
  31. # 空场景 → UNKNOWN(可配置成 0)
  32. [],
  33. ]
  34. class MockDetector(Detector):
  35. """按剧本循环输出检测框,用于自检与演示。"""
  36. name = "mock"
  37. def __init__(self, cfg: Config, script: Optional[Sequence[ScriptFrame]] = None) -> None:
  38. super().__init__(cfg)
  39. self.script: List[ScriptFrame] = [list(frame) for frame in (script or build_demo_script())]
  40. if not self.script:
  41. self.script = [[]]
  42. self._cursor = 0
  43. def infer(self, frame: np.ndarray) -> List[Box]:
  44. height, width = frame.shape[:2]
  45. raw = self.script[self._cursor % len(self.script)]
  46. self._cursor += 1
  47. boxes: List[Box] = []
  48. for name, x1, y1, x2, y2, score in raw:
  49. class_id = self.labels.index(name) if name in self.labels else -1
  50. boxes.append(
  51. Box(
  52. x1 * width,
  53. y1 * height,
  54. x2 * width,
  55. y2 * height,
  56. score=float(score),
  57. class_id=class_id,
  58. class_name=str(name),
  59. )
  60. )
  61. return boxes
  62. def reset(self) -> None:
  63. self._cursor = 0
  64. def describe(self) -> Dict[str, object]:
  65. info = super().describe()
  66. info["script_frames"] = len(self.script)
  67. return info