Upload HOT3DHUGGFACE/Segmentation.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392#Written by Zhonghao Zhang (FKZZddd):# This script was copied and adapted from the original script provided by Meta for HOT3D dataset.# The original script can be found at HOT3D/hot3d/hot3d/render_3d.py in the HOT3D repository.# Used for segmentation of hand meshes,# setup_hand_at_timestamp is the main function that segments hands and adds hand meshes to the scene# 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.## Code Sample## Installation:# - pip install pyrender trimesh## Details:# Demonstrate how to use PyRender to render HOT3D meshes (objects, hands) for a given timestamp & stream_id# - As OpenGL rendering is rectilinear, color, segmentation and depth buffer are also rectilinear rendering# - 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)from typing import Dict, List, Optional, Tupleimport numpy as nptry:import trimeshfrom pyrender import (IntrinsicsCamera,Mesh,Node,OffscreenRenderer,RenderFlags,Scene,)except ImportError:print("trimesh or pyrender modules are missing. Please install them.")from data_loaders.HandDataProviderBase import HandDataProviderBasefrom data_loaders.headsets import Headsetfrom data_loaders.loader_object_library import load_object_library, ObjectLibraryfrom dataset_api import Hot3dDataProviderfrom PIL import Imagefrom projectaria_tools.core.calibration import (CameraCalibration,distort_by_calibration,FISHEYE624,LINEAR,)from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptionsfrom projectaria_tools.core.sophus import SE3from projectaria_tools.core.stream_id import StreamIdfrom tqdm import tqdm# Matrix transform to change Aria camera pose to PyRender coordinate system# PyRender: +Z = back, +Y = up, +X = right# Aria: +Z = forward, +Y = down, +X = rightT_ARIA_OPENGL = SE3.from_matrix(np.array([[1.0, 0.0, 0.0, 0.0],[0.0, -1.0, 0.0, 0.0],[0.0, 0.0, -1.0, 0.0],[0.0, 0.0, 0.0, 1.0],]))ACCEPTABLE_TIME_DELTA = 0 # To retrieve exact GTdef load_meshes_scene(hot3d_data_provider: Hot3dDataProvider,) -> Dict[str, Mesh]:"""Load all meshes in the scene and hash them by object_uid"""object_library = hot3d_data_provider.object_libraryobject_library_folderpath = object_library.asset_folder_nameobject_pose_data_provider = hot3d_data_provider.object_pose_data_providerobject_uids = object_pose_data_provider.object_uids_with_poses## Load all meshes in the scene and store them in a dict#meshes: Dict[str, Mesh] = {}for object_uid in tqdm(object_uids):object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(object_library_folderpath=object_library_folderpath,object_id=object_uid,)# Load the mesh, merge its componentscene = trimesh.load_mesh(object_cad_asset_filepath,process=True,merge_primitives=True,file_type="glb",)# Represent the scene by a single meshglb_mesh = scene.to_mesh()# Store the resulting mesh in the dictmeshes[object_uid] = Mesh.from_trimesh(glb_mesh)return meshesdef setup_objects_at_timestamp(scene: Scene,meshes: Dict[str, Mesh],hot3d_data_provider: Hot3dDataProvider,timestamp_ns: int,) -> Dict[str, Node]:"""Setup object meshes in the scene for the specified timestamp"""object_pose_data_provider = hot3d_data_provider.object_pose_data_providerpyrender_node_meshes = {}object_poses_with_dt = Noneif object_pose_data_provider is not None:object_poses_with_dt = object_pose_data_provider.get_pose_at_timestamp(timestamp_ns=timestamp_ns,time_query_options=TimeQueryOptions.CLOSEST,time_domain=TimeDomain.TIME_CODE,acceptable_time_delta=ACCEPTABLE_TIME_DELTA,)if object_poses_with_dt is not None:objects_pose3d_collection = object_poses_with_dt.pose3d_collectionfor (object_uid,object_pose3d,) in objects_pose3d_collection.poses.items():transform = object_pose3d.T_world_object.to_matrix()pyrender_node_meshes[object_uid] = scene.add(meshes[object_uid], pose=transform)return pyrender_node_meshesdef get_camera_calibration(hot3d_data_provider: Hot3dDataProvider,timestamp_ns: int,stream_id: StreamId,camera_model=LINEAR,) -> Optional[Tuple[SE3, CameraCalibration]]:"""Return the camera calibration"""device_data_provider = hot3d_data_provider.device_data_providerif hot3d_data_provider.get_device_type() is Headset.Aria:return device_data_provider.get_online_camera_calibration(stream_id=stream_id,timestamp_ns=timestamp_ns,camera_model=camera_model,)elif hot3d_data_provider.get_device_type() is Headset.Quest3:return device_data_provider.get_camera_calibration(stream_id=stream_id,camera_model=camera_model,)else:return Nonedef setup_camera_at_timestamp(scene: Scene,hot3d_data_provider: Hot3dDataProvider,timestamp_ns: int,stream_id: StreamId,) -> Tuple[Node, List[int]]:"""Setup a rectilinear camera for the specified stream_id and timestamp"""device_data_provider = hot3d_data_provider.device_data_providerdevice_pose_provider = hot3d_data_provider.device_pose_data_provider[T_device_camera, intrinsics] = get_camera_calibration(hot3d_data_provider=hot3d_data_provider,stream_id=stream_id,timestamp_ns=timestamp_ns,camera_model=LINEAR,)headset_pose3d_with_dt = Noneif device_data_provider is not None:headset_pose3d_with_dt = device_pose_provider.get_pose_at_timestamp(timestamp_ns=timestamp_ns,time_query_options=TimeQueryOptions.CLOSEST,time_domain=TimeDomain.TIME_CODE,acceptable_time_delta=ACCEPTABLE_TIME_DELTA,)if headset_pose3d_with_dt is not None:headset_pose3d = headset_pose3d_with_dt.pose3dfocal_lengths = intrinsics.get_focal_lengths()principal_point = intrinsics.get_principal_point()camera = IntrinsicsCamera(focal_lengths[0],focal_lengths[0],principal_point[0],principal_point[1],znear=0.05,zfar=100.0,name=None,)camera_pose = ((headset_pose3d.T_world_device @ T_device_camera) @ T_ARIA_OPENGL).to_matrix()camera_node = scene.add(camera, pose=camera_pose)return [camera_node, intrinsics.get_image_size().tolist()]def setup_hand_at_timestamp(scene: Scene,hot3d_data_provider: Hot3dDataProvider,timestamp_ns: int,hand_data_provider: HandDataProviderBase,) -> Dict[str, Mesh]:"""Add hand meshes to the scene for the specified timestamp"""pyrender_node_meshes = {}if hand_data_provider is None:return []hand_poses_with_dt = hand_data_provider.get_pose_at_timestamp(timestamp_ns=timestamp_ns,time_query_options=TimeQueryOptions.CLOSEST,time_domain=TimeDomain.TIME_CODE,acceptable_time_delta=ACCEPTABLE_TIME_DELTA,)if hand_poses_with_dt is not None:hand_pose_collection = hand_poses_with_dt.pose3d_collectionfor hand_pose_data in hand_pose_collection.poses.values():handedness_label = hand_pose_data.handedness_label()hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(hand_pose_data)[hand_triangles, hand_vertex_normals] = (hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data))pyrender_node_meshes[handedness_label] = scene.add(Mesh.from_trimesh(trimesh.Trimesh(vertices=hand_mesh_vertices,normals=hand_vertex_normals,faces=hand_triangles,)))return pyrender_node_meshesdef offscreen_render(scene: Scene,resolution: List[int], # [width, height]) -> Tuple[np.ndarray, np.ndarray]:"""Return COLOR and DEPTH images"""renderer = OffscreenRenderer(resolution[0], resolution[1])color, depth = renderer.render(scene) # , flags=RenderFlags.RGBA)nm = {node: 20 * (i + 1) for i, node in enumerate(scene.mesh_nodes)} # Node->Seg Id mapseg = renderer.render(scene, RenderFlags.SEG, nm)[0]renderer.delete()return [color, depth, seg]def distort_rendering(image: np.ndarray,hot3d_data_provider: Hot3dDataProvider,timestamp_ns: int,stream_id: StreamId,) -> np.ndarray:"""Map a rectilinear image to the native Fisheye camera model.- Do notice that we are loosing some field of view."""# Retrieve the camera model we want to distort to[T_device_camera, intrinsics_raw] = get_camera_calibration(hot3d_data_provider=hot3d_data_provider,stream_id=stream_id,timestamp_ns=timestamp_ns,camera_model=FISHEYE624,)# Retrieve the camera model we used for rendering[T_device_camera, intrinsics_linear] = get_camera_calibration(hot3d_data_provider=hot3d_data_provider,stream_id=stream_id,timestamp_ns=timestamp_ns,camera_model=LINEAR,)re_distorted_image = distort_by_calibration(image,intrinsics_raw,intrinsics_linear,)return re_distorted_image#The main function#Set object_library=None because object meshes are unnecessary for project.hot3d_data_provider = Hot3dDataProvider(# sequence_folder="./data_loaders/tests/data_sample/Aria/P0003_c701bd11",sequence_folder="./dataset/P0002_2f137f83",object_library=None,)print(f"data_provider statistics: {hot3d_data_provider.get_data_statistics()}")scene_meshes = {}# Define timestamps and stream ids that need rendering# Default attempts all stream ids and a timestamp in the middle of the sequence#total timestamps/2timestamps = hot3d_data_provider.device_data_provider.get_sequence_timestamps()timestamp_list = [timestamps[len(timestamps) // 2]]stream_id_list = ([StreamId("1201-1"), StreamId("1201-2"), StreamId("214-1")]if hot3d_data_provider.get_device_type() is Headset.Ariaelse [StreamId("1201-1"), StreamId("1201-2")])# Main rendering loopprint(f"Rendering for: {stream_id_list}")for stream_id in stream_id_list:for timestamp_ns in timestamp_list:# Initialize the scenescene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))# Add hands into scene, the main function that do segmentationsetup_hand_at_timestamp(scene=scene,hot3d_data_provider=hot3d_data_provider,timestamp_ns=timestamp_ns,hand_data_provider=hot3d_data_provider.umetrack_hand_data_provider,)# Setup camera rendering (for the specific stream_id and timestamp)camera_node_and_resolution = setup_camera_at_timestamp(scene=scene,hot3d_data_provider=hot3d_data_provider,timestamp_ns=timestamp_ns,stream_id=stream_id,)print(camera_node_and_resolution)# Setup off screen rendering (to save rendering buffer to disk as image)[color, depth, seg] = offscreen_render(scene, camera_node_and_resolution[1])camera_node_and_resolution = setup_camera_at_timestamp(scene=scene,hot3d_data_provider=hot3d_data_provider,timestamp_ns=timestamp_ns,stream_id=stream_id,)im = Image.fromarray(color)im.save(f"render_native_{stream_id}_{timestamp_ns}.png")# im = Image.fromarray(distorted_seg)im = Image.fromarray(seg)im.save(f"seg_ref_{stream_id}_{timestamp_ns}.png")# Save "depth" buffer# im = Image.fromarray(depth)# im.save(f"depth_ref_{stream_id}_{timestamp_ns}.tiff")image_data_raw = hot3d_data_provider.device_data_provider.get_image(timestamp_ns, stream_id)if image_data_raw is not None:im = Image.fromarray(image_data_raw)im.save(f"image_ref_{stream_id}_{timestamp_ns}.png")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085{"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}
HOT3DHUGGFACE/Segmentation.py+1085-392