"""The brain-to-hand contract: a translucent red square over the source and a translucent blue one over the destination square or the tray, drawn on each image. Squares are projected from the board plane with a pinhole camera model. In sim the camera pose comes from MuJoCo; on the real robot the same function takes the calibrated pose (board homography for fixed cameras, forward kinematics plus hand-eye calibration for the wrist). Drawn over everything, including the arm. """ from __future__ import annotations from dataclasses import dataclass import numpy as np from PIL import Image, ImageDraw NEAR = 0.01 # clip polygons this far in front of the lens @dataclass class Camera: pos: np.ndarray # world position rot: np.ndarray # 3x3 camera-to-world; camera looks down -z, +y up fovy_deg: float width: int height: int def _clip_near(poly_cam: np.ndarray) -> np.ndarray: """Sutherland-Hodgman clip of a camera-frame polygon against z <= -NEAR.""" out = [] n = len(poly_cam) for i in range(n): a, b = poly_cam[i], poly_cam[(i + 1) % n] ina, inb = a[2] <= -NEAR, b[2] <= -NEAR if ina: out.append(a) if ina != inb: t = (-NEAR - a[2]) / (b[2] - a[2]) out.append(a + t * (b - a)) return np.array(out) def project(cam: Camera, points_world: np.ndarray) -> np.ndarray | None: """Pixel coordinates of a world polygon, after near-plane clipping.""" local = (np.asarray(points_world) - cam.pos) @ cam.rot local = _clip_near(local) if len(local) < 3: return None f = cam.height / 2 / np.tan(np.radians(cam.fovy_deg) / 2) u = cam.width / 2 + f * local[:, 0] / -local[:, 2] v = cam.height / 2 - f * local[:, 1] / -local[:, 2] return np.stack([u, v], 1) @dataclass class Jitter: """Per-camera error in where the square is drawn, in the board plane.""" shift: np.ndarray # metres angle: float # radians about the square centre scale: float @staticmethod def sample(rng, cfg) -> "Jitter": o = cfg["overlay"] r = o["jitter_mm"] / 1000 * np.sqrt(rng.uniform()) a = rng.uniform(0, 2 * np.pi) return Jitter(np.array([r * np.cos(a), r * np.sin(a), 0.0]), np.radians(rng.uniform(-o["jitter_rot_deg"], o["jitter_rot_deg"])), 1 + rng.uniform(-o["jitter_scale"], o["jitter_scale"])) def apply(self, poly: np.ndarray, extra_shift=None) -> np.ndarray: c = poly.mean(0) cs, sn = np.cos(self.angle), np.sin(self.angle) rel = (poly - c) * [self.scale, self.scale, 1] rel = np.stack([cs * rel[:, 0] - sn * rel[:, 1], sn * rel[:, 0] + cs * rel[:, 1], rel[:, 2]], 1) shift = self.shift if extra_shift is None else self.shift + extra_shift return c + rel + shift def draw(image: np.ndarray, cam: Camera, polygons, alpha: float, outline: int = 0) -> np.ndarray: """Composite filled translucent polygons [(world_poly, rgb), ...] onto an RGB image, with an opaque edge `outline` pixels wide if given (makes small squares stand out).""" base = Image.fromarray(image).convert("RGBA") layer = Image.new("RGBA", base.size, (0, 0, 0, 0)) pen = ImageDraw.Draw(layer) for poly, rgb in polygons: px = project(cam, poly) if px is None: continue pts = [tuple(p) for p in px] pen.polygon(pts, fill=(*rgb, int(round(alpha * 255)))) if outline: pen.line(pts + [pts[0]], fill=(*rgb, 255), width=outline, joint="curve") return np.asarray(Image.alpha_composite(base, layer).convert("RGB"))