"""Shape-agnostic bright-target lock (no class / no training).""" from __future__ import annotations from typing import Optional, Tuple import cv2 import numpy as np from tracker.preprocess import erase_green_reticle Xyxy = Tuple[float, float, float, float] def find_white_target( frame_bgr: np.ndarray, *, erase_green: bool = True, search_near: Optional[Tuple[float, float]] = None, near_radius: float = 220.0, prefer_center: bool = True, min_area: float = 600.0, max_area_ratio: float = 0.25, ) -> Optional[Xyxy]: """ Find a bright, low-saturation blob (opaque phase of the minigame target). Shape-agnostic: circle / star / irregular all work the same. """ img = erase_green_reticle(frame_bgr) if erase_green else frame_bgr h, w = img.shape[:2] max_area = w * h * max_area_ratio hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # White / near-white fill. mask = cv2.inRange(hsv, np.array([0, 0, 185]), np.array([180, 70, 255])) 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) if not contours: return None cx0, cy0 = (w * 0.5, h * 0.5) best: Optional[Xyxy] = None best_score = -1.0 for cnt in contours: area = float(cv2.contourArea(cnt)) if area < min_area or area > max_area: continue x, y, bw, bh = cv2.boundingRect(cnt) if bw < 12 or bh < 12: continue # Reject ultra-thin UI strokes. if area / float(max(bw * bh, 1)) < 0.25: continue cx = x + bw * 0.5 cy = y + bh * 0.5 mean_v = float(cv2.mean(gray, mask=mask[y : y + bh, x : x + bw])[0]) if search_near is not None: dist = float(np.hypot(cx - search_near[0], cy - search_near[1])) if dist > near_radius: continue dist_term = 1.0 / (1.0 + dist / 80.0) elif prefer_center: dist = float(np.hypot(cx - cx0, cy - cy0)) # Soft prior: prefer nearer to screen center (game spawns mid). dist_term = 1.0 / (1.0 + dist / (0.35 * max(w, h))) else: dist_term = 1.0 score = area * (mean_v / 255.0) * dist_term if score > best_score: best_score = score best = (float(x), float(y), float(x + bw), float(y + bh)) return best def xyxy_to_xywh(xyxy: Xyxy) -> Tuple[float, float, float, float]: x1, y1, x2, y2 = xyxy return x1, y1, max(1.0, x2 - x1), max(1.0, y2 - y1) def xywh_to_xyxy(xywh: Tuple[float, float, float, float]) -> Xyxy: x, y, w, h = xywh return x, y, x + w, y + h def clip_xyxy(xyxy: Xyxy, width: int, height: int) -> Optional[Xyxy]: x1, y1, x2, y2 = xyxy x1 = float(np.clip(x1, 0, width - 1)) y1 = float(np.clip(y1, 0, height - 1)) x2 = float(np.clip(x2, 0, width - 1)) y2 = float(np.clip(y2, 0, height - 1)) if x2 - x1 < 8 or y2 - y1 < 8: return None return x1, y1, x2, y2