File size: 3,689 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad6045
 
 
33c14d6
 
 
 
 
 
 
fad6045
 
 
 
33c14d6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""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"))