File size: 14,299 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Fit the fixed camera of one dataset from its own recordings: no calibration target, no hand marks.

The arm is orange; the recorded joints give, through the URDF, where every part of the arm is. The camera (pose and
pinhole intrinsics, in the 256 x 256 stored image) is the one under which the projected arm surface and the orange
pixels coincide: a two-way chamfer cost (projected points to the nearest orange pixel, orange pixels to the nearest
projected point), each distance clipped so that occluded parts and other orange things count only up to the clip.
A coarse search over look-at poses around the base, then Adam on all ten parameters.

    python scripts/fit_camera.py --shard ~/pop/realworld/shards/train/tmhoanggg__so101-push \
        --urdf ~/pop/realworld/so101_urdf/so101_new_calib.urdf --out ~/pop/realworld/camera

Writes <out>/<shard>.json (camera, cost per episode) and <out>/<shard>_overlay.png (sampled frames with the
projected arm and the gripper tip) for checking by eye.
"""
import argparse
import json
import math
import os
import sys
import zlib
import struct

import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.so101 import SO101, SO101Torch, project, rotvec_to_matrix  # noqa: E402

G = 128  # mask grid (the 256 px image halved)
OUT = 1.0  # cost of a model point projected outside the frame (grid px)
BLACK = ("sts3215", "waveshare")  # meshes of parts that are not orange: servos, the controller plate


def orange_mask(img: np.ndarray, hue=(8.0, 38.0), sat=0.5, val=0.3) -> np.ndarray:
    """(N, H, W, 3) uint8 -> (N, H, W) bool."""
    x = img.astype(np.float32) / 255
    mx, mn = x.max(-1), x.min(-1)
    d = mx - mn + 1e-6
    r, g, b = x[..., 0], x[..., 1], x[..., 2]
    h = np.where(mx == r, ((g - b) / d) % 6, np.where(mx == g, (b - r) / d + 2, (r - g) / d + 4)) * 60
    s = d / (mx + 1e-6)
    return (h >= hue[0]) & (h <= hue[1]) & (s >= sat) & (mx >= val)


def dist_maps(mask: torch.Tensor) -> torch.Tensor:
    """(N, G, G) bool -> (N, G, G) distance (grid px) to the nearest True pixel (large where none)."""
    N = mask.shape[0]
    yy, xx = torch.meshgrid(torch.arange(G, device=mask.device), torch.arange(G, device=mask.device), indexing="ij")
    grid = torch.stack([xx, yy], -1).reshape(-1, 2).float()
    out = torch.full((N, G * G), 1e3, device=mask.device)
    for i in range(N):
        o = grid[mask[i].reshape(-1)]
        if len(o):
            out[i] = torch.cdist(grid, o).min(1).values
    return out.reshape(N, G, G)


def lookat_cam(C: np.ndarray, T: np.ndarray, f: float) -> dict:
    """Camera at C looking at T, image y pointing down (towards -z of the base)."""
    z = T - C; z = z / np.linalg.norm(z)
    up = np.array([0.0, 0.0, 1.0])
    x = np.cross(z, up); x = x / (np.linalg.norm(x) + 1e-9)
    y = np.cross(z, x)
    R = np.stack([x, y, z])  # rows: camera axes in base coords; base->camera rotation
    w = matrix_to_rotvec(R)
    return {"rotvec": w, "t": -R @ C, "f": np.array([f, f]), "c": np.array([128.0, 128.0])}


def matrix_to_rotvec(R: np.ndarray) -> np.ndarray:
    th = math.acos(max(-1.0, min(1.0, (np.trace(R) - 1) / 2)))
    if th < 1e-6:
        return np.zeros(3)
    if abs(th - math.pi) < 1e-4:
        w, V = np.linalg.eigh(R + np.eye(3))
        a = V[:, -1]
        return a * th
    a = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) / (2 * math.sin(th))
    return a * th


def full_cam(par: dict, W: int, H: int, R: int) -> dict:
    """Square pixels in the source W x H image, stored at R x R: fx = f0 R / W, fy = f0 R / H; principal point at
    the centre plus dc (source px)."""
    sx, sy = R / W, R / H
    s = torch.stack([torch.tensor(sx, device=par["f0"].device), torch.tensor(sy, device=par["f0"].device)])
    out = {"rotvec": par["rotvec"], "t": par["t"], "f": par["f0"] * s,
           "c": torch.tensor([R / 2, R / 2], device=par["f0"].device) + par["dc"] * s}
    if "k" in par:
        out["k1"], out["k2"] = par["k"][0], par["k"][1]
    return out


def to_t(cam: dict, dev) -> dict:
    return {k: torch.tensor(np.asarray(v, np.float64), dtype=torch.float32, device=dev) for k, v in cam.items()}


def cost(P: torch.Tensor, D: torch.Tensor, O: list, cam: dict, clip: float, per_frame=False):
    """P (N, K, 3) points; D (N, G, G) distance maps; O = (padded orange pixels (N, M, 2) in grid px, valid (N, M))."""
    uv, z = project(P, cam)
    g = uv / 2.0  # 256 px -> grid px
    norm = g / (G - 1) * 2 - 1
    d1 = F.grid_sample(D[:, None], norm[:, :, None, :], align_corners=True, padding_mode="border")[:, 0, :, 0]
    behind = z <= 0.02
    outside = (g[..., 0] < 0) | (g[..., 0] > G - 1) | (g[..., 1] < 0) | (g[..., 1] > G - 1)
    # a point outside the frame is neither right nor wrong (the base is often cut off at the bottom edge): neutral
    d1 = torch.where(behind, torch.full_like(d1, clip), torch.where(outside, torch.full_like(d1, OUT), d1.clamp(max=clip)))
    a = d1.mean(1)
    Opad, Ovalid = O  # (N, M, 2) orange pixels padded, (N, M) valid
    dmin = torch.cdist(Opad, g).min(2).values.clamp(max=clip)
    b = (dmin * Ovalid).sum(1) / Ovalid.sum(1).clamp_min(1)
    c = a + b
    return c if per_frame else c.mean()


def write_png(path: str, img: np.ndarray):
    h, w, _ = img.shape
    raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))

    def chunk(t, b):
        return struct.pack(">I", len(b)) + t + b + struct.pack(">I", zlib.crc32(t + b) & 0xffffffff)
    open(path, "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) +
                          chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--shard", required=True)
    p.add_argument("--urdf", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--frames", type=int, default=200)
    p.add_argument("--points", type=int, default=150, help="surface points per mesh")
    p.add_argument("--clip", type=float, default=8.0, help="distance clip, grid px (2 image px each)")
    p.add_argument("--iters", type=int, default=1500)
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--info", default="", help="the dataset's meta/info.json (source image size)")
    p.add_argument("--joint-offsets", type=int, default=1, help="also fit a constant offset per arm joint (degrees)")
    p.add_argument("--az", type=lambda x: [int(v) for v in x.split(",")], default=[0, 340],
                   help="coarse search: camera azimuth range around the base, degrees (0 = in front of the arm)")
    a = p.parse_args()
    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    torch.manual_seed(a.seed)
    meta = json.load(open(os.path.join(a.shard, "meta.json")))
    eps = json.load(open(os.path.join(a.shard, "episodes.json")))
    N, R = meta["frames"], meta["res"]
    img = np.memmap(os.path.join(a.shard, "agent.u8"), np.uint8, "r", shape=(N, R, R, 3))
    state = np.load(os.path.join(a.shard, "arrays.npz"))["state"].astype(np.float64)
    ep_of = np.load(os.path.join(a.shard, "arrays.npz"))["ep"]
    rng = np.random.default_rng(a.seed)
    idx = np.sort(rng.choice(N, size=min(a.frames, N), replace=False))
    small = np.stack([img[i][::2, ::2] for i in idx])
    mask = torch.from_numpy(orange_mask(small)).to(dev)
    D = dist_maps(mask)
    yy, xx = torch.meshgrid(torch.arange(G, device=dev), torch.arange(G, device=dev), indexing="ij")
    grid = torch.stack([xx, yy], -1).reshape(-1, 2).float()
    M = 300
    Opad = torch.zeros(len(idx), M, 2, device=dev)
    Ovalid = torch.zeros(len(idx), M, device=dev)
    for i in range(len(idx)):
        o = grid[mask[i].reshape(-1)]
        if len(o) > M:
            o = o[torch.randperm(len(o), device=dev)[:M]]
        Opad[i, :len(o)] = o
        Ovalid[i, :len(o)] = 1
    O = (Opad, Ovalid)
    arm = SO101(a.urdf, a.points, a.seed, exclude=BLACK)
    kin = SO101Torch(arm, dev)
    Q = torch.tensor(state[idx], dtype=torch.float32, device=dev)
    offmask = torch.tensor([1, 1, 1, 1, 1, 0], dtype=torch.float32, device=dev)  # gripper opening: not fitted
    P = torch.tensor(arm.points(state[idx]), dtype=torch.float32, device=dev)
    print(f"{meta['dataset']}: {len(idx)} frames, {P.shape[1]} points, orange px per frame median "
          f"{int(np.median(mask.reshape(len(idx), -1).sum(1).cpu().numpy()))}", flush=True)

    # coarse search: camera on a sphere around a point in front of the base, looking at it
    info = json.load(open(a.info)) if a.info else None
    H, W = (info["features"][meta["agent"]]["shape"][:2] if info else (R, R))
    sub = slice(0, min(60, len(idx)))
    Osub = (O[0][sub], O[1][sub])
    cands = []
    with torch.no_grad():
        for tx in (0.1, 0.25, 0.4):
          T = np.array([tx, 0.0, 0.03])
          for az in range(a.az[0], a.az[1] + 1, 20):
            for el in range(5, 75, 10):
                for dist in (0.25, 0.35, 0.5, 0.7, 1.0):
                    for f in (350.0, 450.0, 550.0, 700.0, 900.0):
                        C = T + dist * np.array([math.cos(math.radians(el)) * math.cos(math.radians(az)),
                                                 math.cos(math.radians(el)) * math.sin(math.radians(az)),
                                                 math.sin(math.radians(el))])
                        cam = lookat_cam(C, T, f)
                        cam = {"rotvec": cam["rotvec"], "t": cam["t"], "f0": np.array(f), "dc": np.zeros(2)}
                        c = cost(P[sub], D[sub], Osub, full_cam(to_t(cam, dev), W, H, R), a.clip).item()
                        cands.append((c, (tx, az, el), dist, f, cam))
    cands.sort(key=lambda r: r[0])
    print("coarse best:", [(round(c, 2), pose, d, f) for c, pose, d, f, _ in cands[:6]], flush=True)

    best = None
    for c0, pose, dist, f, cam in cands[:8]:
        par = {k: torch.tensor(np.asarray(v, np.float64), dtype=torch.float32, device=dev, requires_grad=True)
               for k, v in cam.items()}
        par["off"] = torch.zeros(6, device=dev, requires_grad=True)
        par["k"] = torch.zeros(2, device=dev, requires_grad=True)
        groups = [{"params": [par["rotvec"]], "lr": 0.01}, {"params": [par["t"]], "lr": 0.005},
                  {"params": [par["f0"], par["dc"]], "lr": 2.0}, {"params": [par["k"]], "lr": 0.003}]
        opt = torch.optim.Adam(groups)
        opt_off = torch.optim.Adam([par["off"]], lr=0.2)
        for it in range(a.iters):
            opt.zero_grad(); opt_off.zero_grad()
            Pq = kin.points(Q, par["off"] * offmask) if a.joint_offsets and it >= a.iters // 3 else P
            c = cost(Pq, D, O, full_cam(par, W, H, R), a.clip)
            # principal point: weak pull to the centre (1 grid px of cost per 100 source px of offset)
            # joint offsets: weak pull to zero (1 grid px of cost per 30 degrees)
            reg = (par["dc"] ** 2).sum() / 100 ** 2 + (par["off"] ** 2).sum() / 30 ** 2
            (c + reg).backward()
            opt.step()
            if a.joint_offsets and it >= a.iters // 3:
                opt_off.step()
        c = c.item()
        print(f"  start (target x, az, el) {pose} dist {dist} f {f}: coarse {c0:.2f} -> refined {c:.3f}", flush=True)
        if best is None or c < best[0]:
            best = (c, {k: v.detach() for k, v in par.items()})
    cbest, par = best
    cam = full_cam(par, W, H, R)

    # every frame of the shard: tip pixel; cost per sampled frame grouped by episode
    off = (par["off"] * offmask).detach()
    with torch.no_grad():
        P = kin.points(Q, off)
        per = cost(P, D, O, cam, a.clip, per_frame=True).cpu().numpy()
    by_ep = {}
    for i, c in zip(idx, per):
        by_ep.setdefault(int(ep_of[i]), []).append(float(c))
    Rm = rotvec_to_matrix(cam["rotvec"]).cpu().numpy()
    Cw = -Rm.T @ cam["t"].cpu().numpy()
    res = {"dataset": meta["dataset"], "shard": os.path.basename(a.shard.rstrip("/")), "image_size": R,
           "camera": {k: v.cpu().tolist() for k, v in cam.items()}, "camera_center_base_m": Cw.tolist(),
           "joint_offsets_deg": off.cpu().tolist()[:5], "distortion_k1_k2": par["k"].cpu().tolist(), "source_size": [W, H], "focal_source_px": float(par["f0"]), "principal_offset_source_px": par["dc"].cpu().tolist(),
           "cost": cbest, "cost_units": "grid px (= 2 image px), clipped at %.0f" % a.clip,
           "cost_per_episode": {str(k): round(float(np.mean(v)), 3) for k, v in sorted(by_ep.items())},
           "frames_used": len(idx), "urdf": a.urdf}
    os.makedirs(a.out, exist_ok=True)
    json.dump(res, open(os.path.join(a.out, res["shard"] + ".json"), "w"), indent=1)

    # overlay: 8 frames, projected points (cyan) and tip (red cross)
    show = idx[np.linspace(0, len(idx) - 1, 8).round().astype(int)]
    with torch.no_grad():
        Qs = torch.tensor(state[show], dtype=torch.float32, device=dev)
        uv, _ = project(kin.points(Qs, off), cam)
        tip, _ = project(kin.tip(Qs, off), cam)
    tiles = []
    for k, i in enumerate(show):
        im = np.array(img[i])
        for u, v in uv[k, ::2].cpu().numpy().round().astype(int):
            if 0 <= u < R and 0 <= v < R:
                im[v, u] = (0, 255, 255)
        u, v = tip[k].cpu().numpy().round().astype(int)
        for dd in range(-7, 8):
            for (x, y) in ((u + dd, v), (u, v + dd), (u + dd, v + 1), (u + 1, v + dd)):
                if 0 <= x < R and 0 <= y < R:
                    im[y, x] = (255, 0, 255)
        tiles.append(im)
    sheet = np.concatenate([np.concatenate(tiles[:4], 1), np.concatenate(tiles[4:], 1)], 0)
    write_png(os.path.join(a.out, res["shard"] + "_overlay.png"), sheet)
    print(f"joint offsets (deg): {np.round(res['joint_offsets_deg'], 2).tolist()}", flush=True)
    print(f"camera: cost {cbest:.3f}, centre {np.round(Cw, 3).tolist()} m, f {np.round(res['camera']['f'], 1).tolist()}, "
          f"c {np.round(res['camera']['c'], 1).tolist()} | source f0 {res['focal_source_px']:.0f} px, principal offset "
          f"{np.round(res['principal_offset_source_px'], 1).tolist()} px, k1 k2 {np.round(res['distortion_k1_k2'], 3).tolist()}", flush=True)


if __name__ == "__main__":
    main()