"""Vision check: overhead RGB image -> 3x3 board by colour segmentation (numpy only). X tokens are red cubes, O tokens are blue cylinders. For each cell we look at a square ROI around the cell centre's pixel (projected by the server from the camera intrinsics/extrinsics) and count red-ish / blue-ish pixels. """ from __future__ import annotations import numpy as np def masks(img: np.ndarray) -> tuple[np.ndarray, np.ndarray]: im = img[..., :3].astype(np.int16) r, g, b = im[..., 0], im[..., 1], im[..., 2] red = (r > 110) & (r > g + 50) & (r > b + 50) blue = (b > 90) & (b > r + 40) & (b > g + 20) return red, blue def classify(img: np.ndarray, cell_px: list[tuple[float, float]], half: int | None = None, thresh: float = 0.12) -> dict: """cell_px: 9 (u, v) pixel centres (u = column, v = row). Returns {board, red_frac, blue_frac}.""" red, blue = masks(img) if half is None: # ROI = 60% of the cell pitch in pixels half = max(2, int(0.3 * float(np.hypot(cell_px[1][0] - cell_px[0][0], cell_px[1][1] - cell_px[0][1])))) H, W = red.shape board, rf, bf = [], [], [] for u, v in cell_px: u0, u1 = max(0, int(round(u)) - half), min(W, int(round(u)) + half + 1) v0, v1 = max(0, int(round(v)) - half), min(H, int(round(v)) + half + 1) n = max(1, (u1 - u0) * (v1 - v0)) fr = float(red[v0:v1, u0:u1].sum()) / n fb = float(blue[v0:v1, u0:u1].sum()) / n rf.append(round(fr, 3)) bf.append(round(fb, 3)) board.append("X" if fr >= thresh and fr >= fb else ("O" if fb >= thresh else " ")) return {"board": board, "red_frac": rf, "blue_frac": bf}