green_gt.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Extract green reticle center as ground-truth trajectory."""
  2. from __future__ import annotations
  3. from typing import Optional, Tuple
  4. import cv2
  5. import numpy as np
  6. # Bright green reticle in the reference videos.
  7. LOWER_HSV = np.array([40, 80, 80], dtype=np.uint8)
  8. UPPER_HSV = np.array([95, 255, 255], dtype=np.uint8)
  9. MIN_AREA = 80
  10. MAX_AREA = 25000
  11. def detect_green_reticle(frame_bgr: np.ndarray) -> Optional[Tuple[float, float]]:
  12. """Return (x, y) center of the green reticle, or None if not found."""
  13. hsv = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2HSV)
  14. mask = cv2.inRange(hsv, LOWER_HSV, UPPER_HSV)
  15. kernel = np.ones((3, 3), np.uint8)
  16. mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
  17. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
  18. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  19. if not contours:
  20. return None
  21. best = None
  22. best_score = -1.0
  23. for cnt in contours:
  24. area = cv2.contourArea(cnt)
  25. if area < MIN_AREA or area > MAX_AREA:
  26. continue
  27. peri = cv2.arcLength(cnt, True)
  28. if peri <= 0:
  29. continue
  30. circularity = 4.0 * np.pi * area / (peri * peri)
  31. # Prefer compact circular blobs (reticle ring/fill).
  32. score = area * (0.5 + circularity)
  33. if score > best_score:
  34. best_score = score
  35. best = cnt
  36. if best is None:
  37. return None
  38. m = cv2.moments(best)
  39. if m["m00"] == 0:
  40. return None
  41. cx = float(m["m10"] / m["m00"])
  42. cy = float(m["m01"] / m["m00"])
  43. return cx, cy
  44. def extract_trajectory(
  45. video_path: str,
  46. hold_last: bool = True,
  47. ) -> dict:
  48. """Extract per-frame green reticle centers from a video."""
  49. cap = cv2.VideoCapture(video_path)
  50. if not cap.isOpened():
  51. raise RuntimeError(f"Cannot open video: {video_path}")
  52. fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0)
  53. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  54. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  55. total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
  56. frames = []
  57. last: Optional[Tuple[float, float]] = None
  58. idx = 0
  59. while True:
  60. ok, frame = cap.read()
  61. if not ok:
  62. break
  63. pt = detect_green_reticle(frame)
  64. if pt is None and hold_last and last is not None:
  65. pt = last
  66. held = True
  67. else:
  68. held = False
  69. if pt is not None:
  70. last = pt
  71. frames.append(
  72. {
  73. "frame": idx,
  74. "x": None if pt is None else round(pt[0], 2),
  75. "y": None if pt is None else round(pt[1], 2),
  76. "detected": pt is not None and not held,
  77. "held": held,
  78. }
  79. )
  80. idx += 1
  81. cap.release()
  82. return {
  83. "video": video_path,
  84. "fps": fps,
  85. "width": width,
  86. "height": height,
  87. "frame_count": total if total > 0 else len(frames),
  88. "frames": frames,
  89. }