File size: 11,351 Bytes
b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 b19accc 4d66826 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | """
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()
|