| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- """Extract green reticle center as ground-truth trajectory."""
- from __future__ import annotations
- from typing import Optional, Tuple
- import cv2
- import numpy as np
- # Bright green reticle in the reference videos.
- LOWER_HSV = np.array([40, 80, 80], dtype=np.uint8)
- UPPER_HSV = np.array([95, 255, 255], dtype=np.uint8)
- MIN_AREA = 80
- MAX_AREA = 25000
- def detect_green_reticle(frame_bgr: np.ndarray) -> Optional[Tuple[float, float]]:
- """Return (x, y) center of the green reticle, or None if not found."""
- hsv = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2HSV)
- mask = cv2.inRange(hsv, LOWER_HSV, UPPER_HSV)
- kernel = np.ones((3, 3), np.uint8)
- mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
- mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- if not contours:
- return None
- best = None
- best_score = -1.0
- for cnt in contours:
- area = cv2.contourArea(cnt)
- if area < MIN_AREA or area > MAX_AREA:
- continue
- peri = cv2.arcLength(cnt, True)
- if peri <= 0:
- continue
- circularity = 4.0 * np.pi * area / (peri * peri)
- # Prefer compact circular blobs (reticle ring/fill).
- score = area * (0.5 + circularity)
- if score > best_score:
- best_score = score
- best = cnt
- if best is None:
- return None
- m = cv2.moments(best)
- if m["m00"] == 0:
- return None
- cx = float(m["m10"] / m["m00"])
- cy = float(m["m01"] / m["m00"])
- return cx, cy
- def extract_trajectory(
- video_path: str,
- hold_last: bool = True,
- ) -> dict:
- """Extract per-frame green reticle centers from a video."""
- cap = cv2.VideoCapture(video_path)
- if not cap.isOpened():
- raise RuntimeError(f"Cannot open video: {video_path}")
- fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
- frames = []
- last: Optional[Tuple[float, float]] = None
- idx = 0
- while True:
- ok, frame = cap.read()
- if not ok:
- break
- pt = detect_green_reticle(frame)
- if pt is None and hold_last and last is not None:
- pt = last
- held = True
- else:
- held = False
- if pt is not None:
- last = pt
- frames.append(
- {
- "frame": idx,
- "x": None if pt is None else round(pt[0], 2),
- "y": None if pt is None else round(pt[1], 2),
- "detected": pt is not None and not held,
- "held": held,
- }
- )
- idx += 1
- cap.release()
- return {
- "video": video_path,
- "fps": fps,
- "width": width,
- "height": height,
- "frame_count": total if total > 0 else len(frames),
- "frames": frames,
- }
|