Download tools/render_demo.py from rooty2020/LIBERO-VP: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/datasets/rooty2020/LIBERO-VP/resolve/main/tools/render_demo.py
- Command line
-
hf download hf://datasets/rooty2020/LIBERO-VP/tools/render_demo.py
-
curl -L -o render_demo.py https://huggingface.co/datasets/rooty2020/LIBERO-VP/resolve/main/tools/render_demo.py
12 kB
| """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() | |