main.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """CLI: video evaluation or window listen preview (no real mouse control)."""
  2. from __future__ import annotations
  3. import argparse
  4. import json
  5. import sys
  6. import time
  7. from pathlib import Path
  8. from typing import Any, Dict, List, Optional, Tuple
  9. import cv2
  10. ROOT = Path(__file__).resolve().parent
  11. if str(ROOT) not in sys.path:
  12. sys.path.insert(0, str(ROOT))
  13. from tracker.capture import grab_window_bgr, iter_video_frames
  14. from tracker.detect import TargetDetector
  15. from tracker.eval import collect_frame_errors, save_summary, summarize_errors
  16. from tracker.green_gt import detect_green_reticle
  17. from tracker.decoy_viz import DecoyVisualizer
  18. from tracker.hybrid_tracker import HybridTracker
  19. from tracker.mot_tracker import MotYoloTracker
  20. from tracker.overlay import draw_pair
  21. from tracker.paths import EVAL_DIR, GT_DIR, MODELS_DIR, VIDEO_MAP
  22. from tracker.result_utils import get_decoys
  23. from tracker.window_picker import pick_window_interactive
  24. LEGEND = "ORANGE=REAL CYAN=id decoy RED=pred GREEN=GT"
  25. def load_gt_points(key: str) -> List[Optional[Tuple[float, float]]]:
  26. path = GT_DIR / f"{key}.json"
  27. data = json.loads(path.read_text(encoding="utf-8"))
  28. pts: List[Optional[Tuple[float, float]]] = []
  29. for f in data["frames"]:
  30. if f["x"] is None or f["y"] is None:
  31. pts.append(None)
  32. else:
  33. pts.append((float(f["x"]), float(f["y"])))
  34. return pts
  35. def build_tracker(backend: str, weights: str, conf: float) -> Any:
  36. if backend == "yolo":
  37. return TargetDetector(weights=weights, conf=conf, erase_green=True)
  38. if backend == "bytetrack":
  39. return MotYoloTracker(weights=weights, method="bytetrack", conf=conf)
  40. if backend == "deepsort":
  41. return MotYoloTracker(weights=weights, method="deepsort", conf=conf)
  42. return HybridTracker(weights=weights, conf=conf)
  43. def _eval_one_video(
  44. tracker: Any,
  45. key: str,
  46. video_path: Path,
  47. gt_points: Optional[List[Optional[Tuple[float, float]]]],
  48. show: bool,
  49. backend: str,
  50. ) -> dict:
  51. tracker.reset()
  52. cap_meta = cv2.VideoCapture(str(video_path))
  53. fps = float(cap_meta.get(cv2.CAP_PROP_FPS) or 25.0)
  54. w = int(cap_meta.get(cv2.CAP_PROP_FRAME_WIDTH))
  55. h = int(cap_meta.get(cv2.CAP_PROP_FRAME_HEIGHT))
  56. cap_meta.release()
  57. out_path = EVAL_DIR / f"{key}_{backend}_overlay.mp4"
  58. writer = cv2.VideoWriter(
  59. str(out_path),
  60. cv2.VideoWriter_fourcc(*"mp4v"),
  61. fps,
  62. (w, h),
  63. )
  64. green_list: List[Optional[Tuple[float, float]]] = []
  65. red_list: List[Optional[Tuple[float, float]]] = []
  66. decoy_viz = DecoyVisualizer()
  67. print(f"[video] evaluating {key} backend={backend} <- {video_path}")
  68. for idx, frame in iter_video_frames(str(video_path)):
  69. if gt_points is not None and idx < len(gt_points):
  70. green = gt_points[idx]
  71. else:
  72. green = detect_green_reticle(frame)
  73. det = tracker.track(frame)
  74. decoys = get_decoys(tracker, frame, det.xyxy, decoy_viz)
  75. green_list.append(green)
  76. red_list.append(det.center)
  77. overlay = draw_pair(
  78. frame,
  79. green,
  80. det.center,
  81. bbox_xyxy=det.xyxy,
  82. conf=det.conf,
  83. draw_error_line=True,
  84. draw_gt=green is not None,
  85. decoys=decoys,
  86. )
  87. cv2.putText(
  88. overlay,
  89. f"{LEGEND} [{backend}]",
  90. (20, 40),
  91. cv2.FONT_HERSHEY_SIMPLEX,
  92. 0.7,
  93. (255, 255, 255),
  94. 2,
  95. )
  96. writer.write(overlay)
  97. if show:
  98. cv2.imshow("eval", overlay)
  99. if cv2.waitKey(1) & 0xFF == ord("q"):
  100. break
  101. writer.release()
  102. errs = collect_frame_errors(green_list, red_list)
  103. metrics = summarize_errors(errs)
  104. print(
  105. f" {key}: mean={metrics['mean']:.2f}px median={metrics['median']:.2f}px "
  106. f"p95={metrics['p95']:.2f}px hit@15={metrics['hit_rates']['15.0']:.2%} "
  107. f"hit@30={metrics['hit_rates']['30.0']:.2%}"
  108. if metrics["count"]
  109. else f" {key}: no green GT paired (still wrote overlay)"
  110. )
  111. return {
  112. "overlay": str(out_path),
  113. "metrics": metrics,
  114. "source": str(video_path),
  115. "backend": backend,
  116. }
  117. def run_video(
  118. backend: str,
  119. weights: str,
  120. conf: float,
  121. show: bool,
  122. video: Optional[str] = None,
  123. ) -> dict:
  124. EVAL_DIR.mkdir(parents=True, exist_ok=True)
  125. tracker = build_tracker(backend, weights, conf)
  126. summary: Dict[str, dict] = {}
  127. if video:
  128. video_path = Path(video).expanduser().resolve()
  129. if not video_path.exists():
  130. raise FileNotFoundError(f"Video not found: {video_path}")
  131. key = video_path.stem
  132. gt_points = load_gt_points(key) if (GT_DIR / f"{key}.json").exists() else None
  133. summary[key] = _eval_one_video(tracker, key, video_path, gt_points, show, backend)
  134. else:
  135. for key, video_path in VIDEO_MAP.items():
  136. if not video_path.exists():
  137. print(f"[skip] missing {video_path}")
  138. continue
  139. tracker = build_tracker(backend, weights, conf)
  140. summary[key] = _eval_one_video(
  141. tracker, key, video_path, load_gt_points(key), show, backend
  142. )
  143. if show:
  144. cv2.destroyAllWindows()
  145. out_summary = EVAL_DIR / f"summary_{backend}.json"
  146. save_summary(out_summary, summary)
  147. print(f"[video] summary -> {out_summary}")
  148. return summary
  149. def run_window(backend: str, weights: str, conf: float, title: Optional[str]) -> None:
  150. win = pick_window_interactive(title_substr=title)
  151. print(f"[window] listening hwnd={win.hwnd} title={win.title!r} backend={backend}")
  152. tracker = build_tracker(backend, weights, conf)
  153. decoy_viz = DecoyVisualizer()
  154. while True:
  155. frame = grab_window_bgr(win.hwnd)
  156. if frame is None:
  157. print("[window] capture failed; is the window closed?")
  158. time.sleep(0.5)
  159. continue
  160. green = detect_green_reticle(frame)
  161. det = tracker.track(frame)
  162. decoys = get_decoys(tracker, frame, det.xyxy, decoy_viz)
  163. overlay = draw_pair(
  164. frame,
  165. green,
  166. det.center,
  167. bbox_xyxy=det.xyxy,
  168. conf=det.conf,
  169. draw_error_line=bool(green and det.center),
  170. draw_gt=green is not None,
  171. decoys=decoys,
  172. )
  173. cv2.putText(
  174. overlay,
  175. f"{LEGEND} [{backend}] q=quit",
  176. (16, 32),
  177. cv2.FONT_HERSHEY_SIMPLEX,
  178. 0.6,
  179. (255, 255, 255),
  180. 2,
  181. )
  182. cv2.imshow("window-track", overlay)
  183. key = cv2.waitKey(1) & 0xFF
  184. if key == ord("q"):
  185. break
  186. cv2.destroyAllWindows()
  187. def parse_args() -> argparse.Namespace:
  188. p = argparse.ArgumentParser(description="Shape-agnostic / YOLO tracking eval")
  189. p.add_argument("--mode", choices=("video", "window"), default="video")
  190. p.add_argument(
  191. "--backend",
  192. choices=("hybrid", "yolo", "bytetrack", "deepsort"),
  193. default="hybrid",
  194. help="hybrid|yolo|bytetrack|deepsort",
  195. )
  196. p.add_argument("--video", default=None, help="Path to a new video (overrides built-in trio)")
  197. p.add_argument("--weights", default=str(MODELS_DIR / "best.pt"))
  198. p.add_argument("--conf", type=float, default=0.25)
  199. p.add_argument("--title", default=None, help="Optional window title substr for --mode window")
  200. p.add_argument("--show", action="store_true", help="Show OpenCV preview in video mode")
  201. return p.parse_args()
  202. def main() -> None:
  203. args = parse_args()
  204. weights = Path(args.weights)
  205. if args.backend in ("yolo", "hybrid", "bytetrack", "deepsort") and not weights.exists():
  206. raise FileNotFoundError(f"Weights not found: {weights}. Run scripts/train_yolo.py first.")
  207. if args.mode == "video":
  208. run_video(
  209. backend=args.backend,
  210. weights=str(weights),
  211. conf=args.conf,
  212. show=args.show,
  213. video=args.video,
  214. )
  215. else:
  216. run_window(args.backend, str(weights), conf=args.conf, title=args.title)
  217. if __name__ == "__main__":
  218. main()