taco_dataset_resized / tools /precompute_hand_joints.py
mzhobro's picture
Upload folder using huggingface_hub
85f6c1d verified
#!/usr/bin/env python3
"""Pre-compute 3D hand joint positions from MANO parameters.
For each sequence, runs MANO forward kinematics on all frames and saves
a single `hand_joints.npy` with shape (T, 2, 21, 3) — float32, meters,
world frame. Dim 1: 0=left, 1=right.
Joint order (21): wrist, index(MCP,PIP,DIP,tip), middle(...), ring(...),
pinky(...), thumb(CMC,MCP,IP,tip).
Usage:
python precompute_hand_joints.py --root /path/to/taco_dataset
python precompute_hand_joints.py --root /path/to/taco_dataset --force
"""
import argparse
import inspect
import pickle
import sys
from pathlib import Path
# Monkey-patch for chumpy compat with Python 3.12+ / numpy 2.x
if not hasattr(inspect, "getargspec"):
inspect.getargspec = inspect.getfullargspec
import numpy as np
for _alias in ("bool", "int", "float", "complex", "object", "str"):
if not hasattr(np, _alias):
setattr(np, _alias, getattr(__builtins__, _alias, object))
if not hasattr(np, "unicode"):
np.unicode = str
import scipy.sparse
# ── MANO forward kinematics (from render_mesh_overlay.py) ─────────────
_JOINT_REORDER = [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20]
_TIPS_RIGHT = [745, 317, 444, 556, 673]
_TIPS_LEFT = [745, 317, 445, 556, 673]
def _load_mano_pkl(path):
with open(path, "rb") as f:
raw = pickle.load(f, encoding="latin1")
out = {}
for k, v in raw.items():
if hasattr(v, "r"):
out[k] = np.array(v.r, dtype=np.float64)
elif scipy.sparse.issparse(v):
out[k] = v
elif isinstance(v, np.ndarray):
out[k] = v.astype(np.float64) if v.dtype.kind == "f" else v
else:
out[k] = v
return out
def _rodrigues(rotvec):
angle = np.linalg.norm(rotvec)
if angle < 1e-8:
return np.eye(3, dtype=np.float64)
k = rotvec / angle
K = np.array([[0, -k[2], k[1]],
[k[2], 0, -k[0]],
[-k[1], k[0], 0]], dtype=np.float64)
return np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * (K @ K)
def _batch_rodrigues(axisang):
return np.array([_rodrigues(a) for a in axisang])
class ManoModel:
def __init__(self, mano_pkl_path, side="right"):
d = _load_mano_pkl(mano_pkl_path)
self.v_template = d["v_template"]
self.shapedirs = d["shapedirs"]
self.posedirs = d["posedirs"]
self.weights = d["weights"]
self.side = side
jr = d["J_regressor"]
self.J_regressor = jr.toarray() if scipy.sparse.issparse(jr) else np.array(jr)
kt = d["kintree_table"]
self.parents = [int(kt[0, i]) for i in range(kt.shape[1])]
self.parents[0] = -1
self.tip_indices = _TIPS_RIGHT if side == "right" else _TIPS_LEFT
def forward(self, hand_pose, hand_trans, betas=None):
if betas is not None and self.shapedirs.ndim == 3:
v_shaped = self.v_template + np.einsum("vci,i->vc", self.shapedirs, betas)
else:
v_shaped = self.v_template.copy()
J = self.J_regressor @ v_shaped
full_pose = hand_pose[:48].copy()
rot_mats = _batch_rodrigues(full_pose.reshape(16, 3))
pose_feature = (rot_mats[1:] - np.eye(3)).ravel()
v_posed = v_shaped + np.einsum("vci,i->vc", self.posedirs, pose_feature)
G = np.zeros((16, 4, 4), dtype=np.float64)
G[0, :3, :3] = rot_mats[0]
G[0, :3, 3] = J[0]
G[0, 3, 3] = 1.0
for i in range(1, 16):
p = self.parents[i]
local = np.eye(4, dtype=np.float64)
local[:3, :3] = rot_mats[i]
local[:3, 3] = J[i] - J[p]
G[i] = G[p] @ local
jtr = G[:, :3, 3].copy()
G_skin = G.copy()
for i in range(16):
Jh = np.append(J[i], 0.0)
G_skin[i, :, 3] -= G_skin[i] @ Jh
T = np.einsum("jab,vj->vab", G_skin, self.weights)
v_homo = np.concatenate([v_posed, np.ones((778, 1))], axis=1)
v_final = np.einsum("vab,vb->va", T, v_homo)[:, :3]
tips = v_final[self.tip_indices]
jtr = np.concatenate([jtr, tips], axis=0)
center = jtr[0:1].copy()
jtr -= center
jtr += hand_trans
return jtr[_JOINT_REORDER]
# ── Processing ─────────────────────────────────────────────────────────
def process_sequence(hand_dir: Path, mano_left: ManoModel, mano_right: ManoModel) -> np.ndarray:
"""Process one sequence, return (T, 2, 21, 3) float32 array."""
# Load pose data
sides = []
for side, model in [("left", mano_left), ("right", mano_right)]:
pose_file = hand_dir / f"{side}_hand.pkl"
shape_file = hand_dir / f"{side}_hand_shape.pkl"
with open(pose_file, "rb") as f:
pose_data = pickle.load(f)
betas = None
if shape_file.exists():
with open(shape_file, "rb") as f:
shape_data = pickle.load(f)
betas = np.array(shape_data["hand_shape"], dtype=np.float64).ravel()[:10]
# Sort frame keys numerically
frame_keys = sorted(pose_data.keys(), key=lambda x: int(x))
n_frames = len(frame_keys)
joints_all = np.zeros((n_frames, 21, 3), dtype=np.float64)
for fi, fk in enumerate(frame_keys):
frame = pose_data[fk]
hand_pose = np.array(frame["hand_pose"], dtype=np.float64).ravel()
hand_trans = np.array(frame["hand_trans"], dtype=np.float64).ravel()
joints_all[fi] = model.forward(hand_pose, hand_trans, betas=betas)
sides.append(joints_all)
# Stack: (T, 2, 21, 3) — left=0, right=1
assert sides[0].shape[0] == sides[1].shape[0], \
f"Frame count mismatch: left={sides[0].shape[0]}, right={sides[1].shape[0]}"
result = np.stack(sides, axis=1) # (T, 2, 21, 3)
return result.astype(np.float32)
def main():
parser = argparse.ArgumentParser(description="Pre-compute 3D hand joints from MANO parameters")
parser.add_argument("--root", type=Path, required=True, help="Dataset root directory")
parser.add_argument("--force", action="store_true", help="Overwrite existing hand_joints.npy")
args = parser.parse_args()
root = args.root
csv_path = root / "taco_info.csv"
mano_root = root / "mano_v1_2" / "models"
if not csv_path.exists():
print(f"ERROR: {csv_path} not found")
sys.exit(1)
if not mano_root.exists():
print(f"ERROR: {mano_root} not found")
sys.exit(1)
import pandas as pd
meta = pd.read_csv(csv_path)
print(f"Loading MANO models from {mano_root}...")
mano_left = ManoModel(mano_root / "MANO_LEFT.pkl", side="left")
mano_right = ManoModel(mano_root / "MANO_RIGHT.pkl", side="right")
n_total = len(meta)
n_done = 0
n_skipped = 0
n_errors = 0
print(f"Processing {n_total} sequences...")
for i, (_, row) in enumerate(meta.iterrows()):
hand_dir_rel = row.get("hand_poses_dir", "")
if pd.isna(hand_dir_rel) or not hand_dir_rel:
continue
hand_dir = root / hand_dir_rel
out_path = hand_dir / "hand_joints.npy"
if out_path.exists() and not args.force:
n_skipped += 1
if (i + 1) % 200 == 0:
print(f" [{i+1}/{n_total}] {n_done} done, {n_skipped} skipped, {n_errors} errors")
continue
try:
joints = process_sequence(hand_dir, mano_left, mano_right)
np.save(out_path, joints)
n_done += 1
except Exception as e:
seq_id = row.get("sequence_id", "?")
print(f" ERROR {seq_id}: {e}")
n_errors += 1
if (i + 1) % 200 == 0:
print(f" [{i+1}/{n_total}] {n_done} done, {n_skipped} skipped, {n_errors} errors")
print(f"\nDone: {n_done} computed, {n_skipped} skipped, {n_errors} errors (total {n_total})")
if __name__ == "__main__":
main()