Datasets:

FKZZddd commited on
Commit
d188b91
·
verified ·
1 Parent(s): 4ddc1be

Upload HOT3DHUGGFACE/Segmentation.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. HOT3DHUGGFACE/Segmentation.py +392 -1085
HOT3DHUGGFACE/Segmentation.py CHANGED
@@ -1,1085 +1,392 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "id": "ee215408-e60b-4209-a09a-f84a8fd5ffa1",
6
- "metadata": {},
7
- "source": [
8
- "# HOT3D Data Reader\n",
9
- "\n",
10
- "This notebook is adapted from the HOT3D official tutorial. It supports both **Aria** and **Quest3** devices and uses only the **MANO** hand model (no UmeTrack or object assets required).\n",
11
- "\n",
12
- "## Sections\n",
13
- "- **Section 0**: Initialization (update the two paths, then run)\n",
14
- "- **Section 1**: Image streams + camera calibration\n",
15
- "- **Section 2.a**: Device / headset pose trajectory\n",
16
- "- **Section 2.b**: Hand wrist trajectory\n",
17
- "- **Section 2.b.a**: Hand landmarks (skeleton) + mesh\n",
18
- "- **Section 2.c**: Object poses (requires assets folder, skipped automatically otherwise)\n",
19
- "- **Section 3.b**: Hand 2D bounding boxes\n",
20
- "- **Section 4**: Eye gaze (Aria only, skipped automatically on Quest3)\n",
21
- "- **Section 5**: Hand keypoint reprojection onto image\n",
22
- "\n",
23
- "```\n",
24
- "Hot3dDataProvider\n",
25
- "|- device_data_provider -> image data + camera calibration\n",
26
- "|- device_pose_data_provider -> device pose\n",
27
- "|- mano_hand_data_provider -> hand pose (MANO)\n",
28
- "|- object_pose_data_provider -> object pose\n",
29
- "|- hand_box2d_data_provider -> hand 2D bounding boxes\n",
30
- "|- object_box2d_data_provider -> object 2D bounding boxes\n",
31
- "```\n",
32
- "\n",
33
- "> All pose data is in **world coordinates** (meters)."
34
- ]
35
- },
36
- {
37
- "cell_type": "code",
38
- "execution_count": null,
39
- "id": "97bcb96c-4910-4a60-9a41-c3b34ee7ac7b",
40
- "metadata": {},
41
- "outputs": [],
42
- "source": [
43
- "# Section 0: DataProvider initialization\n",
44
- "#\n",
45
- "# Only the two paths below need to be updated; everything else adapts automatically\n",
46
- "# to Aria or Quest3.\n",
47
- "\n",
48
- "import os\n",
49
- "import sys\n",
50
- "\n",
51
- "# Make sure the hot3d package is importable from this notebook\n",
52
- "notebook_dir = os.path.abspath('')\n",
53
- "if notebook_dir not in sys.path:\n",
54
- " sys.path.insert(0, notebook_dir)\n",
55
- "\n",
56
- "from dataset_api import Hot3dDataProvider\n",
57
- "from data_loaders.mano_layer import MANOHandModel\n",
58
- "from data_loaders.headsets import Headset\n",
59
- "from projectaria_tools.core.stream_id import StreamId\n",
60
- "\n",
61
- "# ── Update these two paths ───────────────────────────────────────\n",
62
- "sequence_path = \"/home/zhang/3D_Reconstruct/HOT3D/hot3d/hot3d/dataset/P0002_2f137f83\"\n",
63
- "mano_model_path = \"/home/zhang/Downloads/mano_v1_2/models\"\n",
64
- "# ────────────────────────────────────────────────────────────────\n",
65
- "\n",
66
- "# Load MANO hand model (requires smplx: pip install smplx)\n",
67
- "mano_hand_model = MANOHandModel(mano_model_path)\n",
68
- "\n",
69
- "# Initialize the data provider.\n",
70
- "# object_library=None: no assets folder needed when only reading hand data.\n",
71
- "hot3d_data_provider = Hot3dDataProvider(\n",
72
- " sequence_folder=sequence_path,\n",
73
- " object_library=None,\n",
74
- " mano_hand_model=mano_hand_model,\n",
75
- ")\n",
76
- "\n",
77
- "# Auto-detect device type and pick the corresponding primary camera stream_id\n",
78
- "device_type = hot3d_data_provider.get_device_type()\n",
79
- "print(f\"Device type: {device_type}\")\n",
80
- "\n",
81
- "if device_type == Headset.Aria:\n",
82
- " main_stream_id = StreamId(\"214-1\") # Aria: RGB camera\n",
83
- "else:\n",
84
- " main_stream_id = StreamId(\"1201-1\") # Quest3: SLAM Left camera\n",
85
- "\n",
86
- "print(f\"Primary stream_id: {main_stream_id}\")\n",
87
- "print(f\"Data statistics: {hot3d_data_provider.get_data_statistics()}\")"
88
- ]
89
- },
90
- {
91
- "cell_type": "code",
92
- "execution_count": null,
93
- "id": "24dae021-1cfe-440a-a5c8-6f44851219e7",
94
- "metadata": {},
95
- "outputs": [],
96
- "source": [
97
- "# Utility functions for Rerun visualization\n",
98
- "\n",
99
- "import rerun as rr\n",
100
- "import numpy as np\n",
101
- "from projectaria_tools.core.sophus import SE3\n",
102
- "from projectaria_tools.utils.rerun_helpers import ToTransform3D\n",
103
- "\n",
104
- "\n",
105
- "def log_image(image: np.array, label: str, static=False) -> None:\n",
106
- " rr.log(label, rr.Image(image), static=static)\n",
107
- "\n",
108
- "\n",
109
- "def log_pose(pose: SE3, label: str, static=False) -> None:\n",
110
- " rr.log(label, ToTransform3D(pose, False), static=static)"
111
- ]
112
- },
113
- {
114
- "cell_type": "code",
115
- "execution_count": null,
116
- "id": "c7447d83-bf07-4bfb-8e4f-9d548617cde7",
117
- "metadata": {},
118
- "outputs": [],
119
- "source": [
120
- "# Section 1: Image streams + camera calibration\n",
121
- "\n",
122
- "from tqdm import tqdm\n",
123
- "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n",
124
- "\n",
125
- "device_data_provider = hot3d_data_provider.device_data_provider\n",
126
- "image_stream_ids = device_data_provider.get_image_stream_ids()\n",
127
- "\n",
128
- "# Timestamp retrieval differs between Aria and Quest3\n",
129
- "if device_type == Headset.Aria:\n",
130
- " timestamps = device_data_provider.get_sequence_timestamps(\n",
131
- " stream_id=main_stream_id,\n",
132
- " time_domain=TimeDomain.TIME_CODE,\n",
133
- " )\n",
134
- "else:\n",
135
- " timestamps = device_data_provider.get_sequence_timestamps()\n",
136
- "\n",
137
- "print(f\"Sequence : {os.path.basename(os.path.normpath(sequence_path))}\")\n",
138
- "print(f\"Streams : {image_stream_ids}\")\n",
139
- "print(f\"Frames : {len(timestamps)}\")\n",
140
- "\n",
141
- "rr.init(\"Device images\")\n",
142
- "rec = rr.memory_recording()\n",
143
- "\n",
144
- "# Sample one frame every 200 timestamps to keep the visualization fast\n",
145
- "for timestamp_ns in tqdm(timestamps[::200]):\n",
146
- " for stream_id in image_stream_ids:\n",
147
- " image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
148
- " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
149
- " if image_data is not None:\n",
150
- " log_image(label=f\"img/{image_stream_label}\", image=image_data)\n",
151
- "\n",
152
- "# Print calibration parameters for each camera stream\n",
153
- "for stream_id in image_stream_ids:\n",
154
- " [extrinsics, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
155
- " label = device_data_provider.get_image_stream_label(stream_id)\n",
156
- " print(f\"\\n[{label}] intrinsics: {intrinsics}\")\n",
157
- "\n",
158
- "rr.notebook_show()"
159
- ]
160
- },
161
- {
162
- "cell_type": "markdown",
163
- "id": "1d199e9c-7359-43b2-8ecd-807db548def0",
164
- "metadata": {},
165
- "source": [
166
- "# GT Data Provider API\n",
167
- "\n",
168
- "All GT data providers share the same query interface:\n",
169
- "```python\n",
170
- "result = provider.get_X_at_timestamp(\n",
171
- " timestamp_ns=timestamp_ns,\n",
172
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
173
- " time_domain=TimeDomain.TIME_CODE,\n",
174
- ")\n",
175
- "```\n",
176
- "- If the exact timestamp is not found, the **closest** sample is returned.\n",
177
- "- The delta time (`dt`) between the queried and returned timestamp is also available.\n",
178
- "\n",
179
- "Available providers:\n",
180
- "```\n",
181
- "|- device_pose_data_provider -> device/headset pose\n",
182
- "|- mano_hand_data_provider -> hand pose (MANO)\n",
183
- "|- object_pose_data_provider -> object pose\n",
184
- "|- hand_box2d_data_provider -> hand 2D bbox + visibility\n",
185
- "|- object_box2d_data_provider -> object 2D bbox + visibility\n",
186
- "```"
187
- ]
188
- },
189
- {
190
- "cell_type": "code",
191
- "execution_count": null,
192
- "id": "a7c473c3-174f-4cff-9d58-0650b580da72",
193
- "metadata": {},
194
- "outputs": [],
195
- "source": [
196
- "# Section 2.a: Device / headset pose trajectory\n",
197
- "\n",
198
- "device_pose_provider = hot3d_data_provider.device_pose_data_provider\n",
199
- "\n",
200
- "rr.init(\"Device/Headset trajectory\")\n",
201
- "rec = rr.memory_recording()\n",
202
- "\n",
203
- "pose_translations = []\n",
204
- "for timestamp_ns in tqdm(timestamps):\n",
205
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
206
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
207
- "\n",
208
- " if device_pose_provider is None:\n",
209
- " continue\n",
210
- " result = device_pose_provider.get_pose_at_timestamp(\n",
211
- " timestamp_ns=timestamp_ns,\n",
212
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
213
- " time_domain=TimeDomain.TIME_CODE,\n",
214
- " )\n",
215
- " if result is None:\n",
216
- " continue\n",
217
- "\n",
218
- " T_world_device = result.pose3d.T_world_device\n",
219
- " log_pose(pose=T_world_device, label=\"world/device\")\n",
220
- " pose_translations.append(T_world_device.translation()[0])\n",
221
- "\n",
222
- "rr.log(\"world/device_trajectory\", rr.LineStrips3D([pose_translations]), static=True)\n",
223
- "rr.notebook_show()"
224
- ]
225
- },
226
- {
227
- "cell_type": "code",
228
- "execution_count": null,
229
- "id": "d5253618-2ca2-4d11-a605-aa5aa19c54eb",
230
- "metadata": {},
231
- "outputs": [],
232
- "source": [
233
- "# Section 2.b: Hand wrist trajectory (MANO only)\n",
234
- "\n",
235
- "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n",
236
- "if hand_data_provider is None:\n",
237
- " print(\"MANO hand data provider not initialized. Check mano_model_path and smplx installation.\")\n",
238
- "\n",
239
- "rr.init(\"Hand wrist trajectory\")\n",
240
- "rec = rr.memory_recording()\n",
241
- "\n",
242
- "left_traj, right_traj = [], []\n",
243
- "for timestamp_ns in tqdm(timestamps):\n",
244
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
245
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
246
- "\n",
247
- " if hand_data_provider is None:\n",
248
- " continue\n",
249
- " result = hand_data_provider.get_pose_at_timestamp(\n",
250
- " timestamp_ns=timestamp_ns,\n",
251
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
252
- " time_domain=TimeDomain.TIME_CODE,\n",
253
- " )\n",
254
- " if result is None:\n",
255
- " continue\n",
256
- "\n",
257
- " for hand_pose in result.pose3d_collection.poses.values():\n",
258
- " label = hand_pose.handedness_label()\n",
259
- " T_world_wrist = hand_pose.wrist_pose\n",
260
- " log_pose(pose=T_world_wrist, label=f\"world/hand/{label}\")\n",
261
- " if hand_pose.is_left_hand():\n",
262
- " left_traj.append(T_world_wrist.translation()[0])\n",
263
- " else:\n",
264
- " right_traj.append(T_world_wrist.translation()[0])\n",
265
- "\n",
266
- "if left_traj:\n",
267
- " rr.log(\"world/left_hand_traj\", rr.LineStrips3D([left_traj]), static=True)\n",
268
- "if right_traj:\n",
269
- " rr.log(\"world/right_hand_traj\", rr.LineStrips3D([right_traj]), static=True)\n",
270
- "rr.notebook_show()"
271
- ]
272
- },
273
- {
274
- "cell_type": "code",
275
- "execution_count": null,
276
- "id": "0a013c63-65e6-4c38-b378-141c8c7ae3ae",
277
- "metadata": {},
278
- "outputs": [],
279
- "source": [
280
- "# Section 2.b.a: Hand landmarks (skeleton) and mesh\n",
281
- "#\n",
282
- "# Left hand -> landmark line strips (skeleton)\n",
283
- "# Right hand -> triangular mesh\n",
284
- "\n",
285
- "from data_loaders.hand_common import LANDMARK_CONNECTIVITY\n",
286
- "\n",
287
- "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n",
288
- "\n",
289
- "rr.init(\"Hand Landmark / Mesh\")\n",
290
- "rec = rr.memory_recording()\n",
291
- "\n",
292
- "for timestamp_ns in tqdm(timestamps[:300]):\n",
293
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
294
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
295
- "\n",
296
- " if hand_data_provider is None:\n",
297
- " continue\n",
298
- " result = hand_data_provider.get_pose_at_timestamp(\n",
299
- " timestamp_ns=timestamp_ns,\n",
300
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
301
- " time_domain=TimeDomain.TIME_CODE,\n",
302
- " )\n",
303
- " if result is None:\n",
304
- " continue\n",
305
- "\n",
306
- " for hand_pose in result.pose3d_collection.poses.values():\n",
307
- " label = hand_pose.handedness_label()\n",
308
- "\n",
309
- " if hand_pose.is_left_hand():\n",
310
- " # Skeleton: connected landmark line strips\n",
311
- " landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n",
312
- " points = [\n",
313
- " [landmarks[i].numpy().tolist() for i in conn]\n",
314
- " for conn in LANDMARK_CONNECTIVITY\n",
315
- " ]\n",
316
- " rr.log(f\"world/{label}/joints\", rr.LineStrips3D(points, radii=0.002))\n",
317
- "\n",
318
- " else:\n",
319
- " # Mesh: vertices, triangle indices, and vertex normals\n",
320
- " verts = hand_data_provider.get_hand_mesh_vertices(hand_pose)\n",
321
- " triangles, normals = hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose)\n",
322
- " rr.log(\n",
323
- " f\"world/{label}/mesh\",\n",
324
- " rr.Mesh3D(\n",
325
- " vertex_positions=verts,\n",
326
- " vertex_normals=normals,\n",
327
- " triangle_indices=triangles,\n",
328
- " ),\n",
329
- " )\n",
330
- "\n",
331
- "rr.notebook_show()"
332
- ]
333
- },
334
- {
335
- "cell_type": "code",
336
- "execution_count": null,
337
- "id": "a909427f-d8c5-40a7-8eba-8702de2a313b",
338
- "metadata": {},
339
- "outputs": [],
340
- "source": [
341
- "# Section 2.c: Object poses\n",
342
- "# Requires object_library (assets folder). Skipped automatically if not available.\n",
343
- "\n",
344
- "if hot3d_data_provider._object_library is None:\n",
345
- " print(\"Skipping Section 2.c: object_library=None (no assets folder loaded)\")\n",
346
- "else:\n",
347
- " from data_loaders.loader_object_library import ObjectLibrary\n",
348
- " object_library = hot3d_data_provider._object_library\n",
349
- " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
350
- " object_cache_status = {}\n",
351
- "\n",
352
- " rr.init(\"Object pose\")\n",
353
- " rec = rr.memory_recording()\n",
354
- "\n",
355
- " for timestamp_ns in tqdm(timestamps[100:300]):\n",
356
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
357
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
358
- "\n",
359
- " result = object_pose_data_provider.get_pose_at_timestamp(\n",
360
- " timestamp_ns=timestamp_ns,\n",
361
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
362
- " time_domain=TimeDomain.TIME_CODE,\n",
363
- " )\n",
364
- " if result is None:\n",
365
- " continue\n",
366
- "\n",
367
- " object_uids = object_pose_data_provider.object_uids_with_poses\n",
368
- " logging_status = {x: False for x in object_uids}\n",
369
- "\n",
370
- " for object_uid, object_pose3d in result.pose3d_collection.poses.items():\n",
371
- " object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n",
372
- " log_pose(pose=object_pose3d.T_world_object, label=f\"world/objects/{object_name}\")\n",
373
- " logging_status[object_uid] = True\n",
374
- " if object_uid not in object_cache_status:\n",
375
- " object_cache_status[object_uid] = True\n",
376
- " asset_path = ObjectLibrary.get_cad_asset_path(\n",
377
- " object_library_folderpath=object_library.asset_folder_name,\n",
378
- " object_id=object_uid,\n",
379
- " )\n",
380
- " rr.log(f\"world/objects/{object_name}\", rr.Asset3D(path=asset_path))\n",
381
- "\n",
382
- " for object_uid, displayed in logging_status.items():\n",
383
- " if not displayed:\n",
384
- " object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n",
385
- " rr.log(f\"world/objects/{object_name}\", rr.Clear.recursive())\n",
386
- " object_cache_status.pop(object_uid, None)\n",
387
- "\n",
388
- " rr.notebook_show()"
389
- ]
390
- },
391
- {
392
- "cell_type": "code",
393
- "execution_count": null,
394
- "id": "f31214ce-108e-403e-b66f-2c224ab450f1",
395
- "metadata": {},
396
- "outputs": [],
397
- "source": [
398
- "# Section 3: 2D Bounding Boxes\n",
399
- "# Bbox data is queried by TIMESTAMP + STREAM_ID and contains an amodal bbox and a visibility ratio."
400
- ]
401
- },
402
- {
403
- "cell_type": "code",
404
- "execution_count": null,
405
- "id": "b841145d-a114-4693-a0d4-492f9629bbbe",
406
- "metadata": {},
407
- "outputs": [],
408
- "source": [
409
- "# Section 3.a: Object 2D bounding boxes\n",
410
- "# Requires object_library. Skipped automatically if not available.\n",
411
- "\n",
412
- "if hot3d_data_provider._object_library is None:\n",
413
- " print(\"Skipping Section 3.a: object_library=None\")\n",
414
- "else:\n",
415
- " import matplotlib.pyplot as plt\n",
416
- " object_library = hot3d_data_provider._object_library\n",
417
- " object_box2d_data_provider = hot3d_data_provider.object_box2d_data_provider\n",
418
- " object_uids = list(object_box2d_data_provider.object_uids)\n",
419
- " color_map = plt.get_cmap(\"viridis\")\n",
420
- " object_box2d_colors = color_map(np.linspace(0, 1, len(object_uids)))\n",
421
- "\n",
422
- " rr.init(\"Object bounding boxes\")\n",
423
- " rec = rr.memory_recording()\n",
424
- "\n",
425
- " stream_id = main_stream_id\n",
426
- " for timestamp_ns in tqdm(timestamps[100:200]):\n",
427
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
428
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
429
- "\n",
430
- " result = object_box2d_data_provider.get_bbox_at_timestamp(\n",
431
- " stream_id=stream_id,\n",
432
- " timestamp_ns=timestamp_ns,\n",
433
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
434
- " time_domain=TimeDomain.TIME_CODE,\n",
435
- " )\n",
436
- " if result is None or result.box2d_collection is None:\n",
437
- " continue\n",
438
- "\n",
439
- " for object_uid in result.box2d_collection.object_uid_list:\n",
440
- " object_name = object_library.object_id_to_name_dict[object_uid]\n",
441
- " ab = result.box2d_collection.box2ds[object_uid]\n",
442
- " bbox = ab.box2d\n",
443
- " if bbox is None:\n",
444
- " continue\n",
445
- " rr.log(\n",
446
- " f\"{stream_id}_raw/bbox/{object_name}\",\n",
447
- " rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n",
448
- " colors=object_box2d_colors[object_uids.index(object_uid)]),\n",
449
- " )\n",
450
- " rr.log(f\"visibility/{object_name}\", rr.Scalar(ab.visibility_ratio))\n",
451
- " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
452
- " if image_data is not None:\n",
453
- " log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
454
- "\n",
455
- " rr.notebook_show()"
456
- ]
457
- },
458
- {
459
- "cell_type": "code",
460
- "execution_count": null,
461
- "id": "0d1daf98-2df6-4d0a-ae38-331060353b99",
462
- "metadata": {},
463
- "outputs": [],
464
- "source": [
465
- "# Section 3.b: Hand 2D bounding boxes\n",
466
- "\n",
467
- "import matplotlib.pyplot as plt\n",
468
- "from data_loaders.loader_hand_poses import LEFT_HAND_INDEX, RIGHT_HAND_INDEX\n",
469
- "\n",
470
- "hand_box2d_data_provider = hot3d_data_provider.hand_box2d_data_provider\n",
471
- "hand_uids = [LEFT_HAND_INDEX, RIGHT_HAND_INDEX]\n",
472
- "hand_names = {LEFT_HAND_INDEX: \"left\", RIGHT_HAND_INDEX: \"right\"}\n",
473
- "color_map = plt.get_cmap(\"viridis\")\n",
474
- "hand_box2d_colors = color_map(np.linspace(0, 1, 2))\n",
475
- "\n",
476
- "rr.init(\"Hand bounding boxes\")\n",
477
- "rec = rr.memory_recording()\n",
478
- "\n",
479
- "stream_id = main_stream_id\n",
480
- "if stream_id not in hand_box2d_data_provider.stream_ids:\n",
481
- " print(f\"stream_id {stream_id} has no hand bbox data. Available: {hand_box2d_data_provider.stream_ids}\")\n",
482
- "\n",
483
- "for timestamp_ns in tqdm(timestamps[100:200]):\n",
484
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
485
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
486
- "\n",
487
- " result = hand_box2d_data_provider.get_bbox_at_timestamp(\n",
488
- " stream_id=stream_id,\n",
489
- " timestamp_ns=timestamp_ns,\n",
490
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
491
- " time_domain=TimeDomain.TIME_CODE,\n",
492
- " )\n",
493
- " if result is None or result.box2d_collection is None:\n",
494
- " continue\n",
495
- "\n",
496
- " for i, hand_uid in enumerate(hand_uids):\n",
497
- " ab = result.box2d_collection.box2ds[hand_uid]\n",
498
- " bbox = ab.box2d\n",
499
- " if bbox is None:\n",
500
- " continue\n",
501
- " hand_name = hand_names[hand_uid]\n",
502
- " rr.log(\n",
503
- " f\"{stream_id}_raw/bbox/{hand_name}\",\n",
504
- " rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n",
505
- " colors=hand_box2d_colors[i]),\n",
506
- " )\n",
507
- " rr.log(f\"visibility/{hand_name}\", rr.Scalar(ab.visibility_ratio))\n",
508
- " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
509
- " if image_data is not None:\n",
510
- " log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
511
- "\n",
512
- "rr.notebook_show()"
513
- ]
514
- },
515
- {
516
- "cell_type": "code",
517
- "execution_count": null,
518
- "id": "d8bad34e-a8ab-437d-84ff-1c046ca35d51",
519
- "metadata": {},
520
- "outputs": [],
521
- "source": [
522
- "# Section 4: Eye gaze (Aria only, skipped automatically on Quest3)\n",
523
- "\n",
524
- "if device_type != Headset.Aria:\n",
525
- " print(f\"Skipping Section 4: eye gaze is Aria-only (current device: {device_type})\")\n",
526
- "else:\n",
527
- " from projectaria_tools.core.calibration import FISHEYE624\n",
528
- "\n",
529
- " rr.init(\"Eye Gaze reprojection\")\n",
530
- " rec = rr.memory_recording()\n",
531
- "\n",
532
- " stream_id = StreamId(\"214-1\")\n",
533
- " for timestamp_ns in tqdm(timestamps[100:120]):\n",
534
- " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
535
- " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
536
- "\n",
537
- " eye_gaze = device_data_provider.get_eye_gaze(timestamp_ns)\n",
538
- " if eye_gaze is None:\n",
539
- " continue\n",
540
- "\n",
541
- " proj = device_data_provider.get_eye_gaze_in_camera(\n",
542
- " stream_id, timestamp_ns, camera_model=FISHEYE624\n",
543
- " )\n",
544
- " if proj is None or not proj.any():\n",
545
- " continue\n",
546
- "\n",
547
- " rr.log(f\"{stream_id}/eye-gaze\", rr.Points2D(proj, radii=20))\n",
548
- " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
549
- " if image_data is not None:\n",
550
- " log_image(label=str(stream_id), image=image_data)\n",
551
- "\n",
552
- " rr.notebook_show()"
553
- ]
554
- },
555
- {
556
- "cell_type": "code",
557
- "execution_count": null,
558
- "id": "b4d6ac37-e3b3-401a-83b7-e09a42a183a3",
559
- "metadata": {},
560
- "outputs": [],
561
- "source": [
562
- "# Section 5: Hand keypoint reprojection onto image\n",
563
- "#\n",
564
- "# Projects 3D world-space hand landmarks through the camera extrinsics + intrinsics\n",
565
- "# to obtain 2D pixel coordinates, then overlays them on the image.\n",
566
- "\n",
567
- "%matplotlib inline\n",
568
- "from matplotlib import pyplot as plt\n",
569
- "from typing import Any, Optional\n",
570
- "from data_loaders.HeadsetPose3dProvider import HeadsetPose3dProvider\n",
571
- "from data_loaders.loader_hand_poses import Handedness, HandPose3dCollection\n",
572
- "from projectaria_tools.core.calibration import CameraCalibration\n",
573
- "from projectaria_tools.core.sophus import SE3\n",
574
- "\n",
575
- "# Use a mid-sequence frame; clamp so the index is always valid\n",
576
- "frame_idx = min(420, len(timestamps) - 1)\n",
577
- "timestamp_ns = timestamps[frame_idx]\n",
578
- "image_streamid = main_stream_id # Aria -> 214-1, Quest3 -> 1201-1\n",
579
- "\n",
580
- "image_stream_label = device_data_provider.get_image_stream_label(image_streamid)\n",
581
- "image_data = device_data_provider.get_image(timestamp_ns, image_streamid)\n",
582
- "\n",
583
- "\n",
584
- "def get_hand_poses(ts):\n",
585
- " if hand_data_provider is None:\n",
586
- " return None\n",
587
- " result = hand_data_provider.get_pose_at_timestamp(\n",
588
- " timestamp_ns=ts,\n",
589
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
590
- " time_domain=TimeDomain.TIME_CODE,\n",
591
- " )\n",
592
- " return result.pose3d_collection if result else None\n",
593
- "\n",
594
- "\n",
595
- "def get_camera_pose(ts, stream_id):\n",
596
- " \"\"\"Returns (T_world_camera, intrinsics) or None.\"\"\"\n",
597
- " if device_pose_provider is None:\n",
598
- " return None\n",
599
- " result = device_pose_provider.get_pose_at_timestamp(\n",
600
- " timestamp_ns=ts,\n",
601
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
602
- " time_domain=TimeDomain.TIME_CODE,\n",
603
- " )\n",
604
- " if result is None:\n",
605
- " return None\n",
606
- " [T_device_camera, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
607
- " T_world_camera = result.pose3d.T_world_device @ T_device_camera\n",
608
- " return T_world_camera, intrinsics\n",
609
- "\n",
610
- "\n",
611
- "hand_data = get_hand_poses(timestamp_ns)\n",
612
- "camera_pose = get_camera_pose(timestamp_ns, image_streamid)\n",
613
- "\n",
614
- "if hand_data is None or camera_pose is None or image_data is None:\n",
615
- " print(\"Missing hand data, camera pose, or image — cannot project.\")\n",
616
- "else:\n",
617
- " T_world_camera, intrinsics = camera_pose\n",
618
- " plt.figure(figsize=(10, 8))\n",
619
- " plt.imshow(image_data, interpolation=\"nearest\")\n",
620
- " plt.title(f\"{image_stream_label} frame={frame_idx}\")\n",
621
- "\n",
622
- " for hand_pose in hand_data.poses.values():\n",
623
- " label = hand_pose.handedness_label()\n",
624
- " landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n",
625
- "\n",
626
- " # Gather all 3D points along the skeleton connectivity\n",
627
- " all_pts_3d = [\n",
628
- " landmarks[idx].numpy()\n",
629
- " for conn in LANDMARK_CONNECTIVITY\n",
630
- " for idx in conn\n",
631
- " ]\n",
632
- "\n",
633
- " # Project each 3D world point into the camera image plane\n",
634
- " projected = []\n",
635
- " for pt_world in all_pts_3d:\n",
636
- " pt_cam = T_world_camera.inverse() @ pt_world\n",
637
- " pt_2d = intrinsics.project(pt_cam)\n",
638
- " if pt_2d is not None:\n",
639
- " projected.append(pt_2d)\n",
640
- "\n",
641
- " color = 'r' if hand_pose.handedness == Handedness.Right else 'b'\n",
642
- " print(f\"{label} hand: {len(projected)} keypoints visible in image\")\n",
643
- " if projected:\n",
644
- " plt.scatter([p[0] for p in projected], [p[1] for p in projected],\n",
645
- " s=3, c=color, label=label)\n",
646
- "\n",
647
- " plt.legend()\n",
648
- " plt.axis('off')\n",
649
- " plt.tight_layout()\n",
650
- " plt.show()"
651
- ]
652
- },
653
- {
654
- "cell_type": "markdown",
655
- "id": "88f7a32a",
656
- "metadata": {},
657
- "source": [
658
- "#\n",
659
- "# Segmentation Code Sample\n",
660
- "#\n",
661
- "Written by Zhonghao Zhang (FKZZddd): \n",
662
- "This script was copied and adapted from the original script provided by Meta for HOT3D dataset. \n",
663
- "The original script can be found at HOT3D/hot3d/hot3d/render_3d.py in the HOT3D repository.\n",
664
- "\n",
665
- "Used for segmentation of hand meshes by restoring the hands pose and shape data on sense.\n",
666
- "setup_hand_at_timestamp is the main function that segments hands and adds hand meshes to the scene\n",
667
- "This script was tested on BOTH Aria and Quest3. By modifying sequence_folder=\"./dataset/P0002_2f137f83\". The script can detect the device type and load the corresponding data for rendering.\n",
668
- "#\n",
669
- "# Code Sample\n",
670
- "#\n",
671
- "Installation:\n",
672
- "- pip install pyrender trimesh\n",
673
- "#\n",
674
- "Details:\n",
675
- "Demonstrate how to use PyRender to render HOT3D meshes (objects, hands) for a given timestamp & stream_id\n",
676
- "- As OpenGL rendering is rectilinear, color, segmentation and depth buffer are also rectilinear rendering\n",
677
- "- We then show how to map the rectilinear image back to the original fisheye image (but do not we are loosing some field of view)"
678
- ]
679
- },
680
- {
681
- "cell_type": "code",
682
- "execution_count": null,
683
- "id": "b11b22eb",
684
- "metadata": {},
685
- "outputs": [],
686
- "source": [
687
- "from typing import Dict, List, Optional, Tuple\n",
688
- "\n",
689
- "import numpy as np\n",
690
- "\n",
691
- "try:\n",
692
- " import trimesh\n",
693
- " from pyrender import (\n",
694
- " IntrinsicsCamera,\n",
695
- " Mesh,\n",
696
- " Node,\n",
697
- " OffscreenRenderer,\n",
698
- " RenderFlags,\n",
699
- " Scene,\n",
700
- " )\n",
701
- "except ImportError:\n",
702
- " print(\"trimesh or pyrender modules are missing. Please install them.\")\n",
703
- "\n",
704
- "from data_loaders.HandDataProviderBase import HandDataProviderBase\n",
705
- "from data_loaders.headsets import Headset\n",
706
- "from data_loaders.loader_object_library import load_object_library, ObjectLibrary\n",
707
- "from dataset_api import Hot3dDataProvider\n",
708
- "from PIL import Image\n",
709
- "from projectaria_tools.core.calibration import (\n",
710
- " CameraCalibration,\n",
711
- " distort_by_calibration,\n",
712
- " FISHEYE624,\n",
713
- " LINEAR,\n",
714
- ")\n",
715
- "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n",
716
- "from projectaria_tools.core.sophus import SE3\n",
717
- "from projectaria_tools.core.stream_id import StreamId\n",
718
- "from tqdm import tqdm\n",
719
- "\n",
720
- "# Matrix transform to change Aria camera pose to PyRender coordinate system\n",
721
- "# PyRender: +Z = back, +Y = up, +X = right\n",
722
- "# Aria: +Z = forward, +Y = down, +X = right\n",
723
- "T_ARIA_OPENGL = SE3.from_matrix(\n",
724
- " np.array(\n",
725
- " [\n",
726
- " [1.0, 0.0, 0.0, 0.0],\n",
727
- " [0.0, -1.0, 0.0, 0.0],\n",
728
- " [0.0, 0.0, -1.0, 0.0],\n",
729
- " [0.0, 0.0, 0.0, 1.0],\n",
730
- " ]\n",
731
- " )\n",
732
- ")\n",
733
- "\n",
734
- "ACCEPTABLE_TIME_DELTA = 0 # To retrieve exact GT\n",
735
- "\n",
736
- "\n",
737
- "def load_meshes_scene(\n",
738
- " hot3d_data_provider: Hot3dDataProvider,\n",
739
- ") -> Dict[str, Mesh]:\n",
740
- " \"\"\"\n",
741
- " Load all meshes in the scene and hash them by object_uid\n",
742
- " \"\"\"\n",
743
- "\n",
744
- " object_library = hot3d_data_provider.object_library\n",
745
- " object_library_folderpath = object_library.asset_folder_name\n",
746
- "\n",
747
- " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
748
- " object_uids = object_pose_data_provider.object_uids_with_poses\n",
749
- "\n",
750
- " #\n",
751
- " # Load all meshes in the scene and store them in a dict\n",
752
- " #\n",
753
- " meshes: Dict[str, Mesh] = {}\n",
754
- " for object_uid in tqdm(object_uids):\n",
755
- " object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(\n",
756
- " object_library_folderpath=object_library_folderpath,\n",
757
- " object_id=object_uid,\n",
758
- " )\n",
759
- " # Load the mesh, merge its component\n",
760
- " scene = trimesh.load_mesh(\n",
761
- " object_cad_asset_filepath,\n",
762
- " process=True,\n",
763
- " merge_primitives=True,\n",
764
- " file_type=\"glb\",\n",
765
- " )\n",
766
- " # Represent the scene by a single mesh\n",
767
- " glb_mesh = scene.to_mesh()\n",
768
- " # Store the resulting mesh in the dict\n",
769
- " meshes[object_uid] = Mesh.from_trimesh(glb_mesh)\n",
770
- "\n",
771
- " return meshes\n",
772
- "\n",
773
- "\n",
774
- "def setup_objects_at_timestamp(\n",
775
- " scene: Scene,\n",
776
- " meshes: Dict[str, Mesh],\n",
777
- " hot3d_data_provider: Hot3dDataProvider,\n",
778
- " timestamp_ns: int,\n",
779
- ") -> Dict[str, Node]:\n",
780
- " \"\"\"\n",
781
- " Setup object meshes in the scene for the specified timestamp\n",
782
- " \"\"\"\n",
783
- "\n",
784
- " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
785
- "\n",
786
- " pyrender_node_meshes = {}\n",
787
- " object_poses_with_dt = None\n",
788
- " if object_pose_data_provider is not None:\n",
789
- " object_poses_with_dt = object_pose_data_provider.get_pose_at_timestamp(\n",
790
- " timestamp_ns=timestamp_ns,\n",
791
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
792
- " time_domain=TimeDomain.TIME_CODE,\n",
793
- " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
794
- " )\n",
795
- " if object_poses_with_dt is not None:\n",
796
- " objects_pose3d_collection = object_poses_with_dt.pose3d_collection\n",
797
- " for (\n",
798
- " object_uid,\n",
799
- " object_pose3d,\n",
800
- " ) in objects_pose3d_collection.poses.items():\n",
801
- " transform = object_pose3d.T_world_object.to_matrix()\n",
802
- " pyrender_node_meshes[object_uid] = scene.add(\n",
803
- " meshes[object_uid], pose=transform\n",
804
- " )\n",
805
- "\n",
806
- " return pyrender_node_meshes\n",
807
- "\n",
808
- "\n",
809
- "def get_camera_calibration(\n",
810
- " hot3d_data_provider: Hot3dDataProvider,\n",
811
- " timestamp_ns: int,\n",
812
- " stream_id: StreamId,\n",
813
- " camera_model=LINEAR,\n",
814
- ") -> Optional[Tuple[SE3, CameraCalibration]]:\n",
815
- " \"\"\"\n",
816
- " Return the camera calibration\n",
817
- " \"\"\"\n",
818
- " device_data_provider = hot3d_data_provider.device_data_provider\n",
819
- " if hot3d_data_provider.get_device_type() is Headset.Aria:\n",
820
- " return device_data_provider.get_online_camera_calibration(\n",
821
- " stream_id=stream_id,\n",
822
- " timestamp_ns=timestamp_ns,\n",
823
- " camera_model=camera_model,\n",
824
- " )\n",
825
- " elif hot3d_data_provider.get_device_type() is Headset.Quest3:\n",
826
- " return device_data_provider.get_camera_calibration(\n",
827
- " stream_id=stream_id,\n",
828
- " camera_model=camera_model,\n",
829
- " )\n",
830
- " else:\n",
831
- " return None\n",
832
- "\n",
833
- "\n",
834
- "def setup_camera_at_timestamp(\n",
835
- " scene: Scene,\n",
836
- " hot3d_data_provider: Hot3dDataProvider,\n",
837
- " timestamp_ns: int,\n",
838
- " stream_id: StreamId,\n",
839
- ") -> Tuple[Node, List[int]]:\n",
840
- " \"\"\"\n",
841
- " Setup a rectilinear camera for the specified stream_id and timestamp\n",
842
- " \"\"\"\n",
843
- "\n",
844
- " device_data_provider = hot3d_data_provider.device_data_provider\n",
845
- " device_pose_provider = hot3d_data_provider.device_pose_data_provider\n",
846
- "\n",
847
- " [T_device_camera, intrinsics] = get_camera_calibration(\n",
848
- " hot3d_data_provider=hot3d_data_provider,\n",
849
- " stream_id=stream_id,\n",
850
- " timestamp_ns=timestamp_ns,\n",
851
- " camera_model=LINEAR,\n",
852
- " )\n",
853
- "\n",
854
- " headset_pose3d_with_dt = None\n",
855
- " if device_data_provider is not None:\n",
856
- " headset_pose3d_with_dt = device_pose_provider.get_pose_at_timestamp(\n",
857
- " timestamp_ns=timestamp_ns,\n",
858
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
859
- " time_domain=TimeDomain.TIME_CODE,\n",
860
- " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
861
- " )\n",
862
- " if headset_pose3d_with_dt is not None:\n",
863
- " headset_pose3d = headset_pose3d_with_dt.pose3d\n",
864
- " focal_lengths = intrinsics.get_focal_lengths()\n",
865
- " principal_point = intrinsics.get_principal_point()\n",
866
- " camera = IntrinsicsCamera(\n",
867
- " focal_lengths[0],\n",
868
- " focal_lengths[0],\n",
869
- " principal_point[0],\n",
870
- " principal_point[1],\n",
871
- " znear=0.05,\n",
872
- " zfar=100.0,\n",
873
- " name=None,\n",
874
- " )\n",
875
- "\n",
876
- " camera_pose = (\n",
877
- " (headset_pose3d.T_world_device @ T_device_camera) @ T_ARIA_OPENGL\n",
878
- " ).to_matrix()\n",
879
- "\n",
880
- " camera_node = scene.add(camera, pose=camera_pose)\n",
881
- " return [camera_node, intrinsics.get_image_size().tolist()]\n",
882
- "\n",
883
- "\n",
884
- "def setup_hand_at_timestamp(\n",
885
- " scene: Scene,\n",
886
- " hot3d_data_provider: Hot3dDataProvider,\n",
887
- " timestamp_ns: int,\n",
888
- " hand_data_provider: HandDataProviderBase,\n",
889
- ") -> Dict[str, Mesh]:\n",
890
- " \"\"\"\n",
891
- " Add hand meshes to the scene for the specified timestamp\n",
892
- " \"\"\"\n",
893
- "\n",
894
- " pyrender_node_meshes = {}\n",
895
- "\n",
896
- " if hand_data_provider is None:\n",
897
- " return []\n",
898
- "\n",
899
- " hand_poses_with_dt = hand_data_provider.get_pose_at_timestamp(\n",
900
- " timestamp_ns=timestamp_ns,\n",
901
- " time_query_options=TimeQueryOptions.CLOSEST,\n",
902
- " time_domain=TimeDomain.TIME_CODE,\n",
903
- " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n",
904
- " )\n",
905
- " if hand_poses_with_dt is not None:\n",
906
- " hand_pose_collection = hand_poses_with_dt.pose3d_collection\n",
907
- "\n",
908
- " for hand_pose_data in hand_pose_collection.poses.values():\n",
909
- " handedness_label = hand_pose_data.handedness_label()\n",
910
- "\n",
911
- " hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(\n",
912
- " hand_pose_data\n",
913
- " )\n",
914
- "\n",
915
- " [hand_triangles, hand_vertex_normals] = (\n",
916
- " hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data)\n",
917
- " )\n",
918
- "\n",
919
- " pyrender_node_meshes[handedness_label] = scene.add(\n",
920
- " Mesh.from_trimesh(\n",
921
- " trimesh.Trimesh(\n",
922
- " vertices=hand_mesh_vertices,\n",
923
- " normals=hand_vertex_normals,\n",
924
- " faces=hand_triangles,\n",
925
- " )\n",
926
- " )\n",
927
- " )\n",
928
- " return pyrender_node_meshes\n",
929
- "\n",
930
- "\n",
931
- "def offscreen_render(\n",
932
- " scene: Scene,\n",
933
- " resolution: List[int], # [width, height]\n",
934
- ") -> Tuple[np.ndarray, np.ndarray]:\n",
935
- " \"\"\"\n",
936
- " Return COLOR and DEPTH images\n",
937
- " \"\"\"\n",
938
- " renderer = OffscreenRenderer(resolution[0], resolution[1])\n",
939
- " color, depth = renderer.render(scene) # , flags=RenderFlags.RGBA)\n",
940
- "\n",
941
- " nm = {\n",
942
- " node: 20 * (i + 1) for i, node in enumerate(scene.mesh_nodes)\n",
943
- " } # Node->Seg Id map\n",
944
- " seg = renderer.render(scene, RenderFlags.SEG, nm)[0]\n",
945
- "\n",
946
- " renderer.delete()\n",
947
- " return [color, depth, seg]\n",
948
- "\n",
949
- "\n",
950
- "def distort_rendering(\n",
951
- " image: np.ndarray,\n",
952
- " hot3d_data_provider: Hot3dDataProvider,\n",
953
- " timestamp_ns: int,\n",
954
- " stream_id: StreamId,\n",
955
- ") -> np.ndarray:\n",
956
- " \"\"\"\n",
957
- " Map a rectilinear image to the native Fisheye camera model.\n",
958
- " - Do notice that we are loosing some field of view.\n",
959
- " \"\"\"\n",
960
- "\n",
961
- " # Retrieve the camera model we want to distort to\n",
962
- " [T_device_camera, intrinsics_raw] = get_camera_calibration(\n",
963
- " hot3d_data_provider=hot3d_data_provider,\n",
964
- " stream_id=stream_id,\n",
965
- " timestamp_ns=timestamp_ns,\n",
966
- " camera_model=FISHEYE624,\n",
967
- " )\n",
968
- "\n",
969
- " # Retrieve the camera model we used for rendering\n",
970
- " [T_device_camera, intrinsics_linear] = get_camera_calibration(\n",
971
- " hot3d_data_provider=hot3d_data_provider,\n",
972
- " stream_id=stream_id,\n",
973
- " timestamp_ns=timestamp_ns,\n",
974
- " camera_model=LINEAR,\n",
975
- " )\n",
976
- "\n",
977
- " re_distorted_image = distort_by_calibration(\n",
978
- " image,\n",
979
- " intrinsics_raw,\n",
980
- " intrinsics_linear,\n",
981
- " )\n",
982
- "\n",
983
- " return re_distorted_image\n",
984
- "\n",
985
- "\n",
986
- "\n",
987
- "#The main function \n",
988
- "#Set object_library=None because object meshes are unnecessary for project.\n",
989
- "hot3d_data_provider = Hot3dDataProvider(\n",
990
- " # sequence_folder=\"./data_loaders/tests/data_sample/Aria/P0003_c701bd11\",\n",
991
- " sequence_folder=\"./dataset/P0002_2f137f83\",\n",
992
- " object_library=None,\n",
993
- ")\n",
994
- "print(f\"data_provider statistics: {hot3d_data_provider.get_data_statistics()}\")\n",
995
- "\n",
996
- "scene_meshes = {}\n",
997
- "\n",
998
- "# Define timestamps and stream ids that need rendering\n",
999
- "# Default attempts all stream ids and a timestamp in the middle of the sequence\n",
1000
- "\n",
1001
- "#total timestamps/2\n",
1002
- "timestamps = hot3d_data_provider.device_data_provider.get_sequence_timestamps()\n",
1003
- "timestamp_list = [timestamps[len(timestamps) // 2]]\n",
1004
- "stream_id_list = (\n",
1005
- " [StreamId(\"1201-1\"), StreamId(\"1201-2\"), StreamId(\"214-1\")]\n",
1006
- " if hot3d_data_provider.get_device_type() is Headset.Aria\n",
1007
- " else [StreamId(\"1201-1\"), StreamId(\"1201-2\")]\n",
1008
- ")\n",
1009
- "\n",
1010
- "# Main rendering loop\n",
1011
- "print(f\"Rendering for: {stream_id_list}\")\n",
1012
- "for stream_id in stream_id_list:\n",
1013
- " for timestamp_ns in timestamp_list:\n",
1014
- " # Initialize the scene\n",
1015
- " scene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))\n",
1016
- "\n",
1017
- " # Add hands into scene, the main function that do segmentation\n",
1018
- " setup_hand_at_timestamp(\n",
1019
- " scene=scene,\n",
1020
- " hot3d_data_provider=hot3d_data_provider,\n",
1021
- " timestamp_ns=timestamp_ns,\n",
1022
- " hand_data_provider=hot3d_data_provider.umetrack_hand_data_provider,\n",
1023
- " )\n",
1024
- "\n",
1025
- " # Setup camera rendering (for the specific stream_id and timestamp)\n",
1026
- " camera_node_and_resolution = setup_camera_at_timestamp(\n",
1027
- " scene=scene,\n",
1028
- " hot3d_data_provider=hot3d_data_provider,\n",
1029
- " timestamp_ns=timestamp_ns,\n",
1030
- " stream_id=stream_id,\n",
1031
- " )\n",
1032
- "\n",
1033
- " print(camera_node_and_resolution)\n",
1034
- " # Setup off screen rendering (to save rendering buffer to disk as image)\n",
1035
- " [color, depth, seg] = offscreen_render(scene, camera_node_and_resolution[1])\n",
1036
- "\n",
1037
- " camera_node_and_resolution = setup_camera_at_timestamp(\n",
1038
- " scene=scene,\n",
1039
- " hot3d_data_provider=hot3d_data_provider,\n",
1040
- " timestamp_ns=timestamp_ns,\n",
1041
- " stream_id=stream_id,\n",
1042
- " )\n",
1043
- " \n",
1044
- " im = Image.fromarray(color)\n",
1045
- " im.save(f\"render_native_{stream_id}_{timestamp_ns}.png\")\n",
1046
- "\n",
1047
- " # im = Image.fromarray(distorted_seg)\n",
1048
- " im = Image.fromarray(seg)\n",
1049
- " im.save(f\"seg_ref_{stream_id}_{timestamp_ns}.png\")\n",
1050
- "\n",
1051
- " # Save \"depth\" buffer\n",
1052
- " # im = Image.fromarray(depth)\n",
1053
- " # im.save(f\"depth_ref_{stream_id}_{timestamp_ns}.tiff\")\n",
1054
- "\n",
1055
- " image_data_raw = hot3d_data_provider.device_data_provider.get_image(\n",
1056
- " timestamp_ns, stream_id\n",
1057
- " )\n",
1058
- " if image_data_raw is not None:\n",
1059
- " im = Image.fromarray(image_data_raw)\n",
1060
- " im.save(f\"image_ref_{stream_id}_{timestamp_ns}.png\")"
1061
- ]
1062
- }
1063
- ],
1064
- "metadata": {
1065
- "kernelspec": {
1066
- "display_name": "hamer",
1067
- "language": "python",
1068
- "name": "python3"
1069
- },
1070
- "language_info": {
1071
- "codemirror_mode": {
1072
- "name": "ipython",
1073
- "version": 3
1074
- },
1075
- "file_extension": ".py",
1076
- "mimetype": "text/x-python",
1077
- "name": "python",
1078
- "nbconvert_exporter": "python",
1079
- "pygments_lexer": "ipython3",
1080
- "version": "3.10.20"
1081
- }
1082
- },
1083
- "nbformat": 4,
1084
- "nbformat_minor": 5
1085
- }
 
1
+ #Written by Zhonghao Zhang (FKZZddd):
2
+ # This script was copied and adapted from the original script provided by Meta for HOT3D dataset.
3
+ # The original script can be found at HOT3D/hot3d/hot3d/render_3d.py in the HOT3D repository.
4
+
5
+ # Used for segmentation of hand meshes,
6
+ # setup_hand_at_timestamp is the main function that segments hands and adds hand meshes to the scene
7
+ # This script was tested on BOTH Aria and Quest3. By modifying sequence_folder="./dataset/P0002_2f137f83". The script can detect the device type and load the corresponding data for rendering.
8
+ #
9
+ # Code Sample
10
+ #
11
+ # Installation:
12
+ # - pip install pyrender trimesh
13
+ #
14
+ # Details:
15
+ # Demonstrate how to use PyRender to render HOT3D meshes (objects, hands) for a given timestamp & stream_id
16
+ # - As OpenGL rendering is rectilinear, color, segmentation and depth buffer are also rectilinear rendering
17
+ # - We then show how to map the rectilinear image back to the original fisheye image (but do not we are loosing some field of view)
18
+
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ import numpy as np
22
+
23
+ try:
24
+ import trimesh
25
+ from pyrender import (
26
+ IntrinsicsCamera,
27
+ Mesh,
28
+ Node,
29
+ OffscreenRenderer,
30
+ RenderFlags,
31
+ Scene,
32
+ )
33
+ except ImportError:
34
+ print("trimesh or pyrender modules are missing. Please install them.")
35
+
36
+ from data_loaders.HandDataProviderBase import HandDataProviderBase
37
+ from data_loaders.headsets import Headset
38
+ from data_loaders.loader_object_library import load_object_library, ObjectLibrary
39
+ from dataset_api import Hot3dDataProvider
40
+ from PIL import Image
41
+ from projectaria_tools.core.calibration import (
42
+ CameraCalibration,
43
+ distort_by_calibration,
44
+ FISHEYE624,
45
+ LINEAR,
46
+ )
47
+ from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions
48
+ from projectaria_tools.core.sophus import SE3
49
+ from projectaria_tools.core.stream_id import StreamId
50
+ from tqdm import tqdm
51
+
52
+ # Matrix transform to change Aria camera pose to PyRender coordinate system
53
+ # PyRender: +Z = back, +Y = up, +X = right
54
+ # Aria: +Z = forward, +Y = down, +X = right
55
+ T_ARIA_OPENGL = SE3.from_matrix(
56
+ np.array(
57
+ [
58
+ [1.0, 0.0, 0.0, 0.0],
59
+ [0.0, -1.0, 0.0, 0.0],
60
+ [0.0, 0.0, -1.0, 0.0],
61
+ [0.0, 0.0, 0.0, 1.0],
62
+ ]
63
+ )
64
+ )
65
+
66
+ ACCEPTABLE_TIME_DELTA = 0 # To retrieve exact GT
67
+
68
+
69
+ def load_meshes_scene(
70
+ hot3d_data_provider: Hot3dDataProvider,
71
+ ) -> Dict[str, Mesh]:
72
+ """
73
+ Load all meshes in the scene and hash them by object_uid
74
+ """
75
+
76
+ object_library = hot3d_data_provider.object_library
77
+ object_library_folderpath = object_library.asset_folder_name
78
+
79
+ object_pose_data_provider = hot3d_data_provider.object_pose_data_provider
80
+ object_uids = object_pose_data_provider.object_uids_with_poses
81
+
82
+ #
83
+ # Load all meshes in the scene and store them in a dict
84
+ #
85
+ meshes: Dict[str, Mesh] = {}
86
+ for object_uid in tqdm(object_uids):
87
+ object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(
88
+ object_library_folderpath=object_library_folderpath,
89
+ object_id=object_uid,
90
+ )
91
+ # Load the mesh, merge its component
92
+ scene = trimesh.load_mesh(
93
+ object_cad_asset_filepath,
94
+ process=True,
95
+ merge_primitives=True,
96
+ file_type="glb",
97
+ )
98
+ # Represent the scene by a single mesh
99
+ glb_mesh = scene.to_mesh()
100
+ # Store the resulting mesh in the dict
101
+ meshes[object_uid] = Mesh.from_trimesh(glb_mesh)
102
+
103
+ return meshes
104
+
105
+
106
+ def setup_objects_at_timestamp(
107
+ scene: Scene,
108
+ meshes: Dict[str, Mesh],
109
+ hot3d_data_provider: Hot3dDataProvider,
110
+ timestamp_ns: int,
111
+ ) -> Dict[str, Node]:
112
+ """
113
+ Setup object meshes in the scene for the specified timestamp
114
+ """
115
+
116
+ object_pose_data_provider = hot3d_data_provider.object_pose_data_provider
117
+
118
+ pyrender_node_meshes = {}
119
+ object_poses_with_dt = None
120
+ if object_pose_data_provider is not None:
121
+ object_poses_with_dt = object_pose_data_provider.get_pose_at_timestamp(
122
+ timestamp_ns=timestamp_ns,
123
+ time_query_options=TimeQueryOptions.CLOSEST,
124
+ time_domain=TimeDomain.TIME_CODE,
125
+ acceptable_time_delta=ACCEPTABLE_TIME_DELTA,
126
+ )
127
+ if object_poses_with_dt is not None:
128
+ objects_pose3d_collection = object_poses_with_dt.pose3d_collection
129
+ for (
130
+ object_uid,
131
+ object_pose3d,
132
+ ) in objects_pose3d_collection.poses.items():
133
+ transform = object_pose3d.T_world_object.to_matrix()
134
+ pyrender_node_meshes[object_uid] = scene.add(
135
+ meshes[object_uid], pose=transform
136
+ )
137
+
138
+ return pyrender_node_meshes
139
+
140
+
141
+ def get_camera_calibration(
142
+ hot3d_data_provider: Hot3dDataProvider,
143
+ timestamp_ns: int,
144
+ stream_id: StreamId,
145
+ camera_model=LINEAR,
146
+ ) -> Optional[Tuple[SE3, CameraCalibration]]:
147
+ """
148
+ Return the camera calibration
149
+ """
150
+ device_data_provider = hot3d_data_provider.device_data_provider
151
+ if hot3d_data_provider.get_device_type() is Headset.Aria:
152
+ return device_data_provider.get_online_camera_calibration(
153
+ stream_id=stream_id,
154
+ timestamp_ns=timestamp_ns,
155
+ camera_model=camera_model,
156
+ )
157
+ elif hot3d_data_provider.get_device_type() is Headset.Quest3:
158
+ return device_data_provider.get_camera_calibration(
159
+ stream_id=stream_id,
160
+ camera_model=camera_model,
161
+ )
162
+ else:
163
+ return None
164
+
165
+
166
+ def setup_camera_at_timestamp(
167
+ scene: Scene,
168
+ hot3d_data_provider: Hot3dDataProvider,
169
+ timestamp_ns: int,
170
+ stream_id: StreamId,
171
+ ) -> Tuple[Node, List[int]]:
172
+ """
173
+ Setup a rectilinear camera for the specified stream_id and timestamp
174
+ """
175
+
176
+ device_data_provider = hot3d_data_provider.device_data_provider
177
+ device_pose_provider = hot3d_data_provider.device_pose_data_provider
178
+
179
+ [T_device_camera, intrinsics] = get_camera_calibration(
180
+ hot3d_data_provider=hot3d_data_provider,
181
+ stream_id=stream_id,
182
+ timestamp_ns=timestamp_ns,
183
+ camera_model=LINEAR,
184
+ )
185
+
186
+ headset_pose3d_with_dt = None
187
+ if device_data_provider is not None:
188
+ headset_pose3d_with_dt = device_pose_provider.get_pose_at_timestamp(
189
+ timestamp_ns=timestamp_ns,
190
+ time_query_options=TimeQueryOptions.CLOSEST,
191
+ time_domain=TimeDomain.TIME_CODE,
192
+ acceptable_time_delta=ACCEPTABLE_TIME_DELTA,
193
+ )
194
+ if headset_pose3d_with_dt is not None:
195
+ headset_pose3d = headset_pose3d_with_dt.pose3d
196
+ focal_lengths = intrinsics.get_focal_lengths()
197
+ principal_point = intrinsics.get_principal_point()
198
+ camera = IntrinsicsCamera(
199
+ focal_lengths[0],
200
+ focal_lengths[0],
201
+ principal_point[0],
202
+ principal_point[1],
203
+ znear=0.05,
204
+ zfar=100.0,
205
+ name=None,
206
+ )
207
+
208
+ camera_pose = (
209
+ (headset_pose3d.T_world_device @ T_device_camera) @ T_ARIA_OPENGL
210
+ ).to_matrix()
211
+
212
+ camera_node = scene.add(camera, pose=camera_pose)
213
+ return [camera_node, intrinsics.get_image_size().tolist()]
214
+
215
+
216
+ def setup_hand_at_timestamp(
217
+ scene: Scene,
218
+ hot3d_data_provider: Hot3dDataProvider,
219
+ timestamp_ns: int,
220
+ hand_data_provider: HandDataProviderBase,
221
+ ) -> Dict[str, Mesh]:
222
+ """
223
+ Add hand meshes to the scene for the specified timestamp
224
+ """
225
+
226
+ pyrender_node_meshes = {}
227
+
228
+ if hand_data_provider is None:
229
+ return []
230
+
231
+ hand_poses_with_dt = hand_data_provider.get_pose_at_timestamp(
232
+ timestamp_ns=timestamp_ns,
233
+ time_query_options=TimeQueryOptions.CLOSEST,
234
+ time_domain=TimeDomain.TIME_CODE,
235
+ acceptable_time_delta=ACCEPTABLE_TIME_DELTA,
236
+ )
237
+ if hand_poses_with_dt is not None:
238
+ hand_pose_collection = hand_poses_with_dt.pose3d_collection
239
+
240
+ for hand_pose_data in hand_pose_collection.poses.values():
241
+ handedness_label = hand_pose_data.handedness_label()
242
+
243
+ hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(
244
+ hand_pose_data
245
+ )
246
+
247
+ [hand_triangles, hand_vertex_normals] = (
248
+ hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data)
249
+ )
250
+
251
+ pyrender_node_meshes[handedness_label] = scene.add(
252
+ Mesh.from_trimesh(
253
+ trimesh.Trimesh(
254
+ vertices=hand_mesh_vertices,
255
+ normals=hand_vertex_normals,
256
+ faces=hand_triangles,
257
+ )
258
+ )
259
+ )
260
+ return pyrender_node_meshes
261
+
262
+
263
+ def offscreen_render(
264
+ scene: Scene,
265
+ resolution: List[int], # [width, height]
266
+ ) -> Tuple[np.ndarray, np.ndarray]:
267
+ """
268
+ Return COLOR and DEPTH images
269
+ """
270
+ renderer = OffscreenRenderer(resolution[0], resolution[1])
271
+ color, depth = renderer.render(scene) # , flags=RenderFlags.RGBA)
272
+
273
+ nm = {
274
+ node: 20 * (i + 1) for i, node in enumerate(scene.mesh_nodes)
275
+ } # Node->Seg Id map
276
+ seg = renderer.render(scene, RenderFlags.SEG, nm)[0]
277
+
278
+ renderer.delete()
279
+ return [color, depth, seg]
280
+
281
+
282
+ def distort_rendering(
283
+ image: np.ndarray,
284
+ hot3d_data_provider: Hot3dDataProvider,
285
+ timestamp_ns: int,
286
+ stream_id: StreamId,
287
+ ) -> np.ndarray:
288
+ """
289
+ Map a rectilinear image to the native Fisheye camera model.
290
+ - Do notice that we are loosing some field of view.
291
+ """
292
+
293
+ # Retrieve the camera model we want to distort to
294
+ [T_device_camera, intrinsics_raw] = get_camera_calibration(
295
+ hot3d_data_provider=hot3d_data_provider,
296
+ stream_id=stream_id,
297
+ timestamp_ns=timestamp_ns,
298
+ camera_model=FISHEYE624,
299
+ )
300
+
301
+ # Retrieve the camera model we used for rendering
302
+ [T_device_camera, intrinsics_linear] = get_camera_calibration(
303
+ hot3d_data_provider=hot3d_data_provider,
304
+ stream_id=stream_id,
305
+ timestamp_ns=timestamp_ns,
306
+ camera_model=LINEAR,
307
+ )
308
+
309
+ re_distorted_image = distort_by_calibration(
310
+ image,
311
+ intrinsics_raw,
312
+ intrinsics_linear,
313
+ )
314
+
315
+ return re_distorted_image
316
+
317
+
318
+
319
+ #The main function
320
+ #Set object_library=None because object meshes are unnecessary for project.
321
+ hot3d_data_provider = Hot3dDataProvider(
322
+ # sequence_folder="./data_loaders/tests/data_sample/Aria/P0003_c701bd11",
323
+ sequence_folder="./dataset/P0002_2f137f83",
324
+ object_library=None,
325
+ )
326
+ print(f"data_provider statistics: {hot3d_data_provider.get_data_statistics()}")
327
+
328
+ scene_meshes = {}
329
+
330
+ # Define timestamps and stream ids that need rendering
331
+ # Default attempts all stream ids and a timestamp in the middle of the sequence
332
+
333
+ #total timestamps/2
334
+ timestamps = hot3d_data_provider.device_data_provider.get_sequence_timestamps()
335
+ timestamp_list = [timestamps[len(timestamps) // 2]]
336
+ stream_id_list = (
337
+ [StreamId("1201-1"), StreamId("1201-2"), StreamId("214-1")]
338
+ if hot3d_data_provider.get_device_type() is Headset.Aria
339
+ else [StreamId("1201-1"), StreamId("1201-2")]
340
+ )
341
+
342
+ # Main rendering loop
343
+ print(f"Rendering for: {stream_id_list}")
344
+ for stream_id in stream_id_list:
345
+ for timestamp_ns in timestamp_list:
346
+ # Initialize the scene
347
+ scene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))
348
+
349
+ # Add hands into scene, the main function that do segmentation
350
+ setup_hand_at_timestamp(
351
+ scene=scene,
352
+ hot3d_data_provider=hot3d_data_provider,
353
+ timestamp_ns=timestamp_ns,
354
+ hand_data_provider=hot3d_data_provider.umetrack_hand_data_provider,
355
+ )
356
+
357
+ # Setup camera rendering (for the specific stream_id and timestamp)
358
+ camera_node_and_resolution = setup_camera_at_timestamp(
359
+ scene=scene,
360
+ hot3d_data_provider=hot3d_data_provider,
361
+ timestamp_ns=timestamp_ns,
362
+ stream_id=stream_id,
363
+ )
364
+
365
+ print(camera_node_and_resolution)
366
+ # Setup off screen rendering (to save rendering buffer to disk as image)
367
+ [color, depth, seg] = offscreen_render(scene, camera_node_and_resolution[1])
368
+
369
+ camera_node_and_resolution = setup_camera_at_timestamp(
370
+ scene=scene,
371
+ hot3d_data_provider=hot3d_data_provider,
372
+ timestamp_ns=timestamp_ns,
373
+ stream_id=stream_id,
374
+ )
375
+
376
+ im = Image.fromarray(color)
377
+ im.save(f"render_native_{stream_id}_{timestamp_ns}.png")
378
+
379
+ # im = Image.fromarray(distorted_seg)
380
+ im = Image.fromarray(seg)
381
+ im.save(f"seg_ref_{stream_id}_{timestamp_ns}.png")
382
+
383
+ # Save "depth" buffer
384
+ # im = Image.fromarray(depth)
385
+ # im.save(f"depth_ref_{stream_id}_{timestamp_ns}.tiff")
386
+
387
+ image_data_raw = hot3d_data_provider.device_data_provider.get_image(
388
+ timestamp_ns, stream_id
389
+ )
390
+ if image_data_raw is not None:
391
+ im = Image.fromarray(image_data_raw)
392
+ im.save(f"image_ref_{stream_id}_{timestamp_ns}.png")