File size: 12,044 Bytes
7efb58b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
"""Render a multi-view demo video of the 3D point tracks: all views side by side, persistent points with
fading trails, size and brightness from camera depth. No text on the frames.

The clips given on the command line are played back to back (consecutive subtask clips of one episode
tile it, so the point identities carry over).

usage: python render_demo.py --out demo.mp4 [--height 384] <clip_dir> [<clip_dir> ...]
"""
import argparse
import glob
import json
import os

import cv2
import numpy as np

SS = 3  # supersampling of the drawing layer


def view_order(name):
    return (0, int(name[4:])) if name.startswith("view") and name[4:].isdigit() else (1, name)


def read_video(path):
    import av

    with av.open(path) as c:
        return np.stack([f.to_ndarray(format="rgb24") for f in c.decode(video=0)])


def load_clip(d):
    meta = json.load(open(os.path.join(d, "meta.json")))
    n = meta["n_frames"]
    names = sorted(meta["views"], key=view_order)
    views = {}
    for v in names:
        m = meta["views"][v]
        intr = m["intrinsics"]
        T = np.asarray(m.get("T_cam_world_perframe", m["T_cam_world"]), np.float64)
        if T.ndim == 2:
            T = np.repeat(T[None], n, 0)
        views[v] = dict(
            K=np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]], np.float64),
            dist=np.array([intr.get(k, 0.0) for k in ("k1", "k2", "p1", "p2", "k3")], np.float64),
            wh=(intr["width"], intr["height"]), T=T[:n], rgb=read_video(os.path.join(d, f"{v}.mp4"))[:n])
    parts = {}
    for f in ["robot.npz", "gripper.npz"] + sorted(os.path.basename(p) for p in glob.glob(os.path.join(d, "object*.npz"))):
        if os.path.isfile(os.path.join(d, f)):
            parts[f[:-4]] = np.load(os.path.join(d, f))["points"].astype(np.float64)[:n]
    # view1 camera frame -> world, per frame
    Tw = np.linalg.inv(views["view1"]["T"])
    world = {k: np.einsum("tij,tnj->tni", Tw[:, :3, :3], p) + Tw[:, None, :3, 3] for k, p in parts.items()}
    return meta, names, views, world


def concat_clips(dirs):
    clips = [load_clip(d) for d in dirs]
    names = clips[0][1]
    views = {v: {k: clips[0][2][v][k] for k in ("K", "dist", "wh")} for v in names}
    for v in names:
        views[v]["T"] = np.concatenate([c[2][v]["T"] for c in clips])
        views[v]["rgb"] = np.concatenate([c[2][v]["rgb"] for c in clips])
    keys = list(clips[0][3])
    world = {k: np.concatenate([c[3][k] for c in clips]) for k in keys if all(k in c[3] for c in clips)}
    return clips[0][0], names, views, world


def farthest(X, k):
    if k >= len(X):
        return np.arange(len(X))
    sel = [int(np.argmin(np.linalg.norm(X - X.mean(0), axis=1)))]
    dmin = np.linalg.norm(X - X[sel[0]], axis=1)
    for _ in range(k - 1):
        sel.append(int(np.argmax(dmin)))
        dmin = np.minimum(dmin, np.linalg.norm(X - X[sel[-1]], axis=1))
    return np.sort(np.asarray(sel))


def gradient_colors(X, cmap, lo, hi):
    import matplotlib

    Xc = X - X.mean(0)
    _, _, Vt = np.linalg.svd(Xc, full_matrices=False)
    p = Xc @ Vt[:2].T
    a = (p[:, 0] - p[:, 0].min()) / max(np.ptp(p[:, 0]), 1e-9)
    b = (p[:, 1] - p[:, 1].min()) / max(np.ptp(p[:, 1]), 1e-9)
    rgb = matplotlib.colormaps[cmap](lo + (hi - lo) * a)[:, :3] * (0.85 + 0.15 * b)[:, None]
    return np.clip(rgb, 0, 1)


OBJECT_CMAPS = [("spring", 0.0, 0.55), ("cool", 0.35, 1.0), ("Wistia", 0.2, 1.0), ("PuRd", 0.45, 0.95)]


def select_points(world, targets, n_body, n_object):
    """Farthest-point subsampling on the frame-0 shape: arm and gripper together (even spacing over the
    whole robot), then each object; fixed colour per point."""
    pts, cols, is_obj = [], [], []
    body = [world[k] for k in ("robot", "gripper") if k in world]
    if body:
        B = np.concatenate(body, 1)
        B = B[:, farthest(B[0], n_body)]
        pts.append(B)
        cols.append(gradient_colors(B[0], "turbo", 0.08, 0.92))
        is_obj.append(np.zeros(B.shape[1], bool))
    objs = []
    for k in sorted(k for k in world if k.startswith("object")):
        O = world[k]
        sizes = targets.get(k)
        if sizes and sum(sizes) == O.shape[1] and len(sizes) > 1:  # several targets packed in one file
            objs += np.split(O, np.cumsum(sizes)[:-1], axis=1)
        else:
            objs.append(O)
    for i, O in enumerate(objs):
        O = O[:, farthest(O[0], n_object)]
        cm, lo, hi = OBJECT_CMAPS[i % len(OBJECT_CMAPS)]
        pts.append(O)
        cols.append(gradient_colors(O[0], cm, lo, hi))
        is_obj.append(np.ones(O.shape[1], bool))
    return np.concatenate(pts, 1), (np.concatenate(cols) * 255).astype(np.uint8), np.concatenate(is_obj)


def project(view, Xw, scale):
    """[T,N,3] world -> uv [T,N,2] output pixels, depth [T,N], valid [T,N]."""
    T = view["T"]
    Xc = np.einsum("tij,tnj->tni", T[:, :3, :3], Xw) + T[:, None, :3, 3]
    z = Xc[..., 2]
    w, h = view["wh"]
    K = view["K"]
    uv = np.zeros(Xc.shape[:2] + (2,))
    ok = z > 0.05
    x = Xc[..., 0] / np.where(ok, z, 1)
    y = Xc[..., 1] / np.where(ok, z, 1)
    u0, v0 = K[0, 0] * x + K[0, 2], K[1, 1] * y + K[1, 2]
    ok &= (u0 > -0.1 * w) & (u0 < 1.1 * w) & (v0 > -0.1 * h) & (v0 < 1.1 * h)  # trust distortion only near the image
    if np.any(view["dist"]):
        sel = np.nonzero(ok)
        p, _ = cv2.projectPoints(Xc[sel].reshape(-1, 1, 3), np.zeros(3), np.zeros(3), K, view["dist"])
        uv[sel] = p.reshape(-1, 2)
    else:
        uv[..., 0], uv[..., 1] = u0, v0
    uv = (uv + 0.5) * scale - 0.5
    return uv, z, ok


def draw(frame, uv, z, ok, cols, is_obj, t, tail, base_r):
    H, W = frame.shape[:2]
    h, w = H * SS, W * SS
    rgb = np.zeros((h, w, 3), np.uint8)
    a = np.zeros((h, w), np.uint8)
    P = uv * SS
    inside = ok & (uv[..., 0] >= -2) & (uv[..., 0] < W + 2) & (uv[..., 1] >= -2) & (uv[..., 1] < H + 2)
    zt = z[t][inside[t]]
    zref = np.median(zt) if len(zt) else 1.0
    rad = np.clip(base_r * zref / np.maximum(z, 1e-3), 0.65 * base_r, 1.6 * base_r)
    rad = np.where(is_obj[None], rad * 1.15, rad)
    near = np.clip((zref - z) / max(0.25 * zref, 1e-3), -1, 1)  # >0 nearer than the median
    shade = 0.82 + 0.18 * near
    # trails: oldest segment first
    for k in range(tail, 0, -1):
        t0, t1 = t - k, t - k + 1
        if t0 < 0:
            continue
        f = 1 - (k - 1) / tail
        al = int(255 * (0.05 + 0.55 * f ** 1.5))
        seg = np.nonzero(inside[t0] & inside[t1])[0]
        for n in seg:
            th = max(1, int(round(SS * rad[t1, n] * (0.25 + 0.45 * f))))
            p0 = tuple(int(round(c * 16)) for c in P[t0, n])
            p1 = tuple(int(round(c * 16)) for c in P[t1, n])
            c = tuple(int(x) for x in cols[n] * shade[t1, n])
            cv2.line(rgb, p0, p1, c, th, cv2.LINE_AA, shift=4)
            cv2.line(a, p0, p1, al, th, cv2.LINE_AA, shift=4)
    # dots: far first, near on top; rim (dark on the robot, white on objects), colour body, highlight
    order = np.argsort(-z[t])
    for n in order:
        if not inside[t, n]:
            continue
        cen = tuple(int(round(c * 16)) for c in P[t, n])
        r = rad[t, n] * SS
        col = cols[n].astype(np.float32) * shade[t, n]
        rim = (255, 255, 255) if is_obj[n] else tuple(int(x) for x in col * 0.35)
        cv2.circle(rgb, cen, int(round((r + 0.9 * SS) * 16)), rim, -1, cv2.LINE_AA, shift=4)
        cv2.circle(a, cen, int(round((r + 0.9 * SS) * 16)), 235, -1, cv2.LINE_AA, shift=4)
        cv2.circle(rgb, cen, int(round(r * 16)), tuple(int(x) for x in col), -1, cv2.LINE_AA, shift=4)
        hl = tuple(int(round((c - 0.3 * r) * 16)) for c in P[t, n])
        hcol = tuple(int(min(255, x * 0.55 + 255 * 0.45)) for x in col)
        cv2.circle(rgb, hl, int(round(0.38 * r * 16)), hcol, -1, cv2.LINE_AA, shift=4)
    af = a.astype(np.float32) / 255.0
    pre = rgb.astype(np.float32) / 255.0 * af[..., None]
    pre = cv2.resize(pre, (W, H), interpolation=cv2.INTER_AREA)
    af = cv2.resize(af, (W, H), interpolation=cv2.INTER_AREA)
    return np.clip(frame.astype(np.float32) * (1 - af[..., None]) + pre * 255.0, 0, 255).round().astype(np.uint8)


class Writer:
    def __init__(self, path, w, h, fps, crf):
        import av

        self.c = av.open(path, "w", options={"movflags": "+faststart"})
        self.s = self.c.add_stream("libx264", rate=int(fps))
        self.s.width, self.s.height, self.s.pix_fmt = w, h, "yuv420p"
        self.s.options = {"crf": str(crf), "preset": "slow", "threads": "8"}

    def write(self, frame):
        import av

        for p in self.s.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(frame), format="rgb24")):
            self.c.mux(p)

    def close(self):
        for p in self.s.encode():
            self.c.mux(p)
        self.c.close()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("clips", nargs="+")
    ap.add_argument("--out", required=True)
    ap.add_argument("--height", type=int, default=384, help="height of each view in the output")
    ap.add_argument("--n-body", type=int, default=128, help="points on arm + gripper")
    ap.add_argument("--n-object", type=int, default=40)
    ap.add_argument("--tail", type=int, default=10)
    ap.add_argument("--radius", type=float, default=0.011, help="dot radius as a fraction of the view height")
    ap.add_argument("--views", default=None, help="comma-separated subset/order of views")
    ap.add_argument("--gap", type=int, default=4, help="white gap between views (px)")
    ap.add_argument("--crf", type=int, default=20)
    ap.add_argument("--poster", default=None, help="PNG of frame --poster-frame")
    ap.add_argument("--poster-frame", type=float, default=0.5, help="fraction of the video")
    args = ap.parse_args()

    meta, names, views, world = concat_clips(args.clips)
    if args.views:
        names = args.views.split(",")
    obj = meta.get("object") if isinstance(meta.get("object"), dict) else {}
    targets = {"object": [t["n_points"] for t in obj.get("targets", []) if "n_points" in t]}
    Xw, cols, is_obj = select_points(world, targets, args.n_body, args.n_object)
    n_t = Xw.shape[0]
    tiles = []
    for v in names:
        vw = views[v]
        h0, w0 = vw["rgb"].shape[1:3]
        s = args.height / h0
        W = int(round(w0 * s / 2)) * 2
        uv, z, ok = project(vw, Xw, np.array([W / w0, args.height / h0]))
        if (w0, h0) != tuple(vw["wh"]):
            raise ValueError(f"{v}: video {w0}x{h0} != intrinsics {vw['wh']}")
        T = vw["T"]
        centers = -np.einsum("tji,tj->ti", T[:, :3, :3], T[:, :3, 3])
        moving = np.linalg.norm(centers - centers[0], axis=1).max() > 0.01
        tiles.append(dict(v=v, W=W, uv=uv, z=z, ok=ok, tail=0 if moving else args.tail))
    width = sum(t["W"] for t in tiles) + args.gap * (len(tiles) - 1)
    width += width % 2
    fps = meta.get("fps", 15)
    wr = Writer(args.out, width, args.height, fps, args.crf)
    poster_t = int(args.poster_frame * (n_t - 1))
    for t in range(n_t):
        row = []
        for i, tl in enumerate(tiles):
            fr = cv2.resize(views[tl["v"]]["rgb"][t], (tl["W"], args.height), interpolation=cv2.INTER_LANCZOS4
                            if tl["W"] > views[tl["v"]]["rgb"].shape[2] else cv2.INTER_AREA)
            row.append(draw(fr, tl["uv"], tl["z"], tl["ok"], cols, is_obj, t, tl["tail"], args.radius * args.height))
            if i < len(tiles) - 1:
                row.append(np.full((args.height, args.gap, 3), 255, np.uint8))
        canvas = np.concatenate(row, 1)
        if canvas.shape[1] < width:
            canvas = np.pad(canvas, ((0, 0), (0, width - canvas.shape[1]), (0, 0)), constant_values=255)
        wr.write(canvas)
        if args.poster and t == poster_t:
            cv2.imwrite(args.poster, canvas[..., ::-1])
    wr.close()
    print(f"{args.out}: {len(tiles)} views, {Xw.shape[1]} points ({int(is_obj.sum())} on objects), {n_t} frames @ {fps} fps, {width}x{args.height}")


if __name__ == "__main__":
    main()