v2d / reconstruction /scripts /viz_object_motion.py
hk239's picture
Upload v2d project (excluding data and .venv) (part 12)
c1a4584 verified
Raw History Blame Contribute Delete
13.4 kB
#!/usr/bin/env python3
"""Render one overlay video: tracked 3D object + HaWoR hands on the RGB clip.
Uses the optimized camera-frame layout when present (hand-anchored scale),
otherwise the combined layout from Fast-SAM3D.
python viz_object_motion.py --video-dir /path/to/runs/<seq>
Writes: <video-dir>/obj_tracking_out/<object>/object_motion.mp4
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import cv2
import numpy as np
import torch
from scipy.spatial.transform import Rotation as R
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.structures import Meshes
from pytorch3d.renderer import TexturesVertex
from run_project_mesh_combined import (
DirectoryVideoReader,
_parse_rgb,
make_renderer,
read_video_frame,
render_combined,
render_mesh,
transform_to_camera_frame,
)
def parse_args():
p = argparse.ArgumentParser(
description="One MP4 of 3D object + hand motion overlaid on the demo video.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
p.add_argument("--video-dir", required=True, help="Pipeline run directory")
p.add_argument("--object", default=None, help="Object id (default: config.json)")
p.add_argument("--video", default=None, help="RGB source (mp4 or all_frames/). Default: clip.mp4")
p.add_argument("--mesh", default=None, help="Object .obj (default: SAM-3D mesh on ref frame)")
p.add_argument("--json", default=None, help="Layout JSON (prefers optimized camera-frame)")
p.add_argument("--hand-meshes", default=None, help="HaWoR all_hand_meshes.npz")
p.add_argument(
"--hands",
default="auto",
choices=["auto", "left", "right", "both", "none"],
help="Hands to overlay. auto = config.json anchor_hand (one side). "
"both also drops near-camera ghost meshes (unused HaWoR side).",
)
p.add_argument("--output", default=None, help="Output mp4 path")
p.add_argument("--fps", type=float, default=30.0)
p.add_argument(
"--object-color",
default="0.15,0.85,0.45",
help="Solid overlay RGB in 0-1 as r,g,b",
)
p.add_argument("--left-hand-color", default="0.95,0.35,0.35")
p.add_argument("--right-hand-color", default="0.35,0.45,0.95")
p.add_argument(
"--alpha",
type=float,
default=0.72,
help="Mesh overlay opacity on the video",
)
p.add_argument("--device", default="auto", choices=["auto", "cpu", "cuda"])
return p.parse_args()
def _object_id(video_dir, explicit):
if explicit:
return explicit.replace(" ", "_")
cfg = os.path.join(video_dir, "config.json")
if os.path.isfile(cfg):
with open(cfg) as f:
names = json.load(f).get("object_names") or []
if names:
return str(names[0]).replace(" ", "_")
print("[error] pass --object or put object_names in config.json")
sys.exit(1)
def _ref_frame(video_dir):
cfg = os.path.join(video_dir, "config.json")
if os.path.isfile(cfg):
with open(cfg) as f:
return int(json.load(f).get("frame_number", 0))
return 0
def _anchor_hand(video_dir):
cfg = os.path.join(video_dir, "config.json")
if os.path.isfile(cfg):
with open(cfg) as f:
h = json.load(f).get("anchor_hand")
if h in ("left", "right"):
return h
return "right"
def _layout_json(video_dir, obj_id, explicit):
if explicit:
return explicit
root = os.path.join(video_dir, "obj_tracking_out", obj_id, "combined_visualization")
for name in (
"layout_camera_frame_optimized.json",
"layout_camera_frame.json",
"layout.json",
):
path = os.path.join(root, name)
if os.path.isfile(path):
return path
print(f"[error] no layout JSON under {root}")
sys.exit(1)
def _mesh_path(video_dir, obj_id, explicit):
if explicit:
return explicit
n = _ref_frame(video_dir)
path = os.path.join(
video_dir,
"video_segmentation",
"masks",
f"frame_{n:06d}_masks",
obj_id,
f"{obj_id}.obj",
)
return path
def _rgb_source(video_dir, explicit):
if explicit:
return explicit
clip = os.path.join(video_dir, "clip.mp4")
frames = os.path.join(video_dir, "all_frames")
if os.path.isfile(clip):
return clip
if os.path.isdir(frames):
return frames
print("[error] need clip.mp4 or all_frames/ (or pass --video)")
sys.exit(1)
def _hand_meshes_npz(video_dir, explicit):
if explicit:
return explicit
clip = os.path.join(video_dir, "clip", "all_hand_meshes.npz")
if os.path.isfile(clip):
return clip
try:
for name in os.listdir(video_dir):
path = os.path.join(video_dir, name, "all_hand_meshes.npz")
if os.path.isfile(path):
return path
except FileNotFoundError:
pass
return None
def _hand_valid(hand_data, hand, frame_idx):
key = f"{hand}_valid"
if key not in hand_data.files:
return True
v = np.asarray(hand_data[key])
if frame_idx >= v.shape[0]:
return False
val = np.asarray(v[frame_idx]).reshape(-1)
if val.size == 0:
return True
return bool(val.flat[0])
def _hand_depth_ok(verts, min_median_z=0.15):
"""Skip unused HaWoR side: infiller parks that mesh at the camera (z~0)."""
z = np.asarray(verts)[:, 2]
if not np.isfinite(z).all():
return False
return float(np.median(z)) >= min_median_z
def main():
args = parse_args()
video_dir = os.path.abspath(args.video_dir)
obj_id = _object_id(video_dir, args.object)
layout_path = _layout_json(video_dir, obj_id, args.json)
mesh_path = _mesh_path(video_dir, obj_id, args.mesh)
video_path = _rgb_source(video_dir, args.video)
out_path = args.output or os.path.join(
video_dir, "obj_tracking_out", obj_id, "object_motion.mp4"
)
if args.device == "auto":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
else:
device = torch.device(args.device)
print(f"device: {device}", flush=True)
print(f"layout: {layout_path}", flush=True)
print(f"mesh: {mesh_path}", flush=True)
print(f"video: {video_path}", flush=True)
print(f"output: {out_path}", flush=True)
hand_npz = None if args.hands == "none" else _hand_meshes_npz(video_dir, args.hand_meshes)
hand_data = None
hands_to_render = []
if args.hands != "none":
if not hand_npz or not os.path.isfile(hand_npz):
print("[error] HaWoR all_hand_meshes.npz not found (pass --hand-meshes or --hands none)")
sys.exit(1)
hand_data = np.load(hand_npz)
if args.hands == "auto":
hands_to_render = [_anchor_hand(video_dir)]
elif args.hands == "both":
hands_to_render = ["left", "right"]
else:
hands_to_render = [args.hands]
print(f"hands: {hand_npz} ({', '.join(hands_to_render)})", flush=True)
hand_colors = {
"left": _parse_rgb(args.left_hand_color),
"right": _parse_rgb(args.right_hand_color),
}
with open(layout_path) as f:
data = json.load(f)
objects = [o for o in data.get("objects", []) if "frame_idx" in o]
objects.sort(key=lambda o: o["frame_idx"])
if not objects:
print("[error] layout has no frame_idx objects")
sys.exit(1)
fallback_intr = None
for obj in objects:
if "intrinsics_normalized" in obj:
fallback_intr = obj["intrinsics_normalized"]
break
if fallback_intr is None:
print("[error] layout has no intrinsics_normalized")
sys.exit(1)
is_camera_frame = data.get("frame") == "camera_frame"
override_scale = None
tso = data.get("translation_scale_optimization") or {}
if is_camera_frame and "mesh_scale" in tso:
override_scale = float(tso["mesh_scale"])
print(f"using optimized mesh_scale={override_scale:.6f}")
if not os.path.isfile(mesh_path):
print(f"[error] mesh not found: {mesh_path}")
sys.exit(1)
mesh = load_objs_as_meshes([mesh_path], device=device)
rgb = _parse_rgb(args.object_color)
verts_list = mesh.verts_list()
faces_list = mesh.faces_list()
n_verts = verts_list[0].shape[0]
color_t = torch.tensor(rgb, dtype=torch.float32, device=device)
mesh = Meshes(
verts=verts_list,
faces=faces_list,
textures=TexturesVertex(verts_features=color_t.expand(n_verts, 3).unsqueeze(0)),
)
if os.path.isdir(video_path):
frame_source = DirectoryVideoReader(video_path)
width, height = frame_source.width, frame_source.height
cap = None
else:
cap = cv2.VideoCapture(video_path)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_source = None
renderer_cache = {}
def get_renderer(intr, W, H):
fx = intr["fx_norm"] * W
fy = intr["fy_norm"] * H
cx = intr.get("cx_norm", 0.5) * W
cy = intr.get("cy_norm", 0.5) * H
key = (round(fx, 4), round(fy, 4), round(cx, 4), round(cy, 4), W, H)
if key not in renderer_cache:
renderer_cache[key] = make_renderer(fx, fy, cx, cy, W, H, device)
return renderer_cache[key]
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
tmp_avi = out_path + ".tmp.avi"
writer = cv2.VideoWriter(tmp_avi, fourcc, args.fps, (width, height))
if not writer.isOpened():
print("[error] could not open video writer")
sys.exit(1)
last_read_idx = -1
n_ok = 0
blend = float(np.clip(args.alpha, 0.0, 1.0))
for i, obj in enumerate(objects):
frame_idx = obj["frame_idx"]
lts = obj["local_to_scene"]
scale = override_scale if override_scale is not None else lts["scale"][0]
if is_camera_frame:
quat = lts["quat_wxyz_camera_frame"]
translation = list(lts["translation_camera_frame"])
else:
quat = lts["new_quat"]
tx, ty, tz = lts["translation"]
translation = [tz, tx, ty]
if frame_source is not None:
frame_rgb = frame_source.read_frame(frame_idx)
else:
frame_rgb, last_read_idx = read_video_frame(cap, frame_idx, last_read_idx)
if frame_rgb is None:
print(f" skip frame {frame_idx} (no RGB)")
continue
renderer = get_renderer(obj.get("intrinsics_normalized", fallback_intr), width, height)
quat_xyzw = np.array([quat[1], quat[2], quat[3], quat[0]])
rot_matrix = R.from_quat(quat_xyzw).as_matrix()
obj_verts_cam = transform_to_camera_frame(
mesh.verts_packed(), rot_matrix, translation, scale, device,
camera_frame=is_camera_frame,
)
meshes_data = [(obj_verts_cam, mesh.faces_packed(), rgb)]
n_hand_frames = None
if hand_data is not None:
n_hand_frames = int(hand_data["right_vertices"].shape[0])
if frame_idx < n_hand_frames:
for hand in hands_to_render:
verts_np = np.asarray(hand_data[f"{hand}_vertices"][frame_idx])
if not _hand_valid(hand_data, hand, frame_idx):
continue
if not _hand_depth_ok(verts_np):
continue
verts = torch.tensor(verts_np, dtype=torch.float32, device=device)
faces = torch.tensor(
hand_data[f"{hand}_faces"], dtype=torch.int64, device=device,
)
meshes_data.append((verts, faces, hand_colors[hand]))
if len(meshes_data) > 1:
render_rgb, render_alpha = render_combined(meshes_data, renderer, device)
else:
render_rgb, render_alpha = render_mesh(
mesh, rot_matrix, translation, scale, renderer, device,
camera_frame=is_camera_frame,
)
render_u8 = (render_rgb * 255).clip(0, 255).astype(np.uint8)
mask = render_alpha > 0.5
result = frame_rgb.copy()
result[mask] = (
(1.0 - blend) * result[mask].astype(np.float32)
+ blend * render_u8[mask].astype(np.float32)
).clip(0, 255).astype(np.uint8)
cv2.putText(
result,
f"frame {frame_idx}",
(12, 28),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(255, 255, 255),
2,
cv2.LINE_AA,
)
writer.write(cv2.cvtColor(result, cv2.COLOR_RGB2BGR))
n_ok += 1
if (i + 1) % 10 == 0 or i == 0:
print(f" [{i+1}/{len(objects)}] frame {frame_idx}", flush=True)
writer.release()
if cap is not None:
cap.release()
# Re-encode to H.264 for browsers / players.
import subprocess
cmd = [
"ffmpeg", "-y", "-i", tmp_avi,
"-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
out_path,
]
subprocess.run(cmd, check=True)
os.remove(tmp_avi)
print(f"Wrote {n_ok} frames -> {out_path}", flush=True)
if __name__ == "__main__":
main()