"""White-blob lock helper used by hybrid (any shape while opaque).""" from __future__ import annotations from typing import Optional, Tuple import cv2 import numpy as np MIN_AREA = 1500 MAX_BBOX_RATIO = 0.12 MIN_FILL = 0.35 CENTER_WEIGHT = 0.7 WHITE_V_MIN = 220 WHITE_S_MAX = 70 def find_white_target( frame_bgr: np.ndarray, near_xy: Optional[Tuple[float, float]] = None, near_radius: float = 1e9, ) -> Optional[Tuple[float, float, float, float]]: """Return xyxy of solid bright low-saturation blob, or None.""" h, w = frame_bgr.shape[:2] hsv = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY) mask = cv2.bitwise_and( cv2.inRange(gray, WHITE_V_MIN, 255), cv2.inRange(hsv[:, :, 1], 0, WHITE_S_MAX), ) 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((3, 3), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=1) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: return None cx0, cy0 = near_xy if near_xy is not None else (w * 0.5, h * 0.5) max_bbox = w * h * MAX_BBOX_RATIO best = None best_score = -1.0 for cnt in contours: area = float(cv2.contourArea(cnt)) if area < MIN_AREA: continue x, y, bw, bh = cv2.boundingRect(cnt) bbox_area = float(bw * bh) if bw < 24 or bh < 24 or bbox_area > max_bbox: continue fill = area / max(bbox_area, 1.0) if fill < MIN_FILL: continue aspect = bw / float(bh) if aspect > 2.8 or aspect < 0.35: continue cx = x + bw * 0.5 cy = y + bh * 0.5 dist = float(np.hypot(cx - cx0, cy - cy0)) if dist > near_radius: continue dist_norm = dist / (0.5 * float(np.hypot(w, h))) score = CENTER_WEIGHT * (1.0 - dist_norm) + (1.0 - CENTER_WEIGHT) * fill if score > best_score: best_score = score best = (float(x), float(y), float(x + bw), float(y + bh)) return best