Datasets:

FKZZddd's picture
Update ARCTICHUGGFACE/hand_reader.py
4d66826 verified
Raw
History Blame Contribute Delete
11.4 kB
"""
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"
# the view information contained in misc.json
# view 0 = ego cam (head-mounted, moves every frame)
# view 1-8 = 8 fixed allocentric cameras
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
"""
# -- MANO (same loading as preprocess_dataset.py construct_loader) --
data = np.load(mano_p, allow_pickle=True).item()
num_frames = len(data["right"]["rot"])
def _load_hand(side):
return {
# (F, 3)
"rot": torch.FloatTensor(data[side]["rot"]),
# (F, 45)
#posture
"pose": torch.FloatTensor(data[side]["pose"]),
# (F, 3)
#location
"trans": torch.FloatTensor(data[side]["trans"]),
# (F, 10)
#mano shape
"shape": torch.FloatTensor(data[side]["shape"]).repeat(num_frames, 1),
#an error, lower error means more confident
# (F,)
"fitting_err": data[side]["fitting_err"],
}
right = _load_hand("right")
left = _load_hand("left")
# sanity check from preprocess_dataset.py
assert len(right["fitting_err"]) > 50, f"Too few frames: {mano_p}"
# -- Ego camera (same as preprocess_dataset.py construct_loader) --
ego_p = mano_p.replace("mano.npy", "egocam.dist.npy")
egocam = np.load(ego_p, allow_pickle=True).item()
#direction of camera under world coordinate
# (F, 3, 3)
R_ego = torch.FloatTensor(egocam["R_k_cam_np"])
#location world coordinate
# (F, 3, 1)
T_ego = torch.FloatTensor(egocam["T_k_cam_np"])
# intrinsics
# (3, 3)
K_ego = torch.FloatTensor(egocam["intrinsics"])
# (8,)
dist8 = torch.FloatTensor(egocam["dist8"])
# build homogeneous transform, same as preprocess_dataset.py
world2ego = torch.zeros((num_frames, 4, 4))
world2ego[:, :3, :3] = R_ego
world2ego[:, :3, 3] = T_ego[:, :, 0]
world2ego[:, 3, 3] = 1.0
# -- Static allo cameras (same as process_seqs.py statcams) --
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"])) # (8, 4, 4)
allo_K = torch.FloatTensor(np.array(sub["intris_mat"])) # (8, 3, 3)
image_size = np.array(sub["image_size"]) # (9, 2) [w, h]
seq_name = op.basename(mano_p).replace(".mano.npy", "")
return {
"right": right,
"left": left,
"ego_cam": {
"world2ego": world2ego, # (F, 4, 4)
"K": K_ego, # (3, 3)
"dist8": dist8, # (8,)
},
"static_cams": {
"world2cam": world2cam, # (8, 4, 4) world -> each allo cam
"K": allo_K, # (8, 3, 3)
"image_size": image_size, # (9, 2)
},
"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], # (4, 4)
"K_ego": seq_data["ego_cam"]["K"], # (3, 3)
"dist8": seq_data["ego_cam"]["dist8"], # (8,)
"static_cams": seq_data["static_cams"],
}
# attach image paths if cropped_images are available
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
# --------------------------------------------------------------------------
# CLI helpers
# --------------------------------------------------------------------------
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) # (4,)
pt_cam = (world2cam @ pt_h)[:3] # (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() # (8, 4, 4)
K_allo = seq_data["static_cams"]["K"].numpy() # (8, 3, 3)
trans_r = frame["right"]["trans"].numpy() # (3,)
trans_l = frame["left"]["trans"].numpy() # (3,)
# collect allo views (view_id 1-8 → cam index 0-7)
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 # "allo_1" → 0
W2C = world2cam[cam_idx] # (4, 4)
K = K_allo[cam_idx] # (3, 3)
img = mpimg.imread(img_path)
crop_h, crop_w = img.shape[:2]
# project both wrists to full-image coords
pt_r = project_point(trans_r, W2C, K)
pt_l = project_point(trans_l, W2C, K)
# estimate crop center as midpoint of the two wrists (heuristic,
# since we don't have the exact bbox without splits data)
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
# place image so estimated crop center aligns with wrist midpoint
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()
#mano_p: information of position and shape
parser.add_argument("--mano_p", type=str, default=None)
# for a specific frame
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()