|
| 1 | +"""Find the visually salient regions of a frame (spectral-residual saliency). |
| 2 | +
|
| 3 | +When there is no template, no known colour and no text to OCR, an agent still |
| 4 | +needs a cue for *where to look* — the region that stands out from its |
| 5 | +surroundings (a popup, a badge, a highlighted row). ``saliency`` computes the |
| 6 | +spectral-residual saliency map (Hou & Zhang 2007) — ``log`` amplitude minus its |
| 7 | +local average, reconstructed through the phase — and turns it into ranked salient |
| 8 | +boxes. |
| 9 | +
|
| 10 | +The transform is a pure ``numpy`` FFT (``cv2.saliency`` lives in the forbidden |
| 11 | +opencv-contrib package, so it is re-implemented here over base opencv only). It |
| 12 | +reuses ``visual_match``'s grayscale loader for the source (any ndarray / path / |
| 13 | +PIL image, or the live screen) and ``cv2_utils.blobs.connected_boxes`` for the |
| 14 | +region extraction. cv2 / numpy are lazily imported. Imports no ``PySide6``. |
| 15 | +""" |
| 16 | +from typing import Any, Dict, List, Optional, Sequence, Tuple |
| 17 | + |
| 18 | +ImageSource = Any |
| 19 | + |
| 20 | + |
| 21 | +def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]): |
| 22 | + from je_auto_control.utils.visual_match.visual_match import _haystack_gray |
| 23 | + return _haystack_gray(source, region) |
| 24 | + |
| 25 | + |
| 26 | +def _saliency_from_gray(gray, size: int): |
| 27 | + import cv2 |
| 28 | + import numpy as np |
| 29 | + small = cv2.resize(gray, (size, size), |
| 30 | + interpolation=cv2.INTER_AREA).astype(np.float32) |
| 31 | + fft = np.fft.fft2(small) |
| 32 | + log_amplitude = np.log(np.abs(fft) + 1e-8) |
| 33 | + residual = log_amplitude - cv2.blur(log_amplitude, (3, 3)) |
| 34 | + recon = np.fft.ifft2(np.exp(residual + 1j * np.angle(fft))) |
| 35 | + smoothed = cv2.GaussianBlur(np.abs(recon) ** 2, (0, 0), sigmaX=3.0) |
| 36 | + peak = float(smoothed.max()) |
| 37 | + if peak > 0: |
| 38 | + smoothed = smoothed / peak |
| 39 | + return smoothed.astype(np.float32) |
| 40 | + |
| 41 | + |
| 42 | +def saliency_map(source: Optional[ImageSource] = None, *, |
| 43 | + region: Optional[Sequence[int]] = None, size: int = 64): |
| 44 | + """Return the normalised (0–1) spectral-residual saliency map as an ndarray. |
| 45 | +
|
| 46 | + The map is computed at ``size`` x ``size`` (the algorithm's native low |
| 47 | + resolution); higher = more salient. |
| 48 | + """ |
| 49 | + return _saliency_from_gray(_gray(source, region), int(size)) |
| 50 | + |
| 51 | + |
| 52 | +def _regions_from_saliency(saliency, orig_shape: Tuple[int, int], |
| 53 | + threshold: Optional[float], min_area: int, |
| 54 | + size: int) -> List[Dict[str, Any]]: |
| 55 | + from je_auto_control.utils.cv2_utils.blobs import connected_boxes |
| 56 | + if threshold is not None: |
| 57 | + cut = float(threshold) |
| 58 | + else: # scale-invariant: regions standing 2 std above the mean saliency |
| 59 | + cut = float(saliency.mean()) + 2.0 * float(saliency.std()) |
| 60 | + mask = (saliency >= cut).astype("uint8") * 255 |
| 61 | + orig_height, orig_width = int(orig_shape[0]), int(orig_shape[1]) |
| 62 | + scale_x, scale_y = orig_width / float(size), orig_height / float(size) |
| 63 | + regions: List[Dict[str, Any]] = [] |
| 64 | + for box in connected_boxes(mask, min_area=min_area): |
| 65 | + x, y = int(box["x"] * scale_x), int(box["y"] * scale_y) |
| 66 | + width = max(1, int(box["width"] * scale_x)) |
| 67 | + height = max(1, int(box["height"] * scale_y)) |
| 68 | + patch = saliency[box["y"]:box["y"] + box["height"], |
| 69 | + box["x"]:box["x"] + box["width"]] |
| 70 | + score = float(patch.mean()) if patch.size else 0.0 |
| 71 | + regions.append({"x": x, "y": y, "width": width, "height": height, |
| 72 | + "center": [x + width // 2, y + height // 2], |
| 73 | + "score": score}) |
| 74 | + regions.sort(key=lambda region: region["score"], reverse=True) |
| 75 | + return regions |
| 76 | + |
| 77 | + |
| 78 | +def salient_regions(source: Optional[ImageSource] = None, *, |
| 79 | + region: Optional[Sequence[int]] = None, size: int = 64, |
| 80 | + threshold: Optional[float] = None, |
| 81 | + min_area: int = 4) -> List[Dict[str, Any]]: |
| 82 | + """Return salient regions as ``[{x, y, width, height, center, score}]``. |
| 83 | +
|
| 84 | + Boxes are thresholded from the saliency map (default cut = 3x the mean, |
| 85 | + per Hou & Zhang), extracted with ``connected_boxes`` and scaled back to the |
| 86 | + source's pixel coordinates, ranked most-salient first. |
| 87 | + """ |
| 88 | + gray = _gray(source, region) |
| 89 | + saliency = _saliency_from_gray(gray, int(size)) |
| 90 | + return _regions_from_saliency(saliency, gray.shape[:2], threshold, |
| 91 | + int(min_area), int(size)) |
| 92 | + |
| 93 | + |
| 94 | +def most_salient(source: Optional[ImageSource] = None, *, |
| 95 | + region: Optional[Sequence[int]] = None, size: int = 64, |
| 96 | + threshold: Optional[float] = None, |
| 97 | + min_area: int = 4) -> Optional[Dict[str, Any]]: |
| 98 | + """Return the single most salient region, or ``None`` if none stand out.""" |
| 99 | + regions = salient_regions(source, region=region, size=size, |
| 100 | + threshold=threshold, min_area=min_area) |
| 101 | + return regions[0] if regions else None |
0 commit comments