"""Display-only decoy (干扰项) boxes. Does not change tracking / training.""" from __future__ import annotations from typing import Dict, List, Optional, Tuple import cv2 import numpy as np from tracker.preprocess import erase_green_reticle Xyxy = Tuple[float, float, float, float] def _iou(a: Xyxy, b: Xyxy) -> float: x1, y1 = max(a[0], b[0]), max(a[1], b[1]) x2, y2 = min(a[2], b[2]), min(a[3], b[3]) iw, ih = max(0.0, x2 - x1), max(0.0, y2 - y1) inter = iw * ih if inter <= 0: return 0.0 aa = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1]) bb = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1]) return inter / max(aa + bb - inter, 1e-6) def _center(b: Xyxy) -> Tuple[float, float]: return ((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5) def _nms(boxes: List[Xyxy], thr: float = 0.35) -> List[Xyxy]: order = sorted(boxes, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]), reverse=True) keep: List[Xyxy] = [] for b in order: if all(_iou(b, k) < thr for k in keep): keep.append(b) return keep def find_shape_candidates( frame_bgr: np.ndarray, target_xyxy: Optional[Xyxy] = None, max_n: int = 20, ) -> List[Xyxy]: """Find similar shape-like regions (solid white + edge outlines). Display only.""" # Work at half-res for speed, then scale boxes back. full_h, full_w = frame_bgr.shape[:2] scale = 0.5 small = cv2.resize(frame_bgr, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA) clean = erase_green_reticle(small) h, w = clean.shape[:2] gray = cv2.cvtColor(clean, cv2.COLOR_BGR2GRAY) hsv = cv2.cvtColor(clean, cv2.COLOR_BGR2HSV) boxes: List[Xyxy] = [] inv = 1.0 / scale scaled_target = None if target_xyxy is not None: scaled_target = tuple(v * scale for v in target_xyxy) tw = max(20.0, scaled_target[2] - scaled_target[0]) th = max(20.0, scaled_target[3] - scaled_target[1]) min_side, max_side = tw * 0.45, tw * 2.2 min_area, max_area = tw * th * 0.25, tw * th * 4.0 else: min_side, max_side = 20.0, min(w, h) * 0.35 min_area, max_area = 300.0, w * h * 0.08 # 1) Bright solid blobs (opaque phase target/decoys). bright = cv2.bitwise_and( cv2.inRange(gray, 200, 255), cv2.inRange(hsv[:, :, 1], 0, 80), ) green = cv2.inRange(hsv, np.array([40, 80, 80]), np.array([95, 255, 255])) bright = cv2.bitwise_and(bright, cv2.bitwise_not(green)) k = np.ones((3, 3), np.uint8) bright = cv2.morphologyEx(bright, cv2.MORPH_OPEN, k, iterations=1) bright = cv2.morphologyEx(bright, cv2.MORPH_CLOSE, k, iterations=1) cnts, _ = cv2.findContours(bright, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: area = float(cv2.contourArea(c)) if area < min_area or area > max_area: continue x, y, bw, bh = cv2.boundingRect(c) if bw < min_side or bh < min_side or bw > max_side or bh > max_side: continue if area / float(bw * bh) < 0.25: continue boxes.append((float(x), float(y), float(x + bw), float(y + bh))) # 2) Edge outlines (faded / hollow decoys like the triangular rings). blur = cv2.GaussianBlur(gray, (5, 5), 0) edges = cv2.Canny(blur, 60, 140) edges = cv2.dilate(edges, k, iterations=1) edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8), iterations=2) cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: area = float(cv2.contourArea(c)) if area < min_area * 0.5 or area > max_area * 1.5: continue x, y, bw, bh = cv2.boundingRect(c) if bw < min_side * 0.8 or bh < min_side * 0.8: continue if bw > max_side * 1.3 or bh > max_side * 1.3: continue peri = cv2.arcLength(c, True) if peri <= 0: continue approx = cv2.approxPolyDP(c, 0.04 * peri, True) # Prefer polygon-like outlines (triangle/quad/irregular), reject long strips. if len(approx) < 3 or len(approx) > 12: continue aspect = bw / float(bh) if aspect > 2.6 or aspect < 0.38: continue boxes.append((float(x), float(y), float(x + bw), float(y + bh))) boxes = _nms(boxes, thr=0.4) # Drop the one overlapping the tracked target (compare in small-res space). if scaled_target is not None: boxes = [b for b in boxes if _iou(b, scaled_target) < 0.35] tc = _center(scaled_target) filtered = [] for b in boxes: bc = _center(b) if float(np.hypot(bc[0] - tc[0], bc[1] - tc[1])) < 14: continue filtered.append(b) boxes = filtered # Scale boxes back to full resolution. out: List[Xyxy] = [] for x1, y1, x2, y2 in boxes[:max_n]: out.append((x1 * inv, y1 * inv, x2 * inv, y2 * inv)) return out class DecoyVisualizer: """Stable cyan id labels for decoys (display only).""" def __init__(self) -> None: self._next_id = 1 self._tracks: Dict[int, Xyxy] = {} self._miss: Dict[int, int] = {} def reset(self) -> None: self._next_id = 1 self._tracks.clear() self._miss.clear() def update( self, frame_bgr: np.ndarray, target_xyxy: Optional[Xyxy], ) -> List[Tuple[int, Xyxy]]: dets = find_shape_candidates(frame_bgr, target_xyxy=target_xyxy) assigned_det = set() used_ids = set() # Match existing ids by IoU / distance. for tid, prev in list(self._tracks.items()): best_j, best = -1, 0.0 for j, det in enumerate(dets): if j in assigned_det: continue score = _iou(prev, det) dc = float( np.hypot(_center(prev)[0] - _center(det)[0], _center(prev)[1] - _center(det)[1]) ) score = score + max(0.0, 1.0 - dc / 100.0) * 0.3 if score > best and (_iou(prev, det) > 0.1 or dc < 70): best, best_j = score, j if best_j >= 0: self._tracks[tid] = dets[best_j] self._miss[tid] = 0 assigned_det.add(best_j) used_ids.add(tid) else: self._miss[tid] = self._miss.get(tid, 0) + 1 for j, det in enumerate(dets): if j in assigned_det: continue tid = self._next_id self._next_id += 1 self._tracks[tid] = det self._miss[tid] = 0 used_ids.add(tid) # Drop stale. for tid in list(self._tracks.keys()): if self._miss.get(tid, 0) > 8: self._tracks.pop(tid, None) self._miss.pop(tid, None) return [(tid, box) for tid, box in self._tracks.items() if self._miss.get(tid, 0) <= 2]