detect.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """YOLO target detection with EMA smoothing.
  2. Detects the fading white/camouflage TARGET shape.
  3. Green reticle is erased before inference so the model cannot follow the cursor.
  4. """
  5. from __future__ import annotations
  6. from typing import NamedTuple, Optional, Tuple
  7. import numpy as np
  8. from tracker.preprocess import erase_green_reticle
  9. class DetectResult(NamedTuple):
  10. center: Optional[Tuple[float, float]]
  11. conf: float
  12. xyxy: Optional[Tuple[float, float, float, float]]
  13. class EMASmoother:
  14. def __init__(self, alpha: float = 0.35):
  15. self.alpha = alpha
  16. self._xy: Optional[Tuple[float, float]] = None
  17. def reset(self) -> None:
  18. self._xy = None
  19. @property
  20. def value(self) -> Optional[Tuple[float, float]]:
  21. return self._xy
  22. def update(self, xy: Optional[Tuple[float, float]]) -> Optional[Tuple[float, float]]:
  23. if xy is None:
  24. return self._xy
  25. if self._xy is None:
  26. self._xy = xy
  27. return self._xy
  28. ax, ay = self._xy
  29. a = self.alpha
  30. self._xy = (a * xy[0] + (1 - a) * ax, a * xy[1] + (1 - a) * ay)
  31. return self._xy
  32. class TargetDetector:
  33. def __init__(
  34. self,
  35. weights: str,
  36. conf: float = 0.25,
  37. iou: float = 0.45,
  38. device: Optional[str] = None,
  39. ema_alpha: float = 0.35,
  40. erase_green: bool = True,
  41. imgsz: int = 640,
  42. ):
  43. from ultralytics import YOLO
  44. self.model = YOLO(weights)
  45. self.conf = conf
  46. self.iou = iou
  47. self.device = device
  48. self.erase_green = erase_green
  49. self.imgsz = imgsz
  50. self.smoother = EMASmoother(alpha=ema_alpha)
  51. self.last_raw: Optional[Tuple[float, float]] = None
  52. self.last_xyxy: Optional[Tuple[float, float, float, float]] = None
  53. self.last_conf: float = 0.0
  54. self.miss_streak: int = 0
  55. self._warmed = False
  56. def reset(self) -> None:
  57. self.smoother.reset()
  58. self.last_raw = None
  59. self.last_xyxy = None
  60. self.last_conf = 0.0
  61. self.miss_streak = 0
  62. def warmup(self, frame_bgr: Optional[np.ndarray] = None) -> None:
  63. if self._warmed:
  64. return
  65. import numpy as np
  66. dummy = frame_bgr if frame_bgr is not None else np.zeros((640, 640, 3), dtype=np.uint8)
  67. self.detect_raw(dummy)
  68. self._warmed = True
  69. def detect_raw(self, frame_bgr: np.ndarray) -> DetectResult:
  70. # Real game has no green cursor — strip it so we track the shape only.
  71. infer = erase_green_reticle(frame_bgr) if self.erase_green else frame_bgr
  72. results = self.model.predict(
  73. source=infer,
  74. conf=self.conf,
  75. iou=self.iou,
  76. device=self.device,
  77. imgsz=self.imgsz,
  78. verbose=False,
  79. )
  80. if not results:
  81. return DetectResult(None, 0.0, None)
  82. r0 = results[0]
  83. if r0.boxes is None or len(r0.boxes) == 0:
  84. return DetectResult(None, 0.0, None)
  85. boxes = r0.boxes
  86. confs = boxes.conf.cpu().numpy()
  87. xyxy = boxes.xyxy.cpu().numpy()
  88. i = int(np.argmax(confs))
  89. x1, y1, x2, y2 = map(float, xyxy[i])
  90. cx = (x1 + x2) * 0.5
  91. cy = (y1 + y2) * 0.5
  92. return DetectResult((cx, cy), float(confs[i]), (x1, y1, x2, y2))
  93. def track(self, frame_bgr: np.ndarray) -> DetectResult:
  94. raw = self.detect_raw(frame_bgr)
  95. if raw.center is None:
  96. self.miss_streak += 1
  97. self.last_conf = max(0.0, self.last_conf * 0.85)
  98. if self.miss_streak > 15:
  99. self.last_xyxy = None
  100. return DetectResult(None, 0.0, None)
  101. return DetectResult(self.smoother.value, self.last_conf, self.last_xyxy)
  102. self.miss_streak = 0
  103. self.last_raw = raw.center
  104. self.last_xyxy = raw.xyxy
  105. self.last_conf = raw.conf
  106. smooth = self.smoother.update(raw.center)
  107. return DetectResult(smooth, raw.conf, raw.xyxy)