build_dataset.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. """Build weakly-supervised YOLO dataset from videos + green GT."""
  2. from __future__ import annotations
  3. import json
  4. import random
  5. import shutil
  6. import sys
  7. from pathlib import Path
  8. from typing import List, Optional, Tuple
  9. import cv2
  10. import numpy as np
  11. import yaml
  12. ROOT = Path(__file__).resolve().parent.parent
  13. if str(ROOT) not in sys.path:
  14. sys.path.insert(0, str(ROOT))
  15. from tracker.paths import DATASET_DIR, GT_DIR, VIDEO_MAP
  16. from tracker.preprocess import erase_green_reticle
  17. FRAME_STRIDE = 6
  18. VAL_RATIO = 0.2
  19. SEED = 42
  20. EARLY_WHITE_RATIO = 0.45 # first portion of video: try white blob auto-label
  21. MIN_WHITE_AREA = 800
  22. MAX_WHITE_AREA = 120000
  23. GT_NEAR_PX = 80
  24. FALLBACK_BOX = 120 # side length when using GT-centered weak box
  25. def load_gt(key: str) -> dict:
  26. path = GT_DIR / f"{key}.json"
  27. if not path.exists():
  28. raise FileNotFoundError(f"Missing GT file: {path}. Run scripts/extract_gt.py first.")
  29. return json.loads(path.read_text(encoding="utf-8"))
  30. def white_blob_bbox(
  31. frame: np.ndarray,
  32. gt_xy: Tuple[float, float],
  33. ) -> Optional[Tuple[float, float, float, float]]:
  34. """Return xyxy bbox of bright white target near GT, if found."""
  35. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  36. # High brightness + low saturation for white fill.
  37. hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  38. mask_v = cv2.inRange(gray, 200, 255)
  39. mask_s = cv2.inRange(hsv[:, :, 1], 0, 60)
  40. mask = cv2.bitwise_and(mask_v, mask_s)
  41. # Remove green reticle pixels.
  42. green = cv2.inRange(hsv, np.array([40, 80, 80]), np.array([95, 255, 255]))
  43. mask = cv2.bitwise_and(mask, cv2.bitwise_not(green))
  44. kernel = np.ones((5, 5), np.uint8)
  45. mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
  46. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
  47. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  48. best = None
  49. best_dist = 1e9
  50. for cnt in contours:
  51. area = cv2.contourArea(cnt)
  52. if area < MIN_WHITE_AREA or area > MAX_WHITE_AREA:
  53. continue
  54. x, y, w, h = cv2.boundingRect(cnt)
  55. cx = x + w * 0.5
  56. cy = y + h * 0.5
  57. dist = float(np.hypot(cx - gt_xy[0], cy - gt_xy[1]))
  58. if dist < best_dist and dist <= GT_NEAR_PX:
  59. best_dist = dist
  60. best = (float(x), float(y), float(x + w), float(y + h))
  61. return best
  62. def gt_centered_box(
  63. gt_xy: Tuple[float, float],
  64. size: float,
  65. width: int,
  66. height: int,
  67. ) -> Tuple[float, float, float, float]:
  68. half = size * 0.5
  69. x1 = max(0.0, gt_xy[0] - half)
  70. y1 = max(0.0, gt_xy[1] - half)
  71. x2 = min(float(width - 1), gt_xy[0] + half)
  72. y2 = min(float(height - 1), gt_xy[1] + half)
  73. return x1, y1, x2, y2
  74. def to_yolo_line(xyxy: Tuple[float, float, float, float], w: int, h: int) -> str:
  75. x1, y1, x2, y2 = xyxy
  76. cx = ((x1 + x2) * 0.5) / w
  77. cy = ((y1 + y2) * 0.5) / h
  78. bw = (x2 - x1) / w
  79. bh = (y2 - y1) / h
  80. cx = min(max(cx, 0.0), 1.0)
  81. cy = min(max(cy, 0.0), 1.0)
  82. bw = min(max(bw, 1e-4), 1.0)
  83. bh = min(max(bh, 1e-4), 1.0)
  84. return f"0 {cx:.6f} {cy:.6f} {bw:.6f} {bh:.6f}"
  85. def reset_dataset_dirs() -> None:
  86. if DATASET_DIR.exists():
  87. shutil.rmtree(DATASET_DIR)
  88. for split in ("train", "val"):
  89. (DATASET_DIR / "images" / split).mkdir(parents=True, exist_ok=True)
  90. (DATASET_DIR / "labels" / split).mkdir(parents=True, exist_ok=True)
  91. def collect_samples() -> List[dict]:
  92. samples: List[dict] = []
  93. for key, video_path in VIDEO_MAP.items():
  94. gt = load_gt(key)
  95. frames_meta = gt["frames"]
  96. width, height = gt["width"], gt["height"]
  97. n = len(frames_meta)
  98. early_end = int(n * EARLY_WHITE_RATIO)
  99. cap = cv2.VideoCapture(str(video_path))
  100. if not cap.isOpened():
  101. raise RuntimeError(f"Cannot open {video_path}")
  102. # Estimate box size from early white detections.
  103. sizes: List[float] = []
  104. idx = 0
  105. while True:
  106. ok, frame = cap.read()
  107. if not ok:
  108. break
  109. if idx % FRAME_STRIDE != 0:
  110. idx += 1
  111. continue
  112. meta = frames_meta[idx] if idx < n else None
  113. if meta is None or meta["x"] is None or meta["y"] is None:
  114. idx += 1
  115. continue
  116. # Skip countdown-ish frames: green often not on target yet at very start.
  117. if idx < int(gt["fps"] * 1.2):
  118. idx += 1
  119. continue
  120. gt_xy = (float(meta["x"]), float(meta["y"]))
  121. box = None
  122. source = "gt_box"
  123. if idx <= early_end:
  124. box = white_blob_bbox(frame, gt_xy)
  125. if box is not None:
  126. source = "white"
  127. sizes.append(max(box[2] - box[0], box[3] - box[1]))
  128. box_size = float(np.median(sizes)) if sizes else float(FALLBACK_BOX)
  129. if box is None:
  130. box = gt_centered_box(gt_xy, box_size, width, height)
  131. # Strip green reticle from training images — model must learn the target shape.
  132. samples.append(
  133. {
  134. "key": key,
  135. "frame_idx": idx,
  136. "image": erase_green_reticle(frame),
  137. "xyxy": box,
  138. "source": source,
  139. "width": width,
  140. "height": height,
  141. }
  142. )
  143. idx += 1
  144. cap.release()
  145. print(f"[dataset] {key}: collected {sum(1 for s in samples if s['key']==key)} samples")
  146. return samples
  147. def main() -> None:
  148. random.seed(SEED)
  149. reset_dataset_dirs()
  150. samples = collect_samples()
  151. if not samples:
  152. raise RuntimeError("No samples collected.")
  153. random.shuffle(samples)
  154. n_val = max(1, int(len(samples) * VAL_RATIO))
  155. val_set = set(id(s) for s in samples[:n_val])
  156. counts = {"train": 0, "val": 0}
  157. for s in samples:
  158. split = "val" if id(s) in val_set else "train"
  159. name = f"{s['key']}_{s['frame_idx']:05d}"
  160. img_path = DATASET_DIR / "images" / split / f"{name}.jpg"
  161. lbl_path = DATASET_DIR / "labels" / split / f"{name}.txt"
  162. cv2.imwrite(str(img_path), s["image"], [int(cv2.IMWRITE_JPEG_QUALITY), 92])
  163. lbl_path.write_text(to_yolo_line(s["xyxy"], s["width"], s["height"]) + "\n", encoding="utf-8")
  164. counts[split] += 1
  165. yaml_path = DATASET_DIR / "data.yaml"
  166. data = {
  167. "path": str(DATASET_DIR.resolve()).replace("\\", "/"),
  168. "train": "images/train",
  169. "val": "images/val",
  170. "names": {0: "target"},
  171. }
  172. yaml_path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8")
  173. print(f"[dataset] train={counts['train']} val={counts['val']} yaml={yaml_path}")
  174. if __name__ == "__main__":
  175. main()