| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249 |
- """CLI: video evaluation or window listen preview (no real mouse control)."""
- from __future__ import annotations
- import argparse
- import json
- import sys
- import time
- from pathlib import Path
- from typing import Any, Dict, List, Optional, Tuple
- import cv2
- ROOT = Path(__file__).resolve().parent
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tracker.capture import grab_window_bgr, iter_video_frames
- from tracker.detect import TargetDetector
- from tracker.eval import collect_frame_errors, save_summary, summarize_errors
- from tracker.green_gt import detect_green_reticle
- from tracker.decoy_viz import DecoyVisualizer
- from tracker.hybrid_tracker import HybridTracker
- from tracker.mot_tracker import MotYoloTracker
- from tracker.overlay import draw_pair
- from tracker.paths import EVAL_DIR, GT_DIR, MODELS_DIR, VIDEO_MAP
- from tracker.result_utils import get_decoys
- from tracker.window_picker import pick_window_interactive
- LEGEND = "ORANGE=REAL CYAN=id decoy RED=pred GREEN=GT"
- def load_gt_points(key: str) -> List[Optional[Tuple[float, float]]]:
- path = GT_DIR / f"{key}.json"
- data = json.loads(path.read_text(encoding="utf-8"))
- pts: List[Optional[Tuple[float, float]]] = []
- for f in data["frames"]:
- if f["x"] is None or f["y"] is None:
- pts.append(None)
- else:
- pts.append((float(f["x"]), float(f["y"])))
- return pts
- def build_tracker(backend: str, weights: str, conf: float) -> Any:
- if backend == "yolo":
- return TargetDetector(weights=weights, conf=conf, erase_green=True)
- if backend == "bytetrack":
- return MotYoloTracker(weights=weights, method="bytetrack", conf=conf)
- if backend == "deepsort":
- return MotYoloTracker(weights=weights, method="deepsort", conf=conf)
- return HybridTracker(weights=weights, conf=conf)
- def _eval_one_video(
- tracker: Any,
- key: str,
- video_path: Path,
- gt_points: Optional[List[Optional[Tuple[float, float]]]],
- show: bool,
- backend: str,
- ) -> dict:
- tracker.reset()
- cap_meta = cv2.VideoCapture(str(video_path))
- fps = float(cap_meta.get(cv2.CAP_PROP_FPS) or 25.0)
- w = int(cap_meta.get(cv2.CAP_PROP_FRAME_WIDTH))
- h = int(cap_meta.get(cv2.CAP_PROP_FRAME_HEIGHT))
- cap_meta.release()
- out_path = EVAL_DIR / f"{key}_{backend}_overlay.mp4"
- writer = cv2.VideoWriter(
- str(out_path),
- cv2.VideoWriter_fourcc(*"mp4v"),
- fps,
- (w, h),
- )
- green_list: List[Optional[Tuple[float, float]]] = []
- red_list: List[Optional[Tuple[float, float]]] = []
- decoy_viz = DecoyVisualizer()
- print(f"[video] evaluating {key} backend={backend} <- {video_path}")
- for idx, frame in iter_video_frames(str(video_path)):
- if gt_points is not None and idx < len(gt_points):
- green = gt_points[idx]
- else:
- green = detect_green_reticle(frame)
- det = tracker.track(frame)
- decoys = get_decoys(tracker, frame, det.xyxy, decoy_viz)
- green_list.append(green)
- red_list.append(det.center)
- overlay = draw_pair(
- frame,
- green,
- det.center,
- bbox_xyxy=det.xyxy,
- conf=det.conf,
- draw_error_line=True,
- draw_gt=green is not None,
- decoys=decoys,
- )
- cv2.putText(
- overlay,
- f"{LEGEND} [{backend}]",
- (20, 40),
- cv2.FONT_HERSHEY_SIMPLEX,
- 0.7,
- (255, 255, 255),
- 2,
- )
- writer.write(overlay)
- if show:
- cv2.imshow("eval", overlay)
- if cv2.waitKey(1) & 0xFF == ord("q"):
- break
- writer.release()
- errs = collect_frame_errors(green_list, red_list)
- metrics = summarize_errors(errs)
- print(
- f" {key}: mean={metrics['mean']:.2f}px median={metrics['median']:.2f}px "
- f"p95={metrics['p95']:.2f}px hit@15={metrics['hit_rates']['15.0']:.2%} "
- f"hit@30={metrics['hit_rates']['30.0']:.2%}"
- if metrics["count"]
- else f" {key}: no green GT paired (still wrote overlay)"
- )
- return {
- "overlay": str(out_path),
- "metrics": metrics,
- "source": str(video_path),
- "backend": backend,
- }
- def run_video(
- backend: str,
- weights: str,
- conf: float,
- show: bool,
- video: Optional[str] = None,
- ) -> dict:
- EVAL_DIR.mkdir(parents=True, exist_ok=True)
- tracker = build_tracker(backend, weights, conf)
- summary: Dict[str, dict] = {}
- if video:
- video_path = Path(video).expanduser().resolve()
- if not video_path.exists():
- raise FileNotFoundError(f"Video not found: {video_path}")
- key = video_path.stem
- gt_points = load_gt_points(key) if (GT_DIR / f"{key}.json").exists() else None
- summary[key] = _eval_one_video(tracker, key, video_path, gt_points, show, backend)
- else:
- for key, video_path in VIDEO_MAP.items():
- if not video_path.exists():
- print(f"[skip] missing {video_path}")
- continue
- tracker = build_tracker(backend, weights, conf)
- summary[key] = _eval_one_video(
- tracker, key, video_path, load_gt_points(key), show, backend
- )
- if show:
- cv2.destroyAllWindows()
- out_summary = EVAL_DIR / f"summary_{backend}.json"
- save_summary(out_summary, summary)
- print(f"[video] summary -> {out_summary}")
- return summary
- def run_window(backend: str, weights: str, conf: float, title: Optional[str]) -> None:
- win = pick_window_interactive(title_substr=title)
- print(f"[window] listening hwnd={win.hwnd} title={win.title!r} backend={backend}")
- tracker = build_tracker(backend, weights, conf)
- decoy_viz = DecoyVisualizer()
- while True:
- frame = grab_window_bgr(win.hwnd)
- if frame is None:
- print("[window] capture failed; is the window closed?")
- time.sleep(0.5)
- continue
- green = detect_green_reticle(frame)
- det = tracker.track(frame)
- decoys = get_decoys(tracker, frame, det.xyxy, decoy_viz)
- overlay = draw_pair(
- frame,
- green,
- det.center,
- bbox_xyxy=det.xyxy,
- conf=det.conf,
- draw_error_line=bool(green and det.center),
- draw_gt=green is not None,
- decoys=decoys,
- )
- cv2.putText(
- overlay,
- f"{LEGEND} [{backend}] q=quit",
- (16, 32),
- cv2.FONT_HERSHEY_SIMPLEX,
- 0.6,
- (255, 255, 255),
- 2,
- )
- cv2.imshow("window-track", overlay)
- key = cv2.waitKey(1) & 0xFF
- if key == ord("q"):
- break
- cv2.destroyAllWindows()
- def parse_args() -> argparse.Namespace:
- p = argparse.ArgumentParser(description="Shape-agnostic / YOLO tracking eval")
- p.add_argument("--mode", choices=("video", "window"), default="video")
- p.add_argument(
- "--backend",
- choices=("hybrid", "yolo", "bytetrack", "deepsort"),
- default="hybrid",
- help="hybrid|yolo|bytetrack|deepsort",
- )
- p.add_argument("--video", default=None, help="Path to a new video (overrides built-in trio)")
- p.add_argument("--weights", default=str(MODELS_DIR / "best.pt"))
- p.add_argument("--conf", type=float, default=0.25)
- p.add_argument("--title", default=None, help="Optional window title substr for --mode window")
- p.add_argument("--show", action="store_true", help="Show OpenCV preview in video mode")
- return p.parse_args()
- def main() -> None:
- args = parse_args()
- weights = Path(args.weights)
- if args.backend in ("yolo", "hybrid", "bytetrack", "deepsort") and not weights.exists():
- raise FileNotFoundError(f"Weights not found: {weights}. Run scripts/train_yolo.py first.")
- if args.mode == "video":
- run_video(
- backend=args.backend,
- weights=str(weights),
- conf=args.conf,
- show=args.show,
- video=args.video,
- )
- else:
- run_window(args.backend, str(weights), conf=args.conf, title=args.title)
- if __name__ == "__main__":
- main()
|