Datasets:

File size: 13,122 Bytes
d188b91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#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, Tuple

import numpy as np

try:
    import trimesh
    from 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 HandDataProviderBase
from data_loaders.headsets import Headset
from data_loaders.loader_object_library import load_object_library, ObjectLibrary
from dataset_api import Hot3dDataProvider
from PIL import Image
from projectaria_tools.core.calibration import (
    CameraCalibration,
    distort_by_calibration,
    FISHEYE624,
    LINEAR,
)
from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions
from projectaria_tools.core.sophus import SE3
from projectaria_tools.core.stream_id import StreamId
from 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 = right
T_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 GT


def 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_library
    object_library_folderpath = object_library.asset_folder_name

    object_pose_data_provider = hot3d_data_provider.object_pose_data_provider
    object_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 component
        scene = trimesh.load_mesh(
            object_cad_asset_filepath,
            process=True,
            merge_primitives=True,
            file_type="glb",
        )
        # Represent the scene by a single mesh
        glb_mesh = scene.to_mesh()
        # Store the resulting mesh in the dict
        meshes[object_uid] = Mesh.from_trimesh(glb_mesh)

    return meshes


def 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_provider

    pyrender_node_meshes = {}
    object_poses_with_dt = None
    if 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_collection
            for (
                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_meshes


def 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_provider
    if 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 None


def 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_provider
    device_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 = None
    if 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.pose3d
            focal_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_collection

        for 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_meshes


def 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 map
    seg = 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/2
timestamps = 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.Aria
    else [StreamId("1201-1"), StreamId("1201-2")]
)

# Main rendering loop
print(f"Rendering for: {stream_id_list}")
for stream_id in stream_id_list:
    for timestamp_ns in timestamp_list:
        # Initialize the scene
        scene = Scene(ambient_light=np.array([1.0, 1.0, 1.0, 1.0]))

        # Add hands into scene, the main function that do segmentation
        setup_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")