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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pre-compute 3D hand joint positions from MANO parameters.
|
| 3 |
+
|
| 4 |
+
For each sequence, runs MANO forward kinematics on all frames and saves
|
| 5 |
+
a single `hand_joints.npy` with shape (T, 2, 21, 3) — float32, meters,
|
| 6 |
+
world frame. Dim 1: 0=left, 1=right.
|
| 7 |
+
|
| 8 |
+
Joint order (21): wrist, index(MCP,PIP,DIP,tip), middle(...), ring(...),
|
| 9 |
+
pinky(...), thumb(CMC,MCP,IP,tip).
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python precompute_hand_joints.py --root /path/to/taco_dataset
|
| 13 |
+
python precompute_hand_joints.py --root /path/to/taco_dataset --force
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import inspect
|
| 18 |
+
import pickle
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
# Monkey-patch for chumpy compat with Python 3.12+ / numpy 2.x
|
| 23 |
+
if not hasattr(inspect, "getargspec"):
|
| 24 |
+
inspect.getargspec = inspect.getfullargspec
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
for _alias in ("bool", "int", "float", "complex", "object", "str"):
|
| 29 |
+
if not hasattr(np, _alias):
|
| 30 |
+
setattr(np, _alias, getattr(__builtins__, _alias, object))
|
| 31 |
+
if not hasattr(np, "unicode"):
|
| 32 |
+
np.unicode = str
|
| 33 |
+
|
| 34 |
+
import scipy.sparse
|
| 35 |
+
|
| 36 |
+
# ── MANO forward kinematics (from render_mesh_overlay.py) ─────────────
|
| 37 |
+
|
| 38 |
+
_JOINT_REORDER = [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20]
|
| 39 |
+
_TIPS_RIGHT = [745, 317, 444, 556, 673]
|
| 40 |
+
_TIPS_LEFT = [745, 317, 445, 556, 673]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _load_mano_pkl(path):
|
| 44 |
+
with open(path, "rb") as f:
|
| 45 |
+
raw = pickle.load(f, encoding="latin1")
|
| 46 |
+
out = {}
|
| 47 |
+
for k, v in raw.items():
|
| 48 |
+
if hasattr(v, "r"):
|
| 49 |
+
out[k] = np.array(v.r, dtype=np.float64)
|
| 50 |
+
elif scipy.sparse.issparse(v):
|
| 51 |
+
out[k] = v
|
| 52 |
+
elif isinstance(v, np.ndarray):
|
| 53 |
+
out[k] = v.astype(np.float64) if v.dtype.kind == "f" else v
|
| 54 |
+
else:
|
| 55 |
+
out[k] = v
|
| 56 |
+
return out
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _rodrigues(rotvec):
|
| 60 |
+
angle = np.linalg.norm(rotvec)
|
| 61 |
+
if angle < 1e-8:
|
| 62 |
+
return np.eye(3, dtype=np.float64)
|
| 63 |
+
k = rotvec / angle
|
| 64 |
+
K = np.array([[0, -k[2], k[1]],
|
| 65 |
+
[k[2], 0, -k[0]],
|
| 66 |
+
[-k[1], k[0], 0]], dtype=np.float64)
|
| 67 |
+
return np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * (K @ K)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _batch_rodrigues(axisang):
|
| 71 |
+
return np.array([_rodrigues(a) for a in axisang])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ManoModel:
|
| 75 |
+
def __init__(self, mano_pkl_path, side="right"):
|
| 76 |
+
d = _load_mano_pkl(mano_pkl_path)
|
| 77 |
+
self.v_template = d["v_template"]
|
| 78 |
+
self.shapedirs = d["shapedirs"]
|
| 79 |
+
self.posedirs = d["posedirs"]
|
| 80 |
+
self.weights = d["weights"]
|
| 81 |
+
self.side = side
|
| 82 |
+
|
| 83 |
+
jr = d["J_regressor"]
|
| 84 |
+
self.J_regressor = jr.toarray() if scipy.sparse.issparse(jr) else np.array(jr)
|
| 85 |
+
|
| 86 |
+
kt = d["kintree_table"]
|
| 87 |
+
self.parents = [int(kt[0, i]) for i in range(kt.shape[1])]
|
| 88 |
+
self.parents[0] = -1
|
| 89 |
+
|
| 90 |
+
self.tip_indices = _TIPS_RIGHT if side == "right" else _TIPS_LEFT
|
| 91 |
+
|
| 92 |
+
def forward(self, hand_pose, hand_trans, betas=None):
|
| 93 |
+
if betas is not None and self.shapedirs.ndim == 3:
|
| 94 |
+
v_shaped = self.v_template + np.einsum("vci,i->vc", self.shapedirs, betas)
|
| 95 |
+
else:
|
| 96 |
+
v_shaped = self.v_template.copy()
|
| 97 |
+
|
| 98 |
+
J = self.J_regressor @ v_shaped
|
| 99 |
+
full_pose = hand_pose[:48].copy()
|
| 100 |
+
rot_mats = _batch_rodrigues(full_pose.reshape(16, 3))
|
| 101 |
+
|
| 102 |
+
pose_feature = (rot_mats[1:] - np.eye(3)).ravel()
|
| 103 |
+
v_posed = v_shaped + np.einsum("vci,i->vc", self.posedirs, pose_feature)
|
| 104 |
+
|
| 105 |
+
G = np.zeros((16, 4, 4), dtype=np.float64)
|
| 106 |
+
G[0, :3, :3] = rot_mats[0]
|
| 107 |
+
G[0, :3, 3] = J[0]
|
| 108 |
+
G[0, 3, 3] = 1.0
|
| 109 |
+
|
| 110 |
+
for i in range(1, 16):
|
| 111 |
+
p = self.parents[i]
|
| 112 |
+
local = np.eye(4, dtype=np.float64)
|
| 113 |
+
local[:3, :3] = rot_mats[i]
|
| 114 |
+
local[:3, 3] = J[i] - J[p]
|
| 115 |
+
G[i] = G[p] @ local
|
| 116 |
+
|
| 117 |
+
jtr = G[:, :3, 3].copy()
|
| 118 |
+
|
| 119 |
+
G_skin = G.copy()
|
| 120 |
+
for i in range(16):
|
| 121 |
+
Jh = np.append(J[i], 0.0)
|
| 122 |
+
G_skin[i, :, 3] -= G_skin[i] @ Jh
|
| 123 |
+
|
| 124 |
+
T = np.einsum("jab,vj->vab", G_skin, self.weights)
|
| 125 |
+
v_homo = np.concatenate([v_posed, np.ones((778, 1))], axis=1)
|
| 126 |
+
v_final = np.einsum("vab,vb->va", T, v_homo)[:, :3]
|
| 127 |
+
|
| 128 |
+
tips = v_final[self.tip_indices]
|
| 129 |
+
jtr = np.concatenate([jtr, tips], axis=0)
|
| 130 |
+
|
| 131 |
+
center = jtr[0:1].copy()
|
| 132 |
+
jtr -= center
|
| 133 |
+
jtr += hand_trans
|
| 134 |
+
|
| 135 |
+
return jtr[_JOINT_REORDER]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# ── Processing ─────────────────────────────────────────────────────────
|
| 139 |
+
|
| 140 |
+
def process_sequence(hand_dir: Path, mano_left: ManoModel, mano_right: ManoModel) -> np.ndarray:
|
| 141 |
+
"""Process one sequence, return (T, 2, 21, 3) float32 array."""
|
| 142 |
+
# Load pose data
|
| 143 |
+
sides = []
|
| 144 |
+
for side, model in [("left", mano_left), ("right", mano_right)]:
|
| 145 |
+
pose_file = hand_dir / f"{side}_hand.pkl"
|
| 146 |
+
shape_file = hand_dir / f"{side}_hand_shape.pkl"
|
| 147 |
+
|
| 148 |
+
with open(pose_file, "rb") as f:
|
| 149 |
+
pose_data = pickle.load(f)
|
| 150 |
+
|
| 151 |
+
betas = None
|
| 152 |
+
if shape_file.exists():
|
| 153 |
+
with open(shape_file, "rb") as f:
|
| 154 |
+
shape_data = pickle.load(f)
|
| 155 |
+
betas = np.array(shape_data["hand_shape"], dtype=np.float64).ravel()[:10]
|
| 156 |
+
|
| 157 |
+
# Sort frame keys numerically
|
| 158 |
+
frame_keys = sorted(pose_data.keys(), key=lambda x: int(x))
|
| 159 |
+
n_frames = len(frame_keys)
|
| 160 |
+
|
| 161 |
+
joints_all = np.zeros((n_frames, 21, 3), dtype=np.float64)
|
| 162 |
+
for fi, fk in enumerate(frame_keys):
|
| 163 |
+
frame = pose_data[fk]
|
| 164 |
+
hand_pose = np.array(frame["hand_pose"], dtype=np.float64).ravel()
|
| 165 |
+
hand_trans = np.array(frame["hand_trans"], dtype=np.float64).ravel()
|
| 166 |
+
joints_all[fi] = model.forward(hand_pose, hand_trans, betas=betas)
|
| 167 |
+
|
| 168 |
+
sides.append(joints_all)
|
| 169 |
+
|
| 170 |
+
# Stack: (T, 2, 21, 3) — left=0, right=1
|
| 171 |
+
assert sides[0].shape[0] == sides[1].shape[0], \
|
| 172 |
+
f"Frame count mismatch: left={sides[0].shape[0]}, right={sides[1].shape[0]}"
|
| 173 |
+
result = np.stack(sides, axis=1) # (T, 2, 21, 3)
|
| 174 |
+
return result.astype(np.float32)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def main():
|
| 178 |
+
parser = argparse.ArgumentParser(description="Pre-compute 3D hand joints from MANO parameters")
|
| 179 |
+
parser.add_argument("--root", type=Path, required=True, help="Dataset root directory")
|
| 180 |
+
parser.add_argument("--force", action="store_true", help="Overwrite existing hand_joints.npy")
|
| 181 |
+
args = parser.parse_args()
|
| 182 |
+
|
| 183 |
+
root = args.root
|
| 184 |
+
csv_path = root / "taco_info.csv"
|
| 185 |
+
mano_root = root / "mano_v1_2" / "models"
|
| 186 |
+
|
| 187 |
+
if not csv_path.exists():
|
| 188 |
+
print(f"ERROR: {csv_path} not found")
|
| 189 |
+
sys.exit(1)
|
| 190 |
+
if not mano_root.exists():
|
| 191 |
+
print(f"ERROR: {mano_root} not found")
|
| 192 |
+
sys.exit(1)
|
| 193 |
+
|
| 194 |
+
import pandas as pd
|
| 195 |
+
meta = pd.read_csv(csv_path)
|
| 196 |
+
|
| 197 |
+
print(f"Loading MANO models from {mano_root}...")
|
| 198 |
+
mano_left = ManoModel(mano_root / "MANO_LEFT.pkl", side="left")
|
| 199 |
+
mano_right = ManoModel(mano_root / "MANO_RIGHT.pkl", side="right")
|
| 200 |
+
|
| 201 |
+
n_total = len(meta)
|
| 202 |
+
n_done = 0
|
| 203 |
+
n_skipped = 0
|
| 204 |
+
n_errors = 0
|
| 205 |
+
|
| 206 |
+
print(f"Processing {n_total} sequences...")
|
| 207 |
+
for i, (_, row) in enumerate(meta.iterrows()):
|
| 208 |
+
hand_dir_rel = row.get("hand_poses_dir", "")
|
| 209 |
+
if pd.isna(hand_dir_rel) or not hand_dir_rel:
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
hand_dir = root / hand_dir_rel
|
| 213 |
+
out_path = hand_dir / "hand_joints.npy"
|
| 214 |
+
|
| 215 |
+
if out_path.exists() and not args.force:
|
| 216 |
+
n_skipped += 1
|
| 217 |
+
if (i + 1) % 200 == 0:
|
| 218 |
+
print(f" [{i+1}/{n_total}] {n_done} done, {n_skipped} skipped, {n_errors} errors")
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
joints = process_sequence(hand_dir, mano_left, mano_right)
|
| 223 |
+
np.save(out_path, joints)
|
| 224 |
+
n_done += 1
|
| 225 |
+
except Exception as e:
|
| 226 |
+
seq_id = row.get("sequence_id", "?")
|
| 227 |
+
print(f" ERROR {seq_id}: {e}")
|
| 228 |
+
n_errors += 1
|
| 229 |
+
|
| 230 |
+
if (i + 1) % 200 == 0:
|
| 231 |
+
print(f" [{i+1}/{n_total}] {n_done} done, {n_skipped} skipped, {n_errors} errors")
|
| 232 |
+
|
| 233 |
+
print(f"\nDone: {n_done} computed, {n_skipped} skipped, {n_errors} errors (total {n_total})")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
main()
|