| """ |
| ARCTIC Hand Data Reader |
| Only reads hand (MANO) parameters from raw_seqs. |
| No body model forward pass, no object data, no splits needed. |
| Usage: |
| python scripts_data/hand_reader.py |
| python scripts_data/hand_reader.py --mano_p ./data/raw_seqs/s01/box_grab_01.mano.npy |
| python scripts_data/hand_reader.py --mano_p ./data/raw_seqs/s01/box_grab_01.mano.npy --frame 10 |
| """ |
|
|
| import argparse |
| import json |
| import os.path as op |
| import sys |
| from glob import glob |
|
|
| import numpy as np |
| import torch |
|
|
| sys.path = ["."] + sys.path |
|
|
| DATA_ROOT = "./data" |
|
|
| |
| |
| |
| VIEW_NAMES = ["ego", "allo_1", "allo_2", "allo_3", "allo_4", |
| "allo_5", "allo_6", "allo_7", "allo_8"] |
|
|
|
|
| def load_hand_seq(mano_p): |
| """ |
| Load one sequence. Mirrors construct_loader() in |
| src/arctic/preprocess_dataset.py but keeps only hand fields. |
| Returns a dict with: |
| right / left -> MANO params (tensors) |
| ego_cam -> per-frame ego camera (world2ego, K, dist8) |
| static_cams -> 8 fixed allo cameras from misc.json (world2cam, K) |
| meta -> sid, seq_name, num_frames, gender |
| """ |
| |
| data = np.load(mano_p, allow_pickle=True).item() |
| num_frames = len(data["right"]["rot"]) |
|
|
| def _load_hand(side): |
| return { |
| |
| "rot": torch.FloatTensor(data[side]["rot"]), |
| |
| |
| "pose": torch.FloatTensor(data[side]["pose"]), |
| |
| |
| "trans": torch.FloatTensor(data[side]["trans"]), |
| |
| |
| "shape": torch.FloatTensor(data[side]["shape"]).repeat(num_frames, 1), |
| |
| |
| "fitting_err": data[side]["fitting_err"], |
| } |
|
|
| right = _load_hand("right") |
| left = _load_hand("left") |
|
|
| |
| assert len(right["fitting_err"]) > 50, f"Too few frames: {mano_p}" |
|
|
| |
| ego_p = mano_p.replace("mano.npy", "egocam.dist.npy") |
| egocam = np.load(ego_p, allow_pickle=True).item() |
| |
| |
| R_ego = torch.FloatTensor(egocam["R_k_cam_np"]) |
| |
| |
| T_ego = torch.FloatTensor(egocam["T_k_cam_np"]) |
| |
| |
| K_ego = torch.FloatTensor(egocam["intrinsics"]) |
| |
| dist8 = torch.FloatTensor(egocam["dist8"]) |
|
|
| |
| world2ego = torch.zeros((num_frames, 4, 4)) |
| world2ego[:, :3, :3] = R_ego |
| world2ego[:, :3, 3] = T_ego[:, :, 0] |
| world2ego[:, 3, 3] = 1.0 |
|
|
| |
| sid = op.basename(op.dirname(mano_p)) |
| misc_p = op.join(DATA_ROOT, "meta", "misc.json") |
| with open(misc_p) as f: |
| misc = json.load(f) |
|
|
| sub = misc[sid] |
| world2cam = torch.FloatTensor(np.array(sub["world2cam"])) |
| allo_K = torch.FloatTensor(np.array(sub["intris_mat"])) |
| image_size = np.array(sub["image_size"]) |
|
|
| seq_name = op.basename(mano_p).replace(".mano.npy", "") |
|
|
| return { |
| "right": right, |
| "left": left, |
| "ego_cam": { |
| "world2ego": world2ego, |
| "K": K_ego, |
| "dist8": dist8, |
| }, |
| "static_cams": { |
| "world2cam": world2cam, |
| "K": allo_K, |
| "image_size": image_size, |
| }, |
| "meta": { |
| "sid": sid, |
| "seq_name": seq_name, |
| "num_frames": num_frames, |
| "gender": sub["gender"], |
| }, |
| } |
|
|
|
|
| def get_frame(seq_data, idx): |
| """Return data for a single frame (0-indexed).""" |
| n = seq_data["meta"]["num_frames"] |
| assert 0 <= idx < n, f"Frame {idx} out of range (0-{n-1})" |
|
|
| def _frame_hand(h): |
| return {k: (v[idx] if isinstance(v, torch.Tensor) else v[idx]) |
| for k, v in h.items()} |
|
|
| frame = { |
| "right": _frame_hand(seq_data["right"]), |
| "left": _frame_hand(seq_data["left"]), |
| "world2ego": seq_data["ego_cam"]["world2ego"][idx], |
| "K_ego": seq_data["ego_cam"]["K"], |
| "dist8": seq_data["ego_cam"]["dist8"], |
| "static_cams": seq_data["static_cams"], |
| } |
|
|
| |
| img_dir = op.join(DATA_ROOT, "cropped_images", |
| seq_data["meta"]["sid"], seq_data["meta"]["seq_name"]) |
| if op.exists(img_dir): |
| fname = f"{idx + 1:05d}.jpg" |
| frame["images"] = { |
| name: p for name, view_id in zip(VIEW_NAMES, range(9)) |
| if op.exists(p := op.join(img_dir, str(view_id), fname)) |
| } |
|
|
| return frame |
|
|
|
|
| |
| |
| |
|
|
| def print_summary(seq_data): |
| m = seq_data["meta"] |
| print(f"\n=== Sequence: {m['sid']}/{m['seq_name']} ===") |
| print(f"Frames : {m['num_frames']}") |
| print(f"Subject: {m['sid']} gender={m['gender']}") |
| print(f"\nRight hand shape (10,): {seq_data['right']['shape'][0].numpy()}") |
| print(f"Left hand shape (10,): {seq_data['left']['shape'][0].numpy()}") |
| print(f"\nEgo cam K (3x3):\n{seq_data['ego_cam']['K'].numpy()}") |
| print(f"Ego cam dist8: {seq_data['ego_cam']['dist8'].numpy()}") |
| print(f"\nAllo cams: {seq_data['static_cams']['world2cam'].shape[0]}") |
| print(f"Image sizes (w x h):\n{seq_data['static_cams']['image_size']}") |
|
|
|
|
| def print_frame(frame, idx): |
| print(f"\n--- Frame {idx} ---") |
| for side in ["right", "left"]: |
| h = frame[side] |
| print(f"\n[{side} hand]") |
| print(f" rot (3,) : {h['rot'].numpy()}") |
| print(f" trans (3,) : {h['trans'].numpy()}") |
| print(f" pose (45,) first 6: {h['pose'].numpy()[:6]}") |
| print(f" shape (10,) : {h['shape'].numpy()}") |
| print(f" fitting_err : {h['fitting_err']:.4f}") |
| print(f"\n[Ego world2ego row 0-1]:\n{frame['world2ego'].numpy()[:2]}") |
| if "images" in frame: |
| print(f"\n[Available images]") |
| for view, path in frame["images"].items(): |
| print(f" {view:8s}: {path}") |
|
|
|
|
| def project_point(pt_world, world2cam, K): |
| """Project a 3D world point to 2D image coords via a camera.""" |
| pt_h = np.array([*pt_world, 1.0], dtype=np.float32) |
| pt_cam = (world2cam @ pt_h)[:3] |
| if pt_cam[2] <= 0: |
| return None |
| x = K[0, 0] * pt_cam[0] / pt_cam[2] + K[0, 2] |
| y = K[1, 1] * pt_cam[1] / pt_cam[2] + K[1, 2] |
| return (float(x), float(y)) |
|
|
|
|
| def visualize_wrists(frame, idx, seq_data): |
| """ |
| For each allo camera that has a cropped image, overlay the projected |
| right (red) and left (blue) wrist positions on the image. |
| """ |
| import matplotlib.pyplot as plt |
| import matplotlib.image as mpimg |
| import matplotlib.patches as mpatches |
|
|
| if "images" not in frame: |
| print("No cropped images found — run unzip first.") |
| return |
|
|
| world2cam = seq_data["static_cams"]["world2cam"].numpy() |
| K_allo = seq_data["static_cams"]["K"].numpy() |
|
|
| trans_r = frame["right"]["trans"].numpy() |
| trans_l = frame["left"]["trans"].numpy() |
|
|
| |
| allo_items = [(name, path) for name, path in frame["images"].items() |
| if name.startswith("allo")] |
|
|
| if not allo_items: |
| print("No allo images found for this frame.") |
| return |
|
|
| ncols = len(allo_items) |
| fig, axes = plt.subplots(1, ncols, figsize=(5 * ncols, 5)) |
| if ncols == 1: |
| axes = [axes] |
|
|
| for ax, (view_name, img_path) in zip(axes, allo_items): |
| cam_idx = int(view_name.split("_")[1]) - 1 |
| W2C = world2cam[cam_idx] |
| K = K_allo[cam_idx] |
|
|
| img = mpimg.imread(img_path) |
| crop_h, crop_w = img.shape[:2] |
|
|
| |
| pt_r = project_point(trans_r, W2C, K) |
| pt_l = project_point(trans_l, W2C, K) |
|
|
| |
| |
| if pt_r is not None and pt_l is not None: |
| crop_cx = (pt_r[0] + pt_l[0]) / 2 |
| crop_cy = (pt_r[1] + pt_l[1]) / 2 |
| elif pt_r is not None: |
| crop_cx, crop_cy = pt_r |
| elif pt_l is not None: |
| crop_cx, crop_cy = pt_l |
| else: |
| ax.imshow(img) |
| ax.set_title(f"{view_name} frame {idx}") |
| ax.axis("off") |
| continue |
|
|
| |
| extent = [crop_cx - crop_w / 2, crop_cx + crop_w / 2, |
| crop_cy + crop_h / 2, crop_cy - crop_h / 2] |
| ax.imshow(img, extent=extent, aspect="auto") |
| ax.set_title(f"{view_name} frame {idx}") |
| ax.axis("off") |
|
|
| for pt, color in [(pt_r, "red"), (pt_l, "blue")]: |
| if pt is not None: |
| ax.plot(*pt, "o", color=color, markersize=10, markeredgewidth=2, |
| markeredgecolor="white") |
|
|
| r_patch = mpatches.Patch(color="red", label="right wrist") |
| l_patch = mpatches.Patch(color="blue", label="left wrist") |
| fig.legend(handles=[r_patch, l_patch], loc="lower center", ncol=2, fontsize=12) |
| plt.tight_layout() |
| plt.savefig(f"wrist_vis_frame{idx}.png", dpi=100) |
| plt.show() |
| print(f"Saved to wrist_vis_frame{idx}.png") |
|
|
|
|
| def construct_args(): |
| parser = argparse.ArgumentParser() |
| |
| parser.add_argument("--mano_p", type=str, default=None) |
| |
| parser.add_argument("--frame", type=int, default=55) |
| parser.add_argument("--vis", action="store_true", default=True, help="visualize wrist projection") |
| return parser.parse_args() |
|
|
|
|
| def main(): |
| args = construct_args() |
|
|
| if args.mano_p is not None: |
| mano_p = args.mano_p |
| else: |
| candidates = glob(op.join(DATA_ROOT, "raw_seqs", "*", "*.mano.npy")) |
| assert candidates, "No .mano.npy files found. Unzip raw_seqs.zip first." |
| mano_p = sorted(candidates)[0] |
|
|
| print(f"Loading: {mano_p}") |
| seq_data = load_hand_seq(mano_p) |
|
|
| print_summary(seq_data) |
| frame = get_frame(seq_data, args.frame) |
| print_frame(frame, args.frame) |
|
|
| if args.vis: |
| visualize_wrists(frame, args.frame, seq_data) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|