"""Build weakly-supervised YOLO dataset from videos + green GT.""" from __future__ import annotations import json import random import shutil import sys from pathlib import Path from typing import List, Optional, Tuple import cv2 import numpy as np import yaml ROOT = Path(__file__).resolve().parent.parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from tracker.paths import DATASET_DIR, GT_DIR, VIDEO_MAP from tracker.preprocess import erase_green_reticle FRAME_STRIDE = 6 VAL_RATIO = 0.2 SEED = 42 EARLY_WHITE_RATIO = 0.45 # first portion of video: try white blob auto-label MIN_WHITE_AREA = 800 MAX_WHITE_AREA = 120000 GT_NEAR_PX = 80 FALLBACK_BOX = 120 # side length when using GT-centered weak box def load_gt(key: str) -> dict: path = GT_DIR / f"{key}.json" if not path.exists(): raise FileNotFoundError(f"Missing GT file: {path}. Run scripts/extract_gt.py first.") return json.loads(path.read_text(encoding="utf-8")) def white_blob_bbox( frame: np.ndarray, gt_xy: Tuple[float, float], ) -> Optional[Tuple[float, float, float, float]]: """Return xyxy bbox of bright white target near GT, if found.""" gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # High brightness + low saturation for white fill. hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask_v = cv2.inRange(gray, 200, 255) mask_s = cv2.inRange(hsv[:, :, 1], 0, 60) mask = cv2.bitwise_and(mask_v, mask_s) # Remove green reticle pixels. green = cv2.inRange(hsv, np.array([40, 80, 80]), np.array([95, 255, 255])) mask = cv2.bitwise_and(mask, cv2.bitwise_not(green)) kernel = np.ones((5, 5), 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) best = None best_dist = 1e9 for cnt in contours: area = cv2.contourArea(cnt) if area < MIN_WHITE_AREA or area > MAX_WHITE_AREA: continue x, y, w, h = cv2.boundingRect(cnt) cx = x + w * 0.5 cy = y + h * 0.5 dist = float(np.hypot(cx - gt_xy[0], cy - gt_xy[1])) if dist < best_dist and dist <= GT_NEAR_PX: best_dist = dist best = (float(x), float(y), float(x + w), float(y + h)) return best def gt_centered_box( gt_xy: Tuple[float, float], size: float, width: int, height: int, ) -> Tuple[float, float, float, float]: half = size * 0.5 x1 = max(0.0, gt_xy[0] - half) y1 = max(0.0, gt_xy[1] - half) x2 = min(float(width - 1), gt_xy[0] + half) y2 = min(float(height - 1), gt_xy[1] + half) return x1, y1, x2, y2 def to_yolo_line(xyxy: Tuple[float, float, float, float], w: int, h: int) -> str: x1, y1, x2, y2 = xyxy cx = ((x1 + x2) * 0.5) / w cy = ((y1 + y2) * 0.5) / h bw = (x2 - x1) / w bh = (y2 - y1) / h cx = min(max(cx, 0.0), 1.0) cy = min(max(cy, 0.0), 1.0) bw = min(max(bw, 1e-4), 1.0) bh = min(max(bh, 1e-4), 1.0) return f"0 {cx:.6f} {cy:.6f} {bw:.6f} {bh:.6f}" def reset_dataset_dirs() -> None: if DATASET_DIR.exists(): shutil.rmtree(DATASET_DIR) for split in ("train", "val"): (DATASET_DIR / "images" / split).mkdir(parents=True, exist_ok=True) (DATASET_DIR / "labels" / split).mkdir(parents=True, exist_ok=True) def collect_samples() -> List[dict]: samples: List[dict] = [] for key, video_path in VIDEO_MAP.items(): gt = load_gt(key) frames_meta = gt["frames"] width, height = gt["width"], gt["height"] n = len(frames_meta) early_end = int(n * EARLY_WHITE_RATIO) cap = cv2.VideoCapture(str(video_path)) if not cap.isOpened(): raise RuntimeError(f"Cannot open {video_path}") # Estimate box size from early white detections. sizes: List[float] = [] idx = 0 while True: ok, frame = cap.read() if not ok: break if idx % FRAME_STRIDE != 0: idx += 1 continue meta = frames_meta[idx] if idx < n else None if meta is None or meta["x"] is None or meta["y"] is None: idx += 1 continue # Skip countdown-ish frames: green often not on target yet at very start. if idx < int(gt["fps"] * 1.2): idx += 1 continue gt_xy = (float(meta["x"]), float(meta["y"])) box = None source = "gt_box" if idx <= early_end: box = white_blob_bbox(frame, gt_xy) if box is not None: source = "white" sizes.append(max(box[2] - box[0], box[3] - box[1])) box_size = float(np.median(sizes)) if sizes else float(FALLBACK_BOX) if box is None: box = gt_centered_box(gt_xy, box_size, width, height) # Strip green reticle from training images — model must learn the target shape. samples.append( { "key": key, "frame_idx": idx, "image": erase_green_reticle(frame), "xyxy": box, "source": source, "width": width, "height": height, } ) idx += 1 cap.release() print(f"[dataset] {key}: collected {sum(1 for s in samples if s['key']==key)} samples") return samples def main() -> None: random.seed(SEED) reset_dataset_dirs() samples = collect_samples() if not samples: raise RuntimeError("No samples collected.") random.shuffle(samples) n_val = max(1, int(len(samples) * VAL_RATIO)) val_set = set(id(s) for s in samples[:n_val]) counts = {"train": 0, "val": 0} for s in samples: split = "val" if id(s) in val_set else "train" name = f"{s['key']}_{s['frame_idx']:05d}" img_path = DATASET_DIR / "images" / split / f"{name}.jpg" lbl_path = DATASET_DIR / "labels" / split / f"{name}.txt" cv2.imwrite(str(img_path), s["image"], [int(cv2.IMWRITE_JPEG_QUALITY), 92]) lbl_path.write_text(to_yolo_line(s["xyxy"], s["width"], s["height"]) + "\n", encoding="utf-8") counts[split] += 1 yaml_path = DATASET_DIR / "data.yaml" data = { "path": str(DATASET_DIR.resolve()).replace("\\", "/"), "train": "images/train", "val": "images/val", "names": {0: "target"}, } yaml_path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") print(f"[dataset] train={counts['train']} val={counts['val']} yaml={yaml_path}") if __name__ == "__main__": main()