RoboCasa-VP / tools /visualize_sample.py
rooty2020's picture
Add files using upload-large-folder tool
855eff7 verified
Raw History Blame Contribute Delete
6.58 kB
#!/usr/bin/env python
"""Re-project the 3D point tracks of one sample onto every camera view.
Works for DROID-VP, LIBERO-VP and RoboCasa-VP samples, i.e. any directory that holds
`meta.json`, `view*.mp4` / `ego.mp4` and `robot.npz` / `gripper.npz` / `object*.npz`.
Only the calibration stored in `meta.json` is used, so the output is a direct check of
calibration <-> track consistency.
python visualize_sample.py <sample_dir> --out vis.mp4 [--frame-png vis.png]
Dependencies: numpy, opencv-python.
"""
import argparse
import glob
import json
import os
import sys
import cv2
import numpy as np
def view_order(name):
if name.startswith("view") and name[4:].isdigit():
return (0, int(name[4:]))
return (1, name)
def load_views(sample_dir, meta, max_views):
views = []
for name in sorted(meta["views"], key=view_order):
v = meta["views"][name]
path = os.path.join(sample_dir, f"{name}.mp4")
if not os.path.isfile(path):
continue
intr = v["intrinsics"]
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)
# per-frame extrinsics when the camera moves (RoboCasa mobile base, wrist cameras)
T = np.asarray(v.get("T_cam_world_perframe", v["T_cam_world"]), np.float64)
if T.ndim == 3 and len(T) != meta["n_frames"]:
# RoboCasa-VP subtask clips keep the parent episode's per-frame base-camera
# extrinsics; frame t of the clip is frame frame_range[0] + t of the episode
start = meta["subtask"]["frame_range"][0]
T = T[start:start + meta["n_frames"]]
views.append(dict(name=name, path=path, K=K, dist=dist, calib_wh=(intr["width"], intr["height"]), T=T))
return views[:max_views]
def load_tracks(sample_dir):
parts, is_obj = [], []
files = ["gripper.npz", "robot.npz"] + sorted(
os.path.basename(p) for p in glob.glob(os.path.join(sample_dir, "object*.npz")))
for f in files:
p = os.path.join(sample_dir, f)
if os.path.isfile(p):
pts = np.load(p)["points"].astype(np.float64)
parts.append(pts)
is_obj.append(np.full(pts.shape[1], f.startswith("object")))
if not parts:
sys.exit(f"no point-track npz in {sample_dir}")
return np.concatenate(parts, 1), np.concatenate(is_obj)
def frame_T(T, t):
return T if T.ndim == 2 else T[min(t, len(T) - 1)]
def project(pts_cam, K, dist, wh, margin=0.15):
"""Pinhole pre-check before applying the distortion polynomial, which folds far
out-of-view points back into the image."""
w, h = wh
z = pts_cam[:, 2]
valid = z > 1e-6
uv = np.zeros((len(pts_cam), 2))
if not valid.any():
return uv, valid
xy = pts_cam[valid, :2] / z[valid, None]
u0 = xy[:, 0] * K[0, 0] + K[0, 2]
v0 = xy[:, 1] * K[1, 1] + K[1, 2]
in_fov = (u0 > -margin * w) & (u0 < (1 + margin) * w) & (v0 > -margin * h) & (v0 < (1 + margin) * h)
idx = np.flatnonzero(valid)
valid[idx[~in_fov]] = False
if valid.any():
p, _ = cv2.projectPoints(pts_cam[valid].reshape(-1, 1, 3), np.zeros(3), np.zeros(3), K, dist)
uv[valid] = p.reshape(-1, 2)
return uv, valid
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("sample_dir")
ap.add_argument("--out", default="vis.mp4")
ap.add_argument("--height", type=int, default=360, help="per-view height of the output")
ap.add_argument("--max-views", type=int, default=3)
ap.add_argument("--frame-png", default=None, help="also save the middle frame as a PNG")
args = ap.parse_args()
with open(os.path.join(args.sample_dir, "meta.json")) as f:
meta = json.load(f)
assert meta.get("extrinsics_convention", "cam_from_world") == "cam_from_world"
views = load_views(args.sample_dir, meta, args.max_views)
v1 = next((v for v in views if v["name"] == "view1"), None)
if v1 is None:
sys.exit("view1 (the reference frame of the tracks) is missing")
pts_v1, is_obj = load_tracks(args.sample_dir) # (T, N, 3) in the view1 camera frame
n_t, n_pts = pts_v1.shape[:2]
# view1 camera frame -> world, per frame
pts_w = np.empty_like(pts_v1)
for t in range(n_t):
iv = np.linalg.inv(frame_T(v1["T"], t))
pts_w[t] = pts_v1[t] @ iv[:3, :3].T + iv[:3, 3]
hues = (np.arange(n_pts) / max(n_pts, 1) * 179).astype(np.uint8)
hsv = np.stack([hues, np.full(n_pts, 255, np.uint8), np.full(n_pts, 255, np.uint8)], 1)
colors = cv2.cvtColor(hsv[None], cv2.COLOR_HSV2BGR)[0]
caps = [cv2.VideoCapture(v["path"]) for v in views]
for v, c in zip(views, caps):
w, h = int(c.get(cv2.CAP_PROP_FRAME_WIDTH)), int(c.get(cv2.CAP_PROP_FRAME_HEIGHT))
cw, ch = v["calib_wh"]
if (w, h) != (cw, ch): # intrinsics refer to calib_wh; rescale to the stored video size
v["K"] = np.diag([w / cw, h / ch, 1.0]) @ v["K"]
v["wh"], v["out_w"] = (w, h), int(round(w * args.height / h))
fps = float(meta.get("fps", 15))
writer = cv2.VideoWriter(args.out, cv2.VideoWriter_fourcc(*"mp4v"), fps,
(sum(v["out_w"] for v in views), args.height))
t = 0
while t < n_t:
frames = [c.read()[1] for c in caps]
if any(f is None for f in frames):
break
row = []
for v, fr in zip(views, frames):
T = frame_T(v["T"], t)
uv, valid = project(pts_w[t] @ T[:3, :3].T + T[:3, 3], v["K"], v["dist"], v["wh"])
w, h = v["wh"]
r = max(2, w // 400)
for i in np.flatnonzero(valid):
x, y = int(round(uv[i, 0])), int(round(uv[i, 1]))
if 0 <= x < w and 0 <= y < h:
col = tuple(int(c) for c in colors[i])
cv2.circle(fr, (x, y), r + 2 if is_obj[i] else r, col, -1, lineType=cv2.LINE_AA)
if is_obj[i]:
cv2.circle(fr, (x, y), r + 2, (255, 255, 255), 1, lineType=cv2.LINE_AA)
row.append(cv2.resize(fr, (v["out_w"], args.height)))
canvas = np.hstack(row)
writer.write(canvas)
if args.frame_png and t == n_t // 2:
cv2.imwrite(args.frame_png, canvas)
t += 1
writer.release()
print(f"{args.sample_dir}: {[v['name'] for v in views]}, tracks {pts_v1.shape}, {t} frames -> {args.out}")
if __name__ == "__main__":
main()