{ "cells": [ { "cell_type": "markdown", "id": "ee215408-e60b-4209-a09a-f84a8fd5ffa1", "metadata": {}, "source": [ "# HOT3D Data Reader\n", "\n", "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", "\n", "## Sections\n", "- **Section 0**: Initialization (update the two paths, then run)\n", "- **Section 1**: Image streams + camera calibration\n", "- **Section 2.a**: Device / headset pose trajectory\n", "- **Section 2.b**: Hand wrist trajectory\n", "- **Section 2.b.a**: Hand landmarks (skeleton) + mesh\n", "- **Section 2.c**: Object poses (requires assets folder, skipped automatically otherwise)\n", "- **Section 3.b**: Hand 2D bounding boxes\n", "- **Section 4**: Eye gaze (Aria only, skipped automatically on Quest3)\n", "- **Section 5**: Hand keypoint reprojection onto image\n", "\n", "```\n", "Hot3dDataProvider\n", "|- device_data_provider -> image data + camera calibration\n", "|- device_pose_data_provider -> device pose\n", "|- mano_hand_data_provider -> hand pose (MANO)\n", "|- object_pose_data_provider -> object pose\n", "|- hand_box2d_data_provider -> hand 2D bounding boxes\n", "|- object_box2d_data_provider -> object 2D bounding boxes\n", "```\n", "\n", "> All pose data is in **world coordinates** (meters)." ] }, { "cell_type": "code", "execution_count": null, "id": "97bcb96c-4910-4a60-9a41-c3b34ee7ac7b", "metadata": {}, "outputs": [], "source": [ "# Section 0: DataProvider initialization\n", "#\n", "# Only the two paths below need to be updated; everything else adapts automatically\n", "# to Aria or Quest3.\n", "\n", "import os\n", "import sys\n", "\n", "# Make sure the hot3d package is importable from this notebook\n", "notebook_dir = os.path.abspath('')\n", "if notebook_dir not in sys.path:\n", " sys.path.insert(0, notebook_dir)\n", "\n", "from dataset_api import Hot3dDataProvider\n", "from data_loaders.mano_layer import MANOHandModel\n", "from data_loaders.headsets import Headset\n", "from projectaria_tools.core.stream_id import StreamId\n", "\n", "# ── Update these two paths ───────────────────────────────────────\n", "sequence_path = \"/home/zhang/3D_Reconstruct/HOT3D/hot3d/hot3d/dataset/P0002_2f137f83\"\n", "mano_model_path = \"/home/zhang/Downloads/mano_v1_2/models\"\n", "# ────────────────────────────────────────────────────────────────\n", "\n", "# Load MANO hand model (requires smplx: pip install smplx)\n", "mano_hand_model = MANOHandModel(mano_model_path)\n", "\n", "# Initialize the data provider.\n", "# object_library=None: no assets folder needed when only reading hand data.\n", "hot3d_data_provider = Hot3dDataProvider(\n", " sequence_folder=sequence_path,\n", " object_library=None,\n", " mano_hand_model=mano_hand_model,\n", ")\n", "\n", "# Auto-detect device type and pick the corresponding primary camera stream_id\n", "device_type = hot3d_data_provider.get_device_type()\n", "print(f\"Device type: {device_type}\")\n", "\n", "if device_type == Headset.Aria:\n", " main_stream_id = StreamId(\"214-1\") # Aria: RGB camera\n", "else:\n", " main_stream_id = StreamId(\"1201-1\") # Quest3: SLAM Left camera\n", "\n", "print(f\"Primary stream_id: {main_stream_id}\")\n", "print(f\"Data statistics: {hot3d_data_provider.get_data_statistics()}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "24dae021-1cfe-440a-a5c8-6f44851219e7", "metadata": {}, "outputs": [], "source": [ "# Utility functions for Rerun visualization\n", "\n", "import rerun as rr\n", "import numpy as np\n", "from projectaria_tools.core.sophus import SE3\n", "from projectaria_tools.utils.rerun_helpers import ToTransform3D\n", "\n", "\n", "def log_image(image: np.array, label: str, static=False) -> None:\n", " rr.log(label, rr.Image(image), static=static)\n", "\n", "\n", "def log_pose(pose: SE3, label: str, static=False) -> None:\n", " rr.log(label, ToTransform3D(pose, False), static=static)" ] }, { "cell_type": "code", "execution_count": null, "id": "c7447d83-bf07-4bfb-8e4f-9d548617cde7", "metadata": {}, "outputs": [], "source": [ "# Section 1: Image streams + camera calibration\n", "\n", "from tqdm import tqdm\n", "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n", "\n", "device_data_provider = hot3d_data_provider.device_data_provider\n", "image_stream_ids = device_data_provider.get_image_stream_ids()\n", "\n", "# Timestamp retrieval differs between Aria and Quest3\n", "if device_type == Headset.Aria:\n", " timestamps = device_data_provider.get_sequence_timestamps(\n", " stream_id=main_stream_id,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", "else:\n", " timestamps = device_data_provider.get_sequence_timestamps()\n", "\n", "print(f\"Sequence : {os.path.basename(os.path.normpath(sequence_path))}\")\n", "print(f\"Streams : {image_stream_ids}\")\n", "print(f\"Frames : {len(timestamps)}\")\n", "\n", "rr.init(\"Device images\")\n", "rec = rr.memory_recording()\n", "\n", "# Sample one frame every 200 timestamps to keep the visualization fast\n", "for timestamp_ns in tqdm(timestamps[::200]):\n", " for stream_id in image_stream_ids:\n", " image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n", " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n", " if image_data is not None:\n", " log_image(label=f\"img/{image_stream_label}\", image=image_data)\n", "\n", "# Print calibration parameters for each camera stream\n", "for stream_id in image_stream_ids:\n", " [extrinsics, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n", " label = device_data_provider.get_image_stream_label(stream_id)\n", " print(f\"\\n[{label}] intrinsics: {intrinsics}\")\n", "\n", "rr.notebook_show()" ] }, { "cell_type": "markdown", "id": "1d199e9c-7359-43b2-8ecd-807db548def0", "metadata": {}, "source": [ "# GT Data Provider API\n", "\n", "All GT data providers share the same query interface:\n", "```python\n", "result = provider.get_X_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", ")\n", "```\n", "- If the exact timestamp is not found, the **closest** sample is returned.\n", "- The delta time (`dt`) between the queried and returned timestamp is also available.\n", "\n", "Available providers:\n", "```\n", "|- device_pose_data_provider -> device/headset pose\n", "|- mano_hand_data_provider -> hand pose (MANO)\n", "|- object_pose_data_provider -> object pose\n", "|- hand_box2d_data_provider -> hand 2D bbox + visibility\n", "|- object_box2d_data_provider -> object 2D bbox + visibility\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "a7c473c3-174f-4cff-9d58-0650b580da72", "metadata": {}, "outputs": [], "source": [ "# Section 2.a: Device / headset pose trajectory\n", "\n", "device_pose_provider = hot3d_data_provider.device_pose_data_provider\n", "\n", "rr.init(\"Device/Headset trajectory\")\n", "rec = rr.memory_recording()\n", "\n", "pose_translations = []\n", "for timestamp_ns in tqdm(timestamps):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " if device_pose_provider is None:\n", " continue\n", " result = device_pose_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None:\n", " continue\n", "\n", " T_world_device = result.pose3d.T_world_device\n", " log_pose(pose=T_world_device, label=\"world/device\")\n", " pose_translations.append(T_world_device.translation()[0])\n", "\n", "rr.log(\"world/device_trajectory\", rr.LineStrips3D([pose_translations]), static=True)\n", "rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "d5253618-2ca2-4d11-a605-aa5aa19c54eb", "metadata": {}, "outputs": [], "source": [ "# Section 2.b: Hand wrist trajectory (MANO only)\n", "\n", "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n", "if hand_data_provider is None:\n", " print(\"MANO hand data provider not initialized. Check mano_model_path and smplx installation.\")\n", "\n", "rr.init(\"Hand wrist trajectory\")\n", "rec = rr.memory_recording()\n", "\n", "left_traj, right_traj = [], []\n", "for timestamp_ns in tqdm(timestamps):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " if hand_data_provider is None:\n", " continue\n", " result = hand_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None:\n", " continue\n", "\n", " for hand_pose in result.pose3d_collection.poses.values():\n", " label = hand_pose.handedness_label()\n", " T_world_wrist = hand_pose.wrist_pose\n", " log_pose(pose=T_world_wrist, label=f\"world/hand/{label}\")\n", " if hand_pose.is_left_hand():\n", " left_traj.append(T_world_wrist.translation()[0])\n", " else:\n", " right_traj.append(T_world_wrist.translation()[0])\n", "\n", "if left_traj:\n", " rr.log(\"world/left_hand_traj\", rr.LineStrips3D([left_traj]), static=True)\n", "if right_traj:\n", " rr.log(\"world/right_hand_traj\", rr.LineStrips3D([right_traj]), static=True)\n", "rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "0a013c63-65e6-4c38-b378-141c8c7ae3ae", "metadata": {}, "outputs": [], "source": [ "# Section 2.b.a: Hand landmarks (skeleton) and mesh\n", "#\n", "# Left hand -> landmark line strips (skeleton)\n", "# Right hand -> triangular mesh\n", "\n", "from data_loaders.hand_common import LANDMARK_CONNECTIVITY\n", "\n", "hand_data_provider = hot3d_data_provider.mano_hand_data_provider\n", "\n", "rr.init(\"Hand Landmark / Mesh\")\n", "rec = rr.memory_recording()\n", "\n", "for timestamp_ns in tqdm(timestamps[:300]):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " if hand_data_provider is None:\n", " continue\n", " result = hand_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None:\n", " continue\n", "\n", " for hand_pose in result.pose3d_collection.poses.values():\n", " label = hand_pose.handedness_label()\n", "\n", " if hand_pose.is_left_hand():\n", " # Skeleton: connected landmark line strips\n", " landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n", " points = [\n", " [landmarks[i].numpy().tolist() for i in conn]\n", " for conn in LANDMARK_CONNECTIVITY\n", " ]\n", " rr.log(f\"world/{label}/joints\", rr.LineStrips3D(points, radii=0.002))\n", "\n", " else:\n", " # Mesh: vertices, triangle indices, and vertex normals\n", " verts = hand_data_provider.get_hand_mesh_vertices(hand_pose)\n", " triangles, normals = hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose)\n", " rr.log(\n", " f\"world/{label}/mesh\",\n", " rr.Mesh3D(\n", " vertex_positions=verts,\n", " vertex_normals=normals,\n", " triangle_indices=triangles,\n", " ),\n", " )\n", "\n", "rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "a909427f-d8c5-40a7-8eba-8702de2a313b", "metadata": {}, "outputs": [], "source": [ "# Section 2.c: Object poses\n", "# Requires object_library (assets folder). Skipped automatically if not available.\n", "\n", "if hot3d_data_provider._object_library is None:\n", " print(\"Skipping Section 2.c: object_library=None (no assets folder loaded)\")\n", "else:\n", " from data_loaders.loader_object_library import ObjectLibrary\n", " object_library = hot3d_data_provider._object_library\n", " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n", " object_cache_status = {}\n", "\n", " rr.init(\"Object pose\")\n", " rec = rr.memory_recording()\n", "\n", " for timestamp_ns in tqdm(timestamps[100:300]):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " result = object_pose_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None:\n", " continue\n", "\n", " object_uids = object_pose_data_provider.object_uids_with_poses\n", " logging_status = {x: False for x in object_uids}\n", "\n", " for object_uid, object_pose3d in result.pose3d_collection.poses.items():\n", " object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n", " log_pose(pose=object_pose3d.T_world_object, label=f\"world/objects/{object_name}\")\n", " logging_status[object_uid] = True\n", " if object_uid not in object_cache_status:\n", " object_cache_status[object_uid] = True\n", " asset_path = ObjectLibrary.get_cad_asset_path(\n", " object_library_folderpath=object_library.asset_folder_name,\n", " object_id=object_uid,\n", " )\n", " rr.log(f\"world/objects/{object_name}\", rr.Asset3D(path=asset_path))\n", "\n", " for object_uid, displayed in logging_status.items():\n", " if not displayed:\n", " object_name = object_library.object_id_to_name_dict[object_uid] + \"_\" + str(object_uid)\n", " rr.log(f\"world/objects/{object_name}\", rr.Clear.recursive())\n", " object_cache_status.pop(object_uid, None)\n", "\n", " rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "f31214ce-108e-403e-b66f-2c224ab450f1", "metadata": {}, "outputs": [], "source": [ "# Section 3: 2D Bounding Boxes\n", "# Bbox data is queried by TIMESTAMP + STREAM_ID and contains an amodal bbox and a visibility ratio." ] }, { "cell_type": "code", "execution_count": null, "id": "b841145d-a114-4693-a0d4-492f9629bbbe", "metadata": {}, "outputs": [], "source": [ "# Section 3.a: Object 2D bounding boxes\n", "# Requires object_library. Skipped automatically if not available.\n", "\n", "if hot3d_data_provider._object_library is None:\n", " print(\"Skipping Section 3.a: object_library=None\")\n", "else:\n", " import matplotlib.pyplot as plt\n", " object_library = hot3d_data_provider._object_library\n", " object_box2d_data_provider = hot3d_data_provider.object_box2d_data_provider\n", " object_uids = list(object_box2d_data_provider.object_uids)\n", " color_map = plt.get_cmap(\"viridis\")\n", " object_box2d_colors = color_map(np.linspace(0, 1, len(object_uids)))\n", "\n", " rr.init(\"Object bounding boxes\")\n", " rec = rr.memory_recording()\n", "\n", " stream_id = main_stream_id\n", " for timestamp_ns in tqdm(timestamps[100:200]):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " result = object_box2d_data_provider.get_bbox_at_timestamp(\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None or result.box2d_collection is None:\n", " continue\n", "\n", " for object_uid in result.box2d_collection.object_uid_list:\n", " object_name = object_library.object_id_to_name_dict[object_uid]\n", " ab = result.box2d_collection.box2ds[object_uid]\n", " bbox = ab.box2d\n", " if bbox is None:\n", " continue\n", " rr.log(\n", " f\"{stream_id}_raw/bbox/{object_name}\",\n", " rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n", " colors=object_box2d_colors[object_uids.index(object_uid)]),\n", " )\n", " rr.log(f\"visibility/{object_name}\", rr.Scalar(ab.visibility_ratio))\n", " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n", " if image_data is not None:\n", " log_image(label=f\"{stream_id}_raw\", image=image_data)\n", "\n", " rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "0d1daf98-2df6-4d0a-ae38-331060353b99", "metadata": {}, "outputs": [], "source": [ "# Section 3.b: Hand 2D bounding boxes\n", "\n", "import matplotlib.pyplot as plt\n", "from data_loaders.loader_hand_poses import LEFT_HAND_INDEX, RIGHT_HAND_INDEX\n", "\n", "hand_box2d_data_provider = hot3d_data_provider.hand_box2d_data_provider\n", "hand_uids = [LEFT_HAND_INDEX, RIGHT_HAND_INDEX]\n", "hand_names = {LEFT_HAND_INDEX: \"left\", RIGHT_HAND_INDEX: \"right\"}\n", "color_map = plt.get_cmap(\"viridis\")\n", "hand_box2d_colors = color_map(np.linspace(0, 1, 2))\n", "\n", "rr.init(\"Hand bounding boxes\")\n", "rec = rr.memory_recording()\n", "\n", "stream_id = main_stream_id\n", "if stream_id not in hand_box2d_data_provider.stream_ids:\n", " print(f\"stream_id {stream_id} has no hand bbox data. Available: {hand_box2d_data_provider.stream_ids}\")\n", "\n", "for timestamp_ns in tqdm(timestamps[100:200]):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " result = hand_box2d_data_provider.get_bbox_at_timestamp(\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None or result.box2d_collection is None:\n", " continue\n", "\n", " for i, hand_uid in enumerate(hand_uids):\n", " ab = result.box2d_collection.box2ds[hand_uid]\n", " bbox = ab.box2d\n", " if bbox is None:\n", " continue\n", " hand_name = hand_names[hand_uid]\n", " rr.log(\n", " f\"{stream_id}_raw/bbox/{hand_name}\",\n", " rr.Boxes2D(mins=[bbox.left, bbox.top], sizes=[bbox.width, bbox.height],\n", " colors=hand_box2d_colors[i]),\n", " )\n", " rr.log(f\"visibility/{hand_name}\", rr.Scalar(ab.visibility_ratio))\n", " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n", " if image_data is not None:\n", " log_image(label=f\"{stream_id}_raw\", image=image_data)\n", "\n", "rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "d8bad34e-a8ab-437d-84ff-1c046ca35d51", "metadata": {}, "outputs": [], "source": [ "# Section 4: Eye gaze (Aria only, skipped automatically on Quest3)\n", "\n", "if device_type != Headset.Aria:\n", " print(f\"Skipping Section 4: eye gaze is Aria-only (current device: {device_type})\")\n", "else:\n", " from projectaria_tools.core.calibration import FISHEYE624\n", "\n", " rr.init(\"Eye Gaze reprojection\")\n", " rec = rr.memory_recording()\n", "\n", " stream_id = StreamId(\"214-1\")\n", " for timestamp_ns in tqdm(timestamps[100:120]):\n", " rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n", " rr.set_time_sequence(\"timestamp\", timestamp_ns)\n", "\n", " eye_gaze = device_data_provider.get_eye_gaze(timestamp_ns)\n", " if eye_gaze is None:\n", " continue\n", "\n", " proj = device_data_provider.get_eye_gaze_in_camera(\n", " stream_id, timestamp_ns, camera_model=FISHEYE624\n", " )\n", " if proj is None or not proj.any():\n", " continue\n", "\n", " rr.log(f\"{stream_id}/eye-gaze\", rr.Points2D(proj, radii=20))\n", " image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n", " if image_data is not None:\n", " log_image(label=str(stream_id), image=image_data)\n", "\n", " rr.notebook_show()" ] }, { "cell_type": "code", "execution_count": null, "id": "b4d6ac37-e3b3-401a-83b7-e09a42a183a3", "metadata": {}, "outputs": [], "source": [ "# Section 5: Hand keypoint reprojection onto image\n", "#\n", "# Projects 3D world-space hand landmarks through the camera extrinsics + intrinsics\n", "# to obtain 2D pixel coordinates, then overlays them on the image.\n", "\n", "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "from typing import Any, Optional\n", "from data_loaders.HeadsetPose3dProvider import HeadsetPose3dProvider\n", "from data_loaders.loader_hand_poses import Handedness, HandPose3dCollection\n", "from projectaria_tools.core.calibration import CameraCalibration\n", "from projectaria_tools.core.sophus import SE3\n", "\n", "# Use a mid-sequence frame; clamp so the index is always valid\n", "frame_idx = min(420, len(timestamps) - 1)\n", "timestamp_ns = timestamps[frame_idx]\n", "image_streamid = main_stream_id # Aria -> 214-1, Quest3 -> 1201-1\n", "\n", "image_stream_label = device_data_provider.get_image_stream_label(image_streamid)\n", "image_data = device_data_provider.get_image(timestamp_ns, image_streamid)\n", "\n", "\n", "def get_hand_poses(ts):\n", " if hand_data_provider is None:\n", " return None\n", " result = hand_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=ts,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " return result.pose3d_collection if result else None\n", "\n", "\n", "def get_camera_pose(ts, stream_id):\n", " \"\"\"Returns (T_world_camera, intrinsics) or None.\"\"\"\n", " if device_pose_provider is None:\n", " return None\n", " result = device_pose_provider.get_pose_at_timestamp(\n", " timestamp_ns=ts,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " )\n", " if result is None:\n", " return None\n", " [T_device_camera, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n", " T_world_camera = result.pose3d.T_world_device @ T_device_camera\n", " return T_world_camera, intrinsics\n", "\n", "\n", "hand_data = get_hand_poses(timestamp_ns)\n", "camera_pose = get_camera_pose(timestamp_ns, image_streamid)\n", "\n", "if hand_data is None or camera_pose is None or image_data is None:\n", " print(\"Missing hand data, camera pose, or image — cannot project.\")\n", "else:\n", " T_world_camera, intrinsics = camera_pose\n", " plt.figure(figsize=(10, 8))\n", " plt.imshow(image_data, interpolation=\"nearest\")\n", " plt.title(f\"{image_stream_label} frame={frame_idx}\")\n", "\n", " for hand_pose in hand_data.poses.values():\n", " label = hand_pose.handedness_label()\n", " landmarks = hand_data_provider.get_hand_landmarks(hand_pose)\n", "\n", " # Gather all 3D points along the skeleton connectivity\n", " all_pts_3d = [\n", " landmarks[idx].numpy()\n", " for conn in LANDMARK_CONNECTIVITY\n", " for idx in conn\n", " ]\n", "\n", " # Project each 3D world point into the camera image plane\n", " projected = []\n", " for pt_world in all_pts_3d:\n", " pt_cam = T_world_camera.inverse() @ pt_world\n", " pt_2d = intrinsics.project(pt_cam)\n", " if pt_2d is not None:\n", " projected.append(pt_2d)\n", "\n", " color = 'r' if hand_pose.handedness == Handedness.Right else 'b'\n", " print(f\"{label} hand: {len(projected)} keypoints visible in image\")\n", " if projected:\n", " plt.scatter([p[0] for p in projected], [p[1] for p in projected],\n", " s=3, c=color, label=label)\n", "\n", " plt.legend()\n", " plt.axis('off')\n", " plt.tight_layout()\n", " plt.show()" ] }, { "cell_type": "markdown", "id": "88f7a32a", "metadata": {}, "source": [ "#\n", "# Segmentation Code Sample\n", "#\n", "Written by Zhonghao Zhang (FKZZddd): \n", "This script was copied and adapted from the original script provided by Meta for HOT3D dataset. \n", "The original script can be found at HOT3D/hot3d/hot3d/render_3d.py in the HOT3D repository.\n", "\n", "Used for segmentation of hand meshes by restoring the hands pose and shape data on sense.\n", "setup_hand_at_timestamp is the main function that segments hands and adds hand meshes to the scene\n", "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", "#\n", "# Code Sample\n", "#\n", "Installation:\n", "- pip install pyrender trimesh\n", "#\n", "Details:\n", "Demonstrate how to use PyRender to render HOT3D meshes (objects, hands) for a given timestamp & stream_id\n", "- As OpenGL rendering is rectilinear, color, segmentation and depth buffer are also rectilinear rendering\n", "- 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)" ] }, { "cell_type": "code", "execution_count": null, "id": "b11b22eb", "metadata": {}, "outputs": [], "source": [ "from typing import Dict, List, Optional, Tuple\n", "\n", "import numpy as np\n", "\n", "try:\n", " import trimesh\n", " from pyrender import (\n", " IntrinsicsCamera,\n", " Mesh,\n", " Node,\n", " OffscreenRenderer,\n", " RenderFlags,\n", " Scene,\n", " )\n", "except ImportError:\n", " print(\"trimesh or pyrender modules are missing. Please install them.\")\n", "\n", "from data_loaders.HandDataProviderBase import HandDataProviderBase\n", "from data_loaders.headsets import Headset\n", "from data_loaders.loader_object_library import load_object_library, ObjectLibrary\n", "from dataset_api import Hot3dDataProvider\n", "from PIL import Image\n", "from projectaria_tools.core.calibration import (\n", " CameraCalibration,\n", " distort_by_calibration,\n", " FISHEYE624,\n", " LINEAR,\n", ")\n", "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n", "from projectaria_tools.core.sophus import SE3\n", "from projectaria_tools.core.stream_id import StreamId\n", "from tqdm import tqdm\n", "\n", "# Matrix transform to change Aria camera pose to PyRender coordinate system\n", "# PyRender: +Z = back, +Y = up, +X = right\n", "# Aria: +Z = forward, +Y = down, +X = right\n", "T_ARIA_OPENGL = SE3.from_matrix(\n", " np.array(\n", " [\n", " [1.0, 0.0, 0.0, 0.0],\n", " [0.0, -1.0, 0.0, 0.0],\n", " [0.0, 0.0, -1.0, 0.0],\n", " [0.0, 0.0, 0.0, 1.0],\n", " ]\n", " )\n", ")\n", "\n", "ACCEPTABLE_TIME_DELTA = 0 # To retrieve exact GT\n", "\n", "\n", "def load_meshes_scene(\n", " hot3d_data_provider: Hot3dDataProvider,\n", ") -> Dict[str, Mesh]:\n", " \"\"\"\n", " Load all meshes in the scene and hash them by object_uid\n", " \"\"\"\n", "\n", " object_library = hot3d_data_provider.object_library\n", " object_library_folderpath = object_library.asset_folder_name\n", "\n", " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n", " object_uids = object_pose_data_provider.object_uids_with_poses\n", "\n", " #\n", " # Load all meshes in the scene and store them in a dict\n", " #\n", " meshes: Dict[str, Mesh] = {}\n", " for object_uid in tqdm(object_uids):\n", " object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(\n", " object_library_folderpath=object_library_folderpath,\n", " object_id=object_uid,\n", " )\n", " # Load the mesh, merge its component\n", " scene = trimesh.load_mesh(\n", " object_cad_asset_filepath,\n", " process=True,\n", " merge_primitives=True,\n", " file_type=\"glb\",\n", " )\n", " # Represent the scene by a single mesh\n", " glb_mesh = scene.to_mesh()\n", " # Store the resulting mesh in the dict\n", " meshes[object_uid] = Mesh.from_trimesh(glb_mesh)\n", "\n", " return meshes\n", "\n", "\n", "def setup_objects_at_timestamp(\n", " scene: Scene,\n", " meshes: Dict[str, Mesh],\n", " hot3d_data_provider: Hot3dDataProvider,\n", " timestamp_ns: int,\n", ") -> Dict[str, Node]:\n", " \"\"\"\n", " Setup object meshes in the scene for the specified timestamp\n", " \"\"\"\n", "\n", " object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n", "\n", " pyrender_node_meshes = {}\n", " object_poses_with_dt = None\n", " if object_pose_data_provider is not None:\n", " object_poses_with_dt = object_pose_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n", " )\n", " if object_poses_with_dt is not None:\n", " objects_pose3d_collection = object_poses_with_dt.pose3d_collection\n", " for (\n", " object_uid,\n", " object_pose3d,\n", " ) in objects_pose3d_collection.poses.items():\n", " transform = object_pose3d.T_world_object.to_matrix()\n", " pyrender_node_meshes[object_uid] = scene.add(\n", " meshes[object_uid], pose=transform\n", " )\n", "\n", " return pyrender_node_meshes\n", "\n", "\n", "def get_camera_calibration(\n", " hot3d_data_provider: Hot3dDataProvider,\n", " timestamp_ns: int,\n", " stream_id: StreamId,\n", " camera_model=LINEAR,\n", ") -> Optional[Tuple[SE3, CameraCalibration]]:\n", " \"\"\"\n", " Return the camera calibration\n", " \"\"\"\n", " device_data_provider = hot3d_data_provider.device_data_provider\n", " if hot3d_data_provider.get_device_type() is Headset.Aria:\n", " return device_data_provider.get_online_camera_calibration(\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " camera_model=camera_model,\n", " )\n", " elif hot3d_data_provider.get_device_type() is Headset.Quest3:\n", " return device_data_provider.get_camera_calibration(\n", " stream_id=stream_id,\n", " camera_model=camera_model,\n", " )\n", " else:\n", " return None\n", "\n", "\n", "def setup_camera_at_timestamp(\n", " scene: Scene,\n", " hot3d_data_provider: Hot3dDataProvider,\n", " timestamp_ns: int,\n", " stream_id: StreamId,\n", ") -> Tuple[Node, List[int]]:\n", " \"\"\"\n", " Setup a rectilinear camera for the specified stream_id and timestamp\n", " \"\"\"\n", "\n", " device_data_provider = hot3d_data_provider.device_data_provider\n", " device_pose_provider = hot3d_data_provider.device_pose_data_provider\n", "\n", " [T_device_camera, intrinsics] = get_camera_calibration(\n", " hot3d_data_provider=hot3d_data_provider,\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " camera_model=LINEAR,\n", " )\n", "\n", " headset_pose3d_with_dt = None\n", " if device_data_provider is not None:\n", " headset_pose3d_with_dt = device_pose_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n", " )\n", " if headset_pose3d_with_dt is not None:\n", " headset_pose3d = headset_pose3d_with_dt.pose3d\n", " focal_lengths = intrinsics.get_focal_lengths()\n", " principal_point = intrinsics.get_principal_point()\n", " camera = IntrinsicsCamera(\n", " focal_lengths[0],\n", " focal_lengths[0],\n", " principal_point[0],\n", " principal_point[1],\n", " znear=0.05,\n", " zfar=100.0,\n", " name=None,\n", " )\n", "\n", " camera_pose = (\n", " (headset_pose3d.T_world_device @ T_device_camera) @ T_ARIA_OPENGL\n", " ).to_matrix()\n", "\n", " camera_node = scene.add(camera, pose=camera_pose)\n", " return [camera_node, intrinsics.get_image_size().tolist()]\n", "\n", "\n", "def setup_hand_at_timestamp(\n", " scene: Scene,\n", " hot3d_data_provider: Hot3dDataProvider,\n", " timestamp_ns: int,\n", " hand_data_provider: HandDataProviderBase,\n", ") -> Dict[str, Mesh]:\n", " \"\"\"\n", " Add hand meshes to the scene for the specified timestamp\n", " \"\"\"\n", "\n", " pyrender_node_meshes = {}\n", "\n", " if hand_data_provider is None:\n", " return []\n", "\n", " hand_poses_with_dt = hand_data_provider.get_pose_at_timestamp(\n", " timestamp_ns=timestamp_ns,\n", " time_query_options=TimeQueryOptions.CLOSEST,\n", " time_domain=TimeDomain.TIME_CODE,\n", " acceptable_time_delta=ACCEPTABLE_TIME_DELTA,\n", " )\n", " if hand_poses_with_dt is not None:\n", " hand_pose_collection = hand_poses_with_dt.pose3d_collection\n", "\n", " for hand_pose_data in hand_pose_collection.poses.values():\n", " handedness_label = hand_pose_data.handedness_label()\n", "\n", " hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(\n", " hand_pose_data\n", " )\n", "\n", " [hand_triangles, hand_vertex_normals] = (\n", " hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data)\n", " )\n", "\n", " pyrender_node_meshes[handedness_label] = scene.add(\n", " Mesh.from_trimesh(\n", " trimesh.Trimesh(\n", " vertices=hand_mesh_vertices,\n", " normals=hand_vertex_normals,\n", " faces=hand_triangles,\n", " )\n", " )\n", " )\n", " return pyrender_node_meshes\n", "\n", "\n", "def offscreen_render(\n", " scene: Scene,\n", " resolution: List[int], # [width, height]\n", ") -> Tuple[np.ndarray, np.ndarray]:\n", " \"\"\"\n", " Return COLOR and DEPTH images\n", " \"\"\"\n", " renderer = OffscreenRenderer(resolution[0], resolution[1])\n", " color, depth = renderer.render(scene) # , flags=RenderFlags.RGBA)\n", "\n", " nm = {\n", " node: 20 * (i + 1) for i, node in enumerate(scene.mesh_nodes)\n", " } # Node->Seg Id map\n", " seg = renderer.render(scene, RenderFlags.SEG, nm)[0]\n", "\n", " renderer.delete()\n", " return [color, depth, seg]\n", "\n", "\n", "def distort_rendering(\n", " image: np.ndarray,\n", " hot3d_data_provider: Hot3dDataProvider,\n", " timestamp_ns: int,\n", " stream_id: StreamId,\n", ") -> np.ndarray:\n", " \"\"\"\n", " Map a rectilinear image to the native Fisheye camera model.\n", " - Do notice that we are loosing some field of view.\n", " \"\"\"\n", "\n", " # Retrieve the camera model we want to distort to\n", " [T_device_camera, intrinsics_raw] = get_camera_calibration(\n", " hot3d_data_provider=hot3d_data_provider,\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " camera_model=FISHEYE624,\n", " )\n", "\n", " # Retrieve the camera model we used for rendering\n", " [T_device_camera, intrinsics_linear] = get_camera_calibration(\n", " hot3d_data_provider=hot3d_data_provider,\n", " stream_id=stream_id,\n", " timestamp_ns=timestamp_ns,\n", " camera_model=LINEAR,\n", " )\n", "\n", " re_distorted_image = distort_by_calibration(\n", " image,\n", " intrinsics_raw,\n", " intrinsics_linear,\n", " )\n", "\n", " return re_distorted_image\n", "\n", "\n", "\n", "#The main function \n", "#Set object_library=None because object meshes are unnecessary for project.\n", "hot3d_data_provider = Hot3dDataProvider(\n", " # sequence_folder=\"./data_loaders/tests/data_sample/Aria/P0003_c701bd11\",\n", " sequence_folder=\"./dataset/P0002_2f137f83\",\n", " object_library=None,\n", ")\n", "print(f\"data_provider statistics: {hot3d_data_provider.get_data_statistics()}\")\n", "\n", "scene_meshes = {}\n", "\n", "# Define timestamps and stream ids that need rendering\n", "# Default attempts all stream ids and a timestamp in the middle of the sequence\n", "\n", "#total timestamps/2\n", "timestamps = hot3d_data_provider.device_data_provider.get_sequence_timestamps()\n", "timestamp_list = [timestamps[len(timestamps) // 2]]\n", "stream_id_list = (\n", " [StreamId(\"1201-1\"), StreamId(\"1201-2\"), StreamId(\"214-1\")]\n", " if hot3d_data_provider.get_device_type() is Headset.Aria\n", " else [StreamId(\"1201-1\"), StreamId(\"1201-2\")]\n", ")\n", "\n", "# Main rendering loop\n", "print(f\"Rendering for: {stream_id_list}\")\n", "for stream_id in stream_id_list:\n", " for timestamp_ns in timestamp_list:\n", " # Initialize the scene\n", " scene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))\n", "\n", " # Add hands into scene, the main function that do segmentation\n", " setup_hand_at_timestamp(\n", " scene=scene,\n", " hot3d_data_provider=hot3d_data_provider,\n", " timestamp_ns=timestamp_ns,\n", " hand_data_provider=hot3d_data_provider.umetrack_hand_data_provider,\n", " )\n", "\n", " # Setup camera rendering (for the specific stream_id and timestamp)\n", " camera_node_and_resolution = setup_camera_at_timestamp(\n", " scene=scene,\n", " hot3d_data_provider=hot3d_data_provider,\n", " timestamp_ns=timestamp_ns,\n", " stream_id=stream_id,\n", " )\n", "\n", " print(camera_node_and_resolution)\n", " # Setup off screen rendering (to save rendering buffer to disk as image)\n", " [color, depth, seg] = offscreen_render(scene, camera_node_and_resolution[1])\n", "\n", " camera_node_and_resolution = setup_camera_at_timestamp(\n", " scene=scene,\n", " hot3d_data_provider=hot3d_data_provider,\n", " timestamp_ns=timestamp_ns,\n", " stream_id=stream_id,\n", " )\n", " \n", " im = Image.fromarray(color)\n", " im.save(f\"render_native_{stream_id}_{timestamp_ns}.png\")\n", "\n", " # im = Image.fromarray(distorted_seg)\n", " im = Image.fromarray(seg)\n", " im.save(f\"seg_ref_{stream_id}_{timestamp_ns}.png\")\n", "\n", " # Save \"depth\" buffer\n", " # im = Image.fromarray(depth)\n", " # im.save(f\"depth_ref_{stream_id}_{timestamp_ns}.tiff\")\n", "\n", " image_data_raw = hot3d_data_provider.device_data_provider.get_image(\n", " timestamp_ns, stream_id\n", " )\n", " if image_data_raw is not None:\n", " im = Image.fromarray(image_data_raw)\n", " im.save(f\"image_ref_{stream_id}_{timestamp_ns}.png\")" ] } ], "metadata": { "kernelspec": { "display_name": "hamer", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }