Datasets:

FKZZddd commited on
Commit
b19accc
·
verified ·
1 Parent(s): 2ffde88

Upload hand_reader.py

Browse files
Files changed (1) hide show
  1. ARCTICHUGGFACE/hand_reader.py +202 -0
ARCTICHUGGFACE/hand_reader.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ARCTIC Hand Data Reader
3
+ Only reads hand (MANO) parameters from raw_seqs.
4
+ No body model forward pass, no object data, no splits needed.
5
+
6
+ Usage:
7
+ python scripts_data/hand_reader.py
8
+ python scripts_data/hand_reader.py --mano_p ./unpack/arctic_data/data/raw_seqs/s01/box_grab_01.mano.npy
9
+ python scripts_data/hand_reader.py --mano_p ./unpack/arctic_data/data/raw_seqs/s01/box_grab_01.mano.npy --frame 10
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import os.path as op
15
+ import sys
16
+ from glob import glob
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ sys.path = ["."] + sys.path
22
+
23
+ DATA_ROOT = "./data"
24
+
25
+ # view 0 = ego cam (head-mounted, moves every frame)
26
+ # view 1-8 = 8 fixed allocentric cameras
27
+ VIEW_NAMES = ["ego", "allo_1", "allo_2", "allo_3", "allo_4",
28
+ "allo_5", "allo_6", "allo_7", "allo_8"]
29
+
30
+
31
+ def load_hand_seq(mano_p):
32
+ """
33
+ Load one sequence. Mirrors construct_loader() in
34
+ src/arctic/preprocess_dataset.py but keeps only hand fields.
35
+
36
+ Returns a dict with:
37
+ right / left -> MANO params (tensors)
38
+ ego_cam -> per-frame ego camera (world2ego, K, dist8)
39
+ static_cams -> 8 fixed allo cameras from misc.json (world2cam, K)
40
+ meta -> sid, seq_name, num_frames, gender
41
+ """
42
+ # -- MANO (same loading as preprocess_dataset.py construct_loader) --
43
+ data = np.load(mano_p, allow_pickle=True).item()
44
+ num_frames = len(data["right"]["rot"])
45
+
46
+ def _load_hand(side):
47
+ return {
48
+ "rot": torch.FloatTensor(data[side]["rot"]), # (F, 3)
49
+ "pose": torch.FloatTensor(data[side]["pose"]), # (F, 45)
50
+ "trans": torch.FloatTensor(data[side]["trans"]), # (F, 3)
51
+ "shape": torch.FloatTensor(data[side]["shape"]).repeat(num_frames, 1), # (F, 10)
52
+ "fitting_err": data[side]["fitting_err"], # (F,)
53
+ }
54
+
55
+ right = _load_hand("right")
56
+ left = _load_hand("left")
57
+
58
+ # sanity check from preprocess_dataset.py
59
+ assert len(right["fitting_err"]) > 50, f"Too few frames: {mano_p}"
60
+
61
+ # -- Ego camera (same as preprocess_dataset.py construct_loader) --
62
+ ego_p = mano_p.replace("mano.npy", "egocam.dist.npy")
63
+ egocam = np.load(ego_p, allow_pickle=True).item()
64
+
65
+ R_ego = torch.FloatTensor(egocam["R_k_cam_np"]) # (F, 3, 3)
66
+ T_ego = torch.FloatTensor(egocam["T_k_cam_np"]) # (F, 3, 1)
67
+ K_ego = torch.FloatTensor(egocam["intrinsics"]) # (3, 3)
68
+ dist8 = torch.FloatTensor(egocam["dist8"]) # (8,)
69
+
70
+ # build homogeneous transform, same as preprocess_dataset.py
71
+ world2ego = torch.zeros((num_frames, 4, 4))
72
+ world2ego[:, :3, :3] = R_ego
73
+ world2ego[:, :3, 3] = T_ego[:, :, 0]
74
+ world2ego[:, 3, 3] = 1.0
75
+
76
+ # -- Static allo cameras (same as process_seqs.py statcams) --
77
+ sid = mano_p.split("/")[-2]
78
+ misc_p = op.join(DATA_ROOT, "misc.json")
79
+ with open(misc_p) as f:
80
+ misc = json.load(f)
81
+
82
+ sub = misc[sid]
83
+ world2cam = torch.FloatTensor(np.array(sub["world2cam"])) # (8, 4, 4)
84
+ allo_K = torch.FloatTensor(np.array(sub["intris_mat"])) # (8, 3, 3)
85
+ image_size = np.array(sub["image_size"]) # (9, 2) [w, h]
86
+
87
+ seq_name = mano_p.split("/")[-1].replace(".mano.npy", "")
88
+
89
+ return {
90
+ "right": right,
91
+ "left": left,
92
+ "ego_cam": {
93
+ "world2ego": world2ego, # (F, 4, 4)
94
+ "K": K_ego, # (3, 3)
95
+ "dist8": dist8, # (8,)
96
+ },
97
+ "static_cams": {
98
+ "world2cam": world2cam, # (8, 4, 4) world -> each allo cam
99
+ "K": allo_K, # (8, 3, 3)
100
+ "image_size": image_size, # (9, 2)
101
+ },
102
+ "meta": {
103
+ "sid": sid,
104
+ "seq_name": seq_name,
105
+ "num_frames": num_frames,
106
+ "gender": sub["gender"],
107
+ },
108
+ }
109
+
110
+
111
+ def get_frame(seq_data, idx):
112
+ """Return data for a single frame (0-indexed)."""
113
+ n = seq_data["meta"]["num_frames"]
114
+ assert 0 <= idx < n, f"Frame {idx} out of range (0-{n-1})"
115
+
116
+ def _frame_hand(h):
117
+ return {k: (v[idx] if isinstance(v, torch.Tensor) else v[idx])
118
+ for k, v in h.items()}
119
+
120
+ frame = {
121
+ "right": _frame_hand(seq_data["right"]),
122
+ "left": _frame_hand(seq_data["left"]),
123
+ "world2ego": seq_data["ego_cam"]["world2ego"][idx], # (4, 4)
124
+ "K_ego": seq_data["ego_cam"]["K"], # (3, 3)
125
+ "dist8": seq_data["ego_cam"]["dist8"], # (8,)
126
+ "static_cams": seq_data["static_cams"],
127
+ }
128
+
129
+ # attach image paths if cropped_images are available
130
+ img_dir = op.join(DATA_ROOT, "cropped_images",
131
+ seq_data["meta"]["sid"], seq_data["meta"]["seq_name"])
132
+ if op.exists(img_dir):
133
+ fname = f"{idx + 1:05d}.jpg"
134
+ frame["images"] = {
135
+ name: p for name, view_id in zip(VIEW_NAMES, range(9))
136
+ if op.exists(p := op.join(img_dir, str(view_id), fname))
137
+ }
138
+
139
+ return frame
140
+
141
+
142
+ # --------------------------------------------------------------------------
143
+ # CLI helpers
144
+ # --------------------------------------------------------------------------
145
+
146
+ def print_summary(seq_data):
147
+ m = seq_data["meta"]
148
+ print(f"\n=== Sequence: {m['sid']}/{m['seq_name']} ===")
149
+ print(f"Frames : {m['num_frames']}")
150
+ print(f"Subject: {m['sid']} gender={m['gender']}")
151
+ print(f"\nRight hand shape (10,): {seq_data['right']['shape'][0].numpy()}")
152
+ print(f"Left hand shape (10,): {seq_data['left']['shape'][0].numpy()}")
153
+ print(f"\nEgo cam K (3x3):\n{seq_data['ego_cam']['K'].numpy()}")
154
+ print(f"Ego cam dist8: {seq_data['ego_cam']['dist8'].numpy()}")
155
+ print(f"\nAllo cams: {seq_data['static_cams']['world2cam'].shape[0]}")
156
+ print(f"Image sizes (w x h):\n{seq_data['static_cams']['image_size']}")
157
+
158
+
159
+ def print_frame(frame, idx):
160
+ print(f"\n--- Frame {idx} ---")
161
+ for side in ["right", "left"]:
162
+ h = frame[side]
163
+ print(f"\n[{side} hand]")
164
+ print(f" rot (3,) : {h['rot'].numpy()}")
165
+ print(f" trans (3,) : {h['trans'].numpy()}")
166
+ print(f" pose (45,) first 6: {h['pose'].numpy()[:6]}")
167
+ print(f" shape (10,) : {h['shape'].numpy()}")
168
+ print(f" fitting_err : {h['fitting_err']:.4f}")
169
+ print(f"\n[Ego world2ego row 0-1]:\n{frame['world2ego'].numpy()[:2]}")
170
+ if "images" in frame:
171
+ print(f"\n[Available images]")
172
+ for view, path in frame["images"].items():
173
+ print(f" {view:8s}: {path}")
174
+
175
+
176
+ def construct_args():
177
+ parser = argparse.ArgumentParser()
178
+ parser.add_argument("--mano_p", type=str, default=None)
179
+ parser.add_argument("--frame", type=int, default=0)
180
+ return parser.parse_args()
181
+
182
+
183
+ def main():
184
+ args = construct_args()
185
+
186
+ if args.mano_p is not None:
187
+ mano_p = args.mano_p
188
+ else:
189
+ candidates = glob(op.join(DATA_ROOT, "raw_seqs", "*", "*.mano.npy"))
190
+ assert candidates, "No .mano.npy files found. Unzip raw_seqs.zip first."
191
+ mano_p = sorted(candidates)[0]
192
+
193
+ print(f"Loading: {mano_p}")
194
+ seq_data = load_hand_seq(mano_p)
195
+
196
+ print_summary(seq_data)
197
+ frame = get_frame(seq_data, args.frame)
198
+ print_frame(frame, args.frame)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()