PWM / PWM_code /reward_model /scripts /archive /visualize_3pointr_episode.py
hchen657Naza's picture
Add files using upload-large-folder tool
23e1f91 verified
Raw History Blame Contribute Delete
3.21 kB
"""Project 3D pos[k] back to image (using stored intrinsics) and overlay
on the saved RGB frames. Sanity check that the 3D lift is geometrically consistent."""
import argparse, os, json
import numpy as np
import torch
import cv2
import imageio
def load_episode(ep_dir):
meta = json.load(open(os.path.join(ep_dir, "metadata.json")))
T = meta["T"]
pos = []; vis = []; rgbs = []
for k in range(1, T + 1):
ts = os.path.join(ep_dir, f"timestep_{k}")
pos.append(torch.load(os.path.join(ts, f"{k}_pos.pth")).numpy())
vis.append(torch.load(os.path.join(ts, f"{k}_visibility.pth")).numpy())
rgbs.append(imageio.imread(os.path.join(ts, f"{k}_rgb.png")))
pos = np.stack(pos, axis=0)
vis = np.stack(vis, axis=0)
K = meta["intrinsics"]
if "camera" in K:
K = K["camera"]
fx, fy, cx, cy = K["fx"], K["fy"], K["cx"], K["cy"]
return rgbs, pos, vis, (fx, fy, cx, cy), meta
def project(pos_xyz, fx, fy, cx, cy):
z = np.maximum(pos_xyz[..., 2], 1e-6)
u = pos_xyz[..., 0] / z * fx + cx
v = pos_xyz[..., 1] / z * fy + cy
return np.stack([u, v], axis=-1)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ep_dir", required=True)
ap.add_argument("--out_video", required=True)
ap.add_argument("--stride", type=int, default=4)
args = ap.parse_args()
rgbs, pos, vis, (fx, fy, cx, cy), meta = load_episode(args.ep_dir)
print(f"Loaded {meta['T']} frames, N={meta['N']}, src={meta['source_video']}")
print(f" intrinsics fx={fx:.1f} fy={fy:.1f} cx={cx:.1f} cy={cy:.1f}")
rng = np.random.default_rng(0)
colors = (rng.uniform(0, 255, (pos.shape[1], 3))).astype(np.uint8)
proj_uv = project(pos, fx, fy, cx, cy)
out = []
for t, frame in enumerate(rgbs):
img = frame.copy()
H, W = img.shape[:2]
for n in range(0, pos.shape[1], args.stride):
u, v = proj_uv[t, n]
if not vis[t, n]: continue
if not (0 <= u < W and 0 <= v < H): continue
col = tuple(int(c) for c in colors[n])
cv2.circle(img, (int(u), int(v)), 4, col, -1, cv2.LINE_AA)
cv2.circle(img, (int(u), int(v)), 4, (0,0,0), 1, cv2.LINE_AA)
# Trail (last K frames)
K_trail = 10
t0 = max(0, t - K_trail)
for n in range(0, pos.shape[1], args.stride):
for ti in range(t0 + 1, t + 1):
if not (vis[ti, n] and vis[ti-1, n]): continue
p1 = proj_uv[ti-1, n]; p2 = proj_uv[ti, n]
if not (0 <= p1[0] < W and 0 <= p1[1] < H and 0 <= p2[0] < W and 0 <= p2[1] < H): continue
col = tuple(int(c) for c in colors[n])
cv2.line(img, (int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])), col, 1, cv2.LINE_AA)
cv2.putText(img, f"t={t}, vis={int(vis[t].sum())}/{vis.shape[1]}", (16, 32),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2, cv2.LINE_AA)
out.append(img)
os.makedirs(os.path.dirname(args.out_video) or '.', exist_ok=True)
imageio.mimwrite(args.out_video, out, fps=15, macro_block_size=1)
print(f"saved {args.out_video}")
if __name__ == "__main__":
main()