decoy_viz.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """Display-only decoy (干扰项) boxes. Does not change tracking / training."""
  2. from __future__ import annotations
  3. from typing import Dict, List, Optional, Tuple
  4. import cv2
  5. import numpy as np
  6. from tracker.preprocess import erase_green_reticle
  7. Xyxy = Tuple[float, float, float, float]
  8. def _iou(a: Xyxy, b: Xyxy) -> float:
  9. x1, y1 = max(a[0], b[0]), max(a[1], b[1])
  10. x2, y2 = min(a[2], b[2]), min(a[3], b[3])
  11. iw, ih = max(0.0, x2 - x1), max(0.0, y2 - y1)
  12. inter = iw * ih
  13. if inter <= 0:
  14. return 0.0
  15. aa = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
  16. bb = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
  17. return inter / max(aa + bb - inter, 1e-6)
  18. def _center(b: Xyxy) -> Tuple[float, float]:
  19. return ((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5)
  20. def _nms(boxes: List[Xyxy], thr: float = 0.35) -> List[Xyxy]:
  21. order = sorted(boxes, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]), reverse=True)
  22. keep: List[Xyxy] = []
  23. for b in order:
  24. if all(_iou(b, k) < thr for k in keep):
  25. keep.append(b)
  26. return keep
  27. def find_shape_candidates(
  28. frame_bgr: np.ndarray,
  29. target_xyxy: Optional[Xyxy] = None,
  30. max_n: int = 20,
  31. ) -> List[Xyxy]:
  32. """Find similar shape-like regions (solid white + edge outlines). Display only."""
  33. # Work at half-res for speed, then scale boxes back.
  34. full_h, full_w = frame_bgr.shape[:2]
  35. scale = 0.5
  36. small = cv2.resize(frame_bgr, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
  37. clean = erase_green_reticle(small)
  38. h, w = clean.shape[:2]
  39. gray = cv2.cvtColor(clean, cv2.COLOR_BGR2GRAY)
  40. hsv = cv2.cvtColor(clean, cv2.COLOR_BGR2HSV)
  41. boxes: List[Xyxy] = []
  42. inv = 1.0 / scale
  43. scaled_target = None
  44. if target_xyxy is not None:
  45. scaled_target = tuple(v * scale for v in target_xyxy)
  46. tw = max(20.0, scaled_target[2] - scaled_target[0])
  47. th = max(20.0, scaled_target[3] - scaled_target[1])
  48. min_side, max_side = tw * 0.45, tw * 2.2
  49. min_area, max_area = tw * th * 0.25, tw * th * 4.0
  50. else:
  51. min_side, max_side = 20.0, min(w, h) * 0.35
  52. min_area, max_area = 300.0, w * h * 0.08
  53. # 1) Bright solid blobs (opaque phase target/decoys).
  54. bright = cv2.bitwise_and(
  55. cv2.inRange(gray, 200, 255),
  56. cv2.inRange(hsv[:, :, 1], 0, 80),
  57. )
  58. green = cv2.inRange(hsv, np.array([40, 80, 80]), np.array([95, 255, 255]))
  59. bright = cv2.bitwise_and(bright, cv2.bitwise_not(green))
  60. k = np.ones((3, 3), np.uint8)
  61. bright = cv2.morphologyEx(bright, cv2.MORPH_OPEN, k, iterations=1)
  62. bright = cv2.morphologyEx(bright, cv2.MORPH_CLOSE, k, iterations=1)
  63. cnts, _ = cv2.findContours(bright, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  64. for c in cnts:
  65. area = float(cv2.contourArea(c))
  66. if area < min_area or area > max_area:
  67. continue
  68. x, y, bw, bh = cv2.boundingRect(c)
  69. if bw < min_side or bh < min_side or bw > max_side or bh > max_side:
  70. continue
  71. if area / float(bw * bh) < 0.25:
  72. continue
  73. boxes.append((float(x), float(y), float(x + bw), float(y + bh)))
  74. # 2) Edge outlines (faded / hollow decoys like the triangular rings).
  75. blur = cv2.GaussianBlur(gray, (5, 5), 0)
  76. edges = cv2.Canny(blur, 60, 140)
  77. edges = cv2.dilate(edges, k, iterations=1)
  78. edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8), iterations=2)
  79. cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  80. for c in cnts:
  81. area = float(cv2.contourArea(c))
  82. if area < min_area * 0.5 or area > max_area * 1.5:
  83. continue
  84. x, y, bw, bh = cv2.boundingRect(c)
  85. if bw < min_side * 0.8 or bh < min_side * 0.8:
  86. continue
  87. if bw > max_side * 1.3 or bh > max_side * 1.3:
  88. continue
  89. peri = cv2.arcLength(c, True)
  90. if peri <= 0:
  91. continue
  92. approx = cv2.approxPolyDP(c, 0.04 * peri, True)
  93. # Prefer polygon-like outlines (triangle/quad/irregular), reject long strips.
  94. if len(approx) < 3 or len(approx) > 12:
  95. continue
  96. aspect = bw / float(bh)
  97. if aspect > 2.6 or aspect < 0.38:
  98. continue
  99. boxes.append((float(x), float(y), float(x + bw), float(y + bh)))
  100. boxes = _nms(boxes, thr=0.4)
  101. # Drop the one overlapping the tracked target (compare in small-res space).
  102. if scaled_target is not None:
  103. boxes = [b for b in boxes if _iou(b, scaled_target) < 0.35]
  104. tc = _center(scaled_target)
  105. filtered = []
  106. for b in boxes:
  107. bc = _center(b)
  108. if float(np.hypot(bc[0] - tc[0], bc[1] - tc[1])) < 14:
  109. continue
  110. filtered.append(b)
  111. boxes = filtered
  112. # Scale boxes back to full resolution.
  113. out: List[Xyxy] = []
  114. for x1, y1, x2, y2 in boxes[:max_n]:
  115. out.append((x1 * inv, y1 * inv, x2 * inv, y2 * inv))
  116. return out
  117. class DecoyVisualizer:
  118. """Stable cyan id labels for decoys (display only)."""
  119. def __init__(self) -> None:
  120. self._next_id = 1
  121. self._tracks: Dict[int, Xyxy] = {}
  122. self._miss: Dict[int, int] = {}
  123. def reset(self) -> None:
  124. self._next_id = 1
  125. self._tracks.clear()
  126. self._miss.clear()
  127. def update(
  128. self,
  129. frame_bgr: np.ndarray,
  130. target_xyxy: Optional[Xyxy],
  131. ) -> List[Tuple[int, Xyxy]]:
  132. dets = find_shape_candidates(frame_bgr, target_xyxy=target_xyxy)
  133. assigned_det = set()
  134. used_ids = set()
  135. # Match existing ids by IoU / distance.
  136. for tid, prev in list(self._tracks.items()):
  137. best_j, best = -1, 0.0
  138. for j, det in enumerate(dets):
  139. if j in assigned_det:
  140. continue
  141. score = _iou(prev, det)
  142. dc = float(
  143. np.hypot(_center(prev)[0] - _center(det)[0], _center(prev)[1] - _center(det)[1])
  144. )
  145. score = score + max(0.0, 1.0 - dc / 100.0) * 0.3
  146. if score > best and (_iou(prev, det) > 0.1 or dc < 70):
  147. best, best_j = score, j
  148. if best_j >= 0:
  149. self._tracks[tid] = dets[best_j]
  150. self._miss[tid] = 0
  151. assigned_det.add(best_j)
  152. used_ids.add(tid)
  153. else:
  154. self._miss[tid] = self._miss.get(tid, 0) + 1
  155. for j, det in enumerate(dets):
  156. if j in assigned_det:
  157. continue
  158. tid = self._next_id
  159. self._next_id += 1
  160. self._tracks[tid] = det
  161. self._miss[tid] = 0
  162. used_ids.add(tid)
  163. # Drop stale.
  164. for tid in list(self._tracks.keys()):
  165. if self._miss.get(tid, 0) > 8:
  166. self._tracks.pop(tid, None)
  167. self._miss.pop(tid, None)
  168. return [(tid, box) for tid, box in self._tracks.items() if self._miss.get(tid, 0) <= 2]