shape_tracker.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """White-blob lock helper used by hybrid (any shape while opaque)."""
  2. from __future__ import annotations
  3. from typing import Optional, Tuple
  4. import cv2
  5. import numpy as np
  6. MIN_AREA = 1500
  7. MAX_BBOX_RATIO = 0.12
  8. MIN_FILL = 0.35
  9. CENTER_WEIGHT = 0.7
  10. WHITE_V_MIN = 220
  11. WHITE_S_MAX = 70
  12. def find_white_target(
  13. frame_bgr: np.ndarray,
  14. near_xy: Optional[Tuple[float, float]] = None,
  15. near_radius: float = 1e9,
  16. ) -> Optional[Tuple[float, float, float, float]]:
  17. """Return xyxy of solid bright low-saturation blob, or None."""
  18. h, w = frame_bgr.shape[:2]
  19. hsv = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2HSV)
  20. gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
  21. mask = cv2.bitwise_and(
  22. cv2.inRange(gray, WHITE_V_MIN, 255),
  23. cv2.inRange(hsv[:, :, 1], 0, WHITE_S_MAX),
  24. )
  25. green = cv2.inRange(hsv, np.array([40, 80, 80]), np.array([95, 255, 255]))
  26. mask = cv2.bitwise_and(mask, cv2.bitwise_not(green))
  27. kernel = np.ones((3, 3), np.uint8)
  28. mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
  29. mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=1)
  30. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  31. if not contours:
  32. return None
  33. cx0, cy0 = near_xy if near_xy is not None else (w * 0.5, h * 0.5)
  34. max_bbox = w * h * MAX_BBOX_RATIO
  35. best = None
  36. best_score = -1.0
  37. for cnt in contours:
  38. area = float(cv2.contourArea(cnt))
  39. if area < MIN_AREA:
  40. continue
  41. x, y, bw, bh = cv2.boundingRect(cnt)
  42. bbox_area = float(bw * bh)
  43. if bw < 24 or bh < 24 or bbox_area > max_bbox:
  44. continue
  45. fill = area / max(bbox_area, 1.0)
  46. if fill < MIN_FILL:
  47. continue
  48. aspect = bw / float(bh)
  49. if aspect > 2.8 or aspect < 0.35:
  50. continue
  51. cx = x + bw * 0.5
  52. cy = y + bh * 0.5
  53. dist = float(np.hypot(cx - cx0, cy - cy0))
  54. if dist > near_radius:
  55. continue
  56. dist_norm = dist / (0.5 * float(np.hypot(w, h)))
  57. score = CENTER_WEIGHT * (1.0 - dist_norm) + (1.0 - CENTER_WEIGHT) * fill
  58. if score > best_score:
  59. best_score = score
  60. best = (float(x), float(y), float(x + bw), float(y + bh))
  61. return best