Datasets:

File size: 44,934 Bytes
dbf8921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ee215408-e60b-4209-a09a-f84a8fd5ffa1",
   "metadata": {},
   "source": [
    "\n",
    "# Hot3D Data Provider Tutorial\n",
    "\n",
    "In order to use sequences from the HOT3D dataset, you will need ot use the Hot3dDataProvider object.\n",
    "\n",
    "This notebook is explaining how to use the various \"DataProvider\" in order to retrieve:\n",
    "- Section 0: DataProvider initialization\n",
    "- Section 1: Device calibration and Image data\n",
    "- Section 2: Pose data\n",
    "  - Section 2.a: Device/Headset pose data\n",
    "  - Section 2.b: Hand pose data\n",
    "  - Section 2.b.a: Hand pose data and MESH hands\n",
    "  - Section 2.c: Object pose data\n",
    "- Section 3:\n",
    "  - Section 3.a: Object bounding boxes (amodal bounding boxes)\n",
    "  - Section 3.b: Hand bounding boxes (amodal bounding boxes)\n",
    "- Section 4: Eye Gaze data (only for Aria data)\n",
    "- Section 5: Camera reprojection (reprojection hand vertices to raw fish images)\n",
    "\n",
    "Hot3dDataProvider API is organized as follow:\n",
    "```\n",
    "|- device_data_provider        -> provides device calibration and image data\n",
    "|- device_pose_data_provider   -> provides device pose data\n",
    "|- mano_hand_data_provider     -> provides hand pose data (MANO representation)\n",
    "|- umetrack_hand_data_provider -> provides hand pose data (UmeTrack representation)\n",
    "|- object_pose_data_provider   -> provides object pose data\n",
    "|- object_library              -> provides information about the HOT3D 3D objects/assets\n",
    "|- hand_box2d_data_provider    -> provides hands bbox information\n",
    "|- object_box2d_data_provider  -> provides objects bbox information\n",
    "```\n",
    "\n",
    "## Notes\n",
    "- All Device/Headset, Hand, Object poses data are shared in world coordinates (meters)\n",
    "\n",
    "In this tutorial you will learn that:\n",
    "- Device data, such as Image data stream is indexed with a stream_id\n",
    "- Headset use camera rig coordinates relative to the DEVICE pose (world_camera_stream_id = world_device @ device_camera_stream_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97bcb96c-4910-4a60-9a41-c3b34ee7ac7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 0: DataProvider initialization\n",
    "#\n",
    "# Take home message:\n",
    "# - Device data, such as Image data stream is indexed with a stream_id\n",
    "# - Intrinsics and Extrinsics calibration relative to the device coordinates is available for each CAMERA/stream_id\n",
    "#\n",
    "# Data Requirements:\n",
    "# - a sequence\n",
    "# - the object library\n",
    "# Optional:\n",
    "# - To use the Mano hand you need to have the LEFT/RIGHT *.pkl hand models (available)\n",
    "\n",
    "import os\n",
    "from dataset_api import Hot3dDataProvider\n",
    "from data_loaders.loader_object_library import load_object_library\n",
    "from data_loaders.mano_layer import MANOHandModel\n",
    "\n",
    "home = os.path.expanduser(\"~\")\n",
    "hot3d_dataset_path = home + \"/Downloads/hot3d_dataset\"\n",
    "sequence_path = os.path.join(hot3d_dataset_path, \"P0003_c701bd11\")\n",
    "object_library_path = os.path.join(hot3d_dataset_path, \"assets\")\n",
    "mano_hand_model_path = os.path.join(home, \"Downloads\")\n",
    "\n",
    "if not os.path.exists(sequence_path) or not os.path.exists(object_library_path):\n",
    "    print(\"Invalid input sequence or library path.\")\n",
    "    print(\"Please do update the path to VALID values for your system.\")\n",
    "    raise\n",
    "#\n",
    "# Init the object library\n",
    "#\n",
    "object_library = load_object_library(object_library_folderpath=object_library_path)\n",
    "\n",
    "#\n",
    "# Init the HANDs model\n",
    "# If None, the UmeTrack HANDs model will be used\n",
    "#\n",
    "mano_hand_model = None\n",
    "if mano_hand_model_path is not None:\n",
    "    mano_hand_model = MANOHandModel(mano_hand_model_path)\n",
    "\n",
    "#\n",
    "# Initialize hot3d data provider\n",
    "#\n",
    "hot3d_data_provider = Hot3dDataProvider(\n",
    "    sequence_folder=sequence_path,\n",
    "    object_library=object_library,\n",
    "    mano_hand_model=mano_hand_model,\n",
    ")\n",
    "print(f\"data_provider statistics: {hot3d_data_provider.get_data_statistics()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24dae021-1cfe-440a-a5c8-6f44851219e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Utility functions\n",
    "# Used for interactive display in the following sections\n",
    "#\n",
    "import rerun as rr\n",
    "import numpy as np\n",
    "\n",
    "from projectaria_tools.core.sophus import SE3\n",
    "from projectaria_tools.utils.rerun_helpers import ToTransform3D\n",
    "\n",
    "\n",
    "def log_image(\n",
    "    image: np.array,\n",
    "    label: str,\n",
    "    static=False\n",
    ") -> None:\n",
    "    rr.log(label, rr.Image(image), static=static)\n",
    "\n",
    "\n",
    "def log_pose(\n",
    "    pose: SE3,\n",
    "    label: str,\n",
    "    static=False\n",
    ") -> 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: Device calibration and Image data\n",
    "\n",
    "from tqdm import tqdm\n",
    "\n",
    "#\n",
    "# Retrieve some statistics about the \"IMAGE\" VRS recording\n",
    "#\n",
    "\n",
    "# Getting the device data provider (alias)\n",
    "device_data_provider = hot3d_data_provider.device_data_provider\n",
    "\n",
    "# Retrieve the list of image stream supported by this sequence\n",
    "# It will return the RGB and SLAM Left/Right image streams\n",
    "image_stream_ids = device_data_provider.get_image_stream_ids()\n",
    "# Retrieve a list of timestamps for the sequence (in nanoseconds)\n",
    "timestamps = device_data_provider.get_sequence_timestamps()\n",
    "\n",
    "print(f\"Sequence: {os.path.basename(os.path.normpath(sequence_path))}\")\n",
    "print(f\"Device type is {hot3d_data_provider.get_device_type()}\")\n",
    "print(f\"Image stream ids: {image_stream_ids}\")\n",
    "print(f\"Number of timestamp for this sequence: {len(timestamps)}\")\n",
    "print(\n",
    "    f\"Duration of the sequence: {(timestamps[-1] - timestamps[0]) / 1e9} (seconds)\"\n",
    ")  # Timestamps are in nanoseconds\n",
    "\n",
    "\n",
    "# Init a rerun context to visualize the sequence file images\n",
    "rr.init(\"Device images\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# How to iterate over timestamps using a slice to show one timestamp every 200\n",
    "timestamps_slice = slice(None, None, 200)\n",
    "# Loop over the timestamps of the sequence and visualize corresponding data\n",
    "for timestamp_ns in tqdm(timestamps[timestamps_slice]):\n",
    "\n",
    "    for stream_id in image_stream_ids:\n",
    "        # Retrieve the image stream label as string\n",
    "        image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "        # Retrieve the image data for a given timestamp\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        # Visualize the image data (it's a numpy array)\n",
    "        log_image(label=f\"img/{image_stream_label}\", image=image_data)\n",
    "\n",
    "\n",
    "#\n",
    "# Retrieve Camera calibration (intrinsics and extrinsics) for a given stream_id\n",
    "#\n",
    "for stream_id in image_stream_ids:\n",
    "    # Retrieve the camera calibration (intrinsics and extrinsics) for a given stream_id\n",
    "    [extrinsics, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
    "    print(intrinsics)\n",
    "    # We will show in next section how to visualize the position of the camera in the world frame\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d199e9c-7359-43b2-8ecd-807db548def0",
   "metadata": {},
   "source": [
    "# A gentle introduction to the \"GT Data\" Provider API\n",
    "\n",
    "Take home message:\n",
    "- All \"GT data provider\" are using a similar API interface to query data at a given timestamp and/or StreamID.\n",
    "- If the requested timestamp does not exists, the closest one can be retrieve along its delta time (dt).\n",
    "\n",
    "All the following \"GT data providers\" are accessible from Hot3dDataProvider and using a similar API interface.\n",
    "```\n",
    "|- device_pose_data_provider   -> device/headset pose data\n",
    "|- mano_hand_data_provider     -> hand pose data (MANO hand model)\n",
    "|- umetrack_hand_data_provider -> hand pose data (UmeTrack hand model)\n",
    "|- object_pose_data_provider   -> object pose data\n",
    "|- hand_box2d_data_provider    -> hand information such as amodal BBox and visibility ratio\n",
    "|- object_box2d_data_provider  -> object information such as amodal BBox and visibility ratio\n",
    "```\n",
    "\n",
    "We are here shortly introducing the retrieval concept used, and then will showcase how to use each data_provider.\n",
    "GT data providers enable retrieving information at a given TIMESTAMP\n",
    "- If the timestamp is not exact, the closest one can will be returned,\n",
    "- Delta Time (dt) between the found sample and the query timestamp is returned\n",
    "  Meaning that you known if you have a perfect match to the GT time sample or retrieved a close sample.\n",
    "  \n",
    "Note: Some GT data providers are STREAM_ID specific and enable retrieve information for a given image stream.\n",
    "```\n",
    "data_with_dt = device_pose_provider.get_pose_at_timestamp(\n",
    "   timestamp_ns: int,                           -> Timestamp\n",
    "   stream_id: StreamID,                         -> If used, specify for which VRS image stream you query the data\n",
    "   time_query_options: TimeQueryOptions,        -> Retrieval configuration, i.e TimeQueryOptions.CLOSEST\n",
    "   time_domain: TimeDomain,                     -> TimeDomain (always use TimeDomain.TIME_CODE)\n",
    "   acceptable_time_delta: Optional[int] = None, -> Threshold to reject delta dt that would be too large (using 0 or None is recommended)\n",
    "```\n",
    "\n",
    "Here is how most of the interface will be used in the following sections:\n",
    "```\n",
    "data_with_dt = X_provider.get_X_at_timestamp(\n",
    "    timestamp_ns=timestamp_ns,\n",
    "    time_query_options=TimeQueryOptions.CLOSEST,\n",
    "    time_domain=TimeDomain.TIME_CODE)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c473c3-174f-4cff-9d58-0650b580da72",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 2: Pose data\n",
    "#\n",
    "# Take home message:\n",
    "# - the device_pose_provider enables you to retrieve the Headset pose as (T_world_device)\n",
    "# - moving to the device to a given camera can be done by using calibration data and combining SE3 poses\n",
    "#   - such as T_world_camera = T_world_device @ T_device_camera\n",
    "#\n",
    "\n",
    "from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions\n",
    "\n",
    "# Alias over the HEADSET/Device pose data provider\n",
    "device_pose_provider = hot3d_data_provider.device_pose_data_provider\n",
    "\n",
    "# Init a rerun context to visualize the device trajectory\n",
    "rr.init(\"Device/Headset trajectory\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "pose_translations = []\n",
    "# Retrieve the position of the device in the world frame at a given timestamp\n",
    "for timestamp_ns in tqdm(timestamps):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    headset_pose3d_with_dt = None\n",
    "    if device_pose_provider is None:\n",
    "        continue\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",
    "    )\n",
    "\n",
    "    if headset_pose3d_with_dt is None:\n",
    "        continue\n",
    "\n",
    "    headset_pose3d = headset_pose3d_with_dt.pose3d\n",
    "    T_world_device = headset_pose3d.T_world_device\n",
    "    \n",
    "    log_pose(pose=T_world_device, label=\"world/device\")\n",
    "    pose_translations.append(T_world_device.translation()[0])\n",
    "    # This is the pose of the device, to move to a given camera, you need to apply the device_camera transformation\n",
    "    #for stream_id in image_stream_ids:\n",
    "       # # Retrieve the camera calibration (intrinsics and extrinsics) for a given stream_id\n",
    "       # [T_device_camera, intrinsics] = device_data_provider.get_camera_calibration(stream_id)\n",
    "       # # The pose of the given camera at this timestamp is (world_camera = world_device @ device_camera):\n",
    "       # T_world_camera = headset_pose3d.T_world_device @ T_device_camera\n",
    "       # camera_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "       # print(f\"Image stream label: {camera_stream_label} -> world_camera translation: {T_world_camera.translation()[0]}\")\n",
    "\n",
    "rr.log(\"world/device_trajectory\", rr.LineStrips3D([pose_translations]), static=True)\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5253618-2ca2-4d11-a605-aa5aa19c54eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 2.b: Hand pose data\n",
    "#\n",
    "# Take home message:\n",
    "# - Hands are labelled as LEFT or RIGHT hands\n",
    "# - \"Hands pose\" are representing the WRIST pose on which a MESH or LANDMARKS can be attached (see next section)\n",
    "#\n",
    "\n",
    "# Alias over the HAND pose data provider\n",
    "hand_data_provider = hot3d_data_provider.mano_hand_data_provider if hot3d_data_provider.mano_hand_data_provider is not None else hot3d_data_provider.umetrack_hand_data_provider\n",
    "\n",
    "# Init a rerun context to visualize the hand pose data trajectory\n",
    "rr.init(\"Hand pose trajectory (wrist)\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Accumulate HAND poses translations as list, to show a LINE strip HAND trajectory\n",
    "left_hand_pose_translations = []\n",
    "right_hand_pose_translations = []\n",
    "\n",
    "# Retrieve the position of the device in the world frame at a given timestamp\n",
    "for timestamp_ns in tqdm(timestamps):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    hand_poses_with_dt = None\n",
    "    if hand_data_provider is None:\n",
    "        continue\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",
    "    )\n",
    "\n",
    "    if hand_poses_with_dt is None:\n",
    "        continue\n",
    "        \n",
    "    hand_pose_collection = hand_poses_with_dt.pose3d_collection\n",
    "\n",
    "    for hand_pose_data in hand_pose_collection.poses.values():\n",
    "        # Retrieve the handedness of the hand (i.e Left or Right)\n",
    "        handedness_label = hand_pose_data.handedness_label()\n",
    "\n",
    "        T_world_wrist = hand_pose_data.wrist_pose\n",
    "        log_pose(pose=T_world_wrist, label=f\"world/hand/{handedness_label}\")\n",
    "\n",
    "        # Accumulate HAND poses translations as list, to show a LINE strip HAND trajectory\n",
    "        if hand_pose_data.is_left_hand():\n",
    "            left_hand_pose_translations.append(T_world_wrist.translation()[0])\n",
    "        elif hand_pose_data.is_right_hand():\n",
    "            right_hand_pose_translations.append(T_world_wrist.translation()[0])\n",
    "\n",
    "rr.log(\"world/left_hand\", rr.LineStrips3D([left_hand_pose_translations]), static=True)\n",
    "rr.log(\"world/right_hand\", rr.LineStrips3D([right_hand_pose_translations]), static=True)\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a013c63-65e6-4c38-b378-141c8c7ae3ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 2.b.a: Hand pose data\n",
    "#\n",
    "# Take home message:\n",
    "# - Hands are labelled as LEFT or RIGHT hands\n",
    "# - Hands can be retrieved as:\n",
    "#   - Landmarks and displayed as line\n",
    "#   - Vertices\n",
    "#   - Mesh (using vertices, faces index and normals)\n",
    "#\n",
    "\n",
    "from data_loaders.hand_common import LANDMARK_CONNECTIVITY\n",
    "\n",
    "\n",
    "# Alias over the HAND pose data provider\n",
    "hand_data_provider = hot3d_data_provider.mano_hand_data_provider if hot3d_data_provider.mano_hand_data_provider is not None else hot3d_data_provider.umetrack_hand_data_provider\n",
    "\n",
    "# Init a rerun context\n",
    "rr.init(\"Hand pose LANDMARK/MESH\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "left_hand_pose_translations = []\n",
    "right_hand_pose_translations = []\n",
    "\n",
    "# Limit to the first 300 timestamps\n",
    "for timestamp_ns in tqdm(timestamps[:300]):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    hand_poses_with_dt = None\n",
    "    if hand_data_provider is None:\n",
    "        continue\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",
    "    )\n",
    "\n",
    "    if hand_poses_with_dt is None:\n",
    "        continue\n",
    "    \n",
    "    hand_pose_collection = hand_poses_with_dt.pose3d_collection\n",
    "\n",
    "    for hand_pose_data in hand_pose_collection.poses.values():\n",
    "        # Retrieve the handedness of the hand (i.e Left or Right)\n",
    "        handedness_label = hand_pose_data.handedness_label()\n",
    "\n",
    "        # Skeleton/Joints landmark representation (for LEFT hand)\n",
    "        if hand_pose_data.is_left_hand():\n",
    "            hand_landmarks = hand_data_provider.get_hand_landmarks(\n",
    "                hand_pose_data\n",
    "            )\n",
    "            # convert landmarks to connected lines for display\n",
    "            # (i.e retrieve points along the HAND LANDMARK_CONNECTIVITY as a list)\n",
    "            points = [connections\n",
    "                      for connectivity in LANDMARK_CONNECTIVITY\n",
    "                      for connections in [[hand_landmarks[it].numpy().tolist() for it in connectivity]]]\n",
    "            rr.log(\n",
    "                f\"world/{handedness_label}/joints\",\n",
    "                rr.LineStrips3D(points, radii=0.002),\n",
    "            )\n",
    "\n",
    "        #\n",
    "        # Plot RIGHT hand as a Triangular Mesh representation\n",
    "        #\n",
    "        if hand_pose_data.is_right_hand():\n",
    "            hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(hand_pose_data)\n",
    "            hand_triangles, hand_vertex_normals = hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data)\n",
    "            \n",
    "            rr.log(\n",
    "                f\"world/{handedness_label}/mesh_faces\",\n",
    "                rr.Mesh3D(\n",
    "                    vertex_positions=hand_mesh_vertices,\n",
    "                    vertex_normals=hand_vertex_normals,\n",
    "                    triangle_indices=hand_triangles,\n",
    "                ),\n",
    "            )\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a909427f-d8c5-40a7-8eba-8702de2a313b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 2.c: Object pose data\n",
    "#\n",
    "# Take home message:\n",
    "# - Each object is associated with a Unique Identified (uid)\n",
    "# - The object library enables to retrieve the 3D asset linked to this UID (a glb file)\n",
    "#\n",
    "\n",
    "from data_loaders.loader_object_library import ObjectLibrary\n",
    "\n",
    "# Alias over the Object pose data provider\n",
    "object_pose_data_provider = hot3d_data_provider.object_pose_data_provider\n",
    "\n",
    "# Keep track of what 3D assets has been loaded/unloaded so we will load them only when needed\n",
    "# So we will load them only when required for Rerun\n",
    "object_cache_status = {}\n",
    "\n",
    "# Init a rerun context\n",
    "rr.init(\"Object pose\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Limit to the some timestamps\n",
    "for timestamp_ns in tqdm(timestamps[100:300]):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    object_poses_with_dt = (\n",
    "        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",
    "    )\n",
    "    if object_poses_with_dt is None:\n",
    "        continue\n",
    "\n",
    "    objects_pose3d_collection = object_poses_with_dt.pose3d_collection\n",
    "\n",
    "    # Keep a mapping to know what object has been seen, and which one has not\n",
    "    object_uids = object_pose_data_provider.object_uids_with_poses\n",
    "    logging_status = {x: False for x in object_uids}\n",
    "\n",
    "    for (\n",
    "        object_uid,\n",
    "        object_pose3d,\n",
    "    ) in objects_pose3d_collection.poses.items():\n",
    "\n",
    "        object_name = object_library.object_id_to_name_dict[object_uid]\n",
    "        object_name = object_name + \"_\" + str(object_uid)\n",
    "        object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path(\n",
    "            object_library_folderpath=object_library.asset_folder_name,\n",
    "            object_id=object_uid,\n",
    "        )\n",
    "\n",
    "        log_pose(pose=object_pose3d.T_world_object, label=f\"world/objects/{object_name}\")\n",
    "        \n",
    "        # Mark object has been seen (enable to know which object has been logged or not)\n",
    "        # I.E and object not logged, has not been seen and will have its entity cleared for rerun\n",
    "        logging_status[object_uid] = True\n",
    "\n",
    "        # Link the corresponding 3D object to the pose\n",
    "        if object_uid not in object_cache_status.keys():\n",
    "            object_cache_status[object_uid] = True\n",
    "            rr.log(\n",
    "                f\"world/objects/{object_name}\",\n",
    "                rr.Asset3D(\n",
    "                    path=object_cad_asset_filepath,\n",
    "                ),\n",
    "            )\n",
    "\n",
    "    # Rerun specifics (if an entity is disapearing, the last status is shown)\n",
    "    # To compensate that , if some objects are not visible, we clear the entity\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]\n",
    "            object_name = object_name + \"_\" + str(object_uid)\n",
    "            rr.log(\n",
    "                f\"world/objects/{object_name}\",\n",
    "                rr.Clear.recursive(),\n",
    "            )\n",
    "            if object_uid in object_cache_status.keys():\n",
    "                del object_cache_status[object_uid]  # We will log the mesh again\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f31214ce-108e-403e-b66f-2c224ab450f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 3: Object/Hand bounding boxes\n",
    "#\n",
    "# Take home message\n",
    "# - Bounding box data is queried by TIMESTAMP and STREAM_ID and contains amodal bbox and visibility ratio\n",
    "# - Unique Identifiers are used to label objects (uid) -> they can be mapped to literal name by using the object_library\n",
    "#"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b841145d-a114-4693-a0d4-492f9629bbbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 3.a: Object bounding boxes\n",
    "#\n",
    "#\n",
    "from projectaria_tools.core.stream_id import StreamId\n",
    "\n",
    "import matplotlib.pyplot as plt # Used to display consistent colored Bounding Boxes contours\n",
    "\n",
    "# Alias over the Object box2d data provider and Device data provider (to get image data)\n",
    "object_box2d_data_provider = hot3d_data_provider.object_box2d_data_provider\n",
    "device_data_provider = hot3d_data_provider.device_data_provider\n",
    "\n",
    "# Retrieve a distinct color mapping for object bounding box\n",
    "# by using a colormap (i.e associate a object_uid to a specific color)\n",
    "object_uids = list(object_box2d_data_provider.object_uids) # list of available object_uid used to map them to [0, 1, 2, ...] indices\n",
    "object_box2d_colors = None\n",
    "if object_box2d_data_provider is not None:\n",
    "    color_map = plt.get_cmap(\"viridis\")\n",
    "    object_box2d_colors = color_map(\n",
    "        np.linspace(0, 1, len(object_uids))\n",
    "    )\n",
    "else:\n",
    "    print(\"This section expect to have valid bounding box data\")\n",
    "\n",
    "\n",
    "# Init a rerun context\n",
    "rr.init(\"Object bounding boxed and visibility ratio\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Use SLAM-LEFT image (exists for both Aria and Quest files)\n",
    "stream_id = StreamId(\"1201-1\")\n",
    "if stream_id not in object_box2d_data_provider.stream_ids:\n",
    "    print(f\"The object_box2d_data_provider does not have data for this StreamId: {stream_id}\")\n",
    "\n",
    "\n",
    "# Limit to the some timestamps\n",
    "for timestamp_ns in tqdm(timestamps[100:200]):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    # Retrieve data for this timestamp and specific stream_id\n",
    "    box2d_collection_with_dt = (\n",
    "        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",
    "    )\n",
    "    if box2d_collection_with_dt is None:\n",
    "        continue\n",
    "    if (\n",
    "        box2d_collection_with_dt is None\n",
    "        and box2d_collection_with_dt.box2d_collection or None\n",
    "    ):\n",
    "        continue\n",
    "    \n",
    "    # We have valid data, returned as a collection\n",
    "    # i.e for each object_uid, we retrieve its BBOX and visibility\n",
    "    object_uids_at_query_timestamp = (\n",
    "        box2d_collection_with_dt.box2d_collection.object_uid_list\n",
    "    )\n",
    "\n",
    "    for object_uid in object_uids_at_query_timestamp:\n",
    "        object_name = object_library.object_id_to_name_dict[object_uid]\n",
    "        axis_aligned_box2d = box2d_collection_with_dt.box2d_collection.box2ds[object_uid]\n",
    "        bbox = axis_aligned_box2d.box2d\n",
    "        visibility_ratio = axis_aligned_box2d.visibility_ratio\n",
    "        if bbox is None:\n",
    "            continue\n",
    "\n",
    "        rr.log(\n",
    "            f\"{stream_id}_raw/bbox/{object_name}\",\n",
    "            rr.Boxes2D(\n",
    "                mins=[bbox.left, bbox.top],\n",
    "                sizes=[bbox.width, bbox.height],\n",
    "                colors=object_box2d_colors[object_uids.index(object_uid)],\n",
    "            ),\n",
    "        )\n",
    "        rr.log(f\"visibility_ratio/{object_name}\", rr.Scalar(visibility_ratio))\n",
    "        \n",
    "        # Log the corresponding image\n",
    "        image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "        # Retrieve the image data for a given timestamp\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        # Visualize the image data (it's a numpy array)\n",
    "        log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d1daf98-2df6-4d0a-ae38-331060353b99",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 3.b: Hand bounding boxes\n",
    "#\n",
    "#\n",
    "from projectaria_tools.core.stream_id import StreamId\n",
    "\n",
    "from data_loaders.loader_hand_poses import LEFT_HAND_INDEX, RIGHT_HAND_INDEX\n",
    "import matplotlib.pyplot as plt # Used to display consistent colored Bounding Boxes contours\n",
    "\n",
    "# Alias over the Hand box2d data provider and Device data provider (to get image data)\n",
    "hand_box2d_data_provider = hot3d_data_provider.hand_box2d_data_provider\n",
    "device_data_provider = hot3d_data_provider.device_data_provider\n",
    "\n",
    "# Retrieve a distinct color mapping for hand bounding box\n",
    "# by using a colormap (i.e associate a hand_uid to a specific color)\n",
    "hand_uids = [LEFT_HAND_INDEX, RIGHT_HAND_INDEX]\n",
    "hand_box2d_colors = None\n",
    "if hand_box2d_data_provider is not None:\n",
    "    color_map = plt.get_cmap(\"viridis\")\n",
    "    hand_box2d_colors = color_map(\n",
    "        np.linspace(0, 1, len(hand_uids))\n",
    "    )\n",
    "else:\n",
    "    print(\"This section expect to have valid bounding box data\")\n",
    "\n",
    "\n",
    "# Init a rerun context\n",
    "rr.init(\"Hand bounding boxed and visibility ratio\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Use SLAM-LEFT image (exists for both Aria and Quest files)\n",
    "stream_id = StreamId(\"1201-1\")\n",
    "if stream_id not in hand_box2d_data_provider.stream_ids:\n",
    "    print(f\"The hand_box2d_data_provider does not have data for this StreamId: {stream_id}\")\n",
    "\n",
    "\n",
    "# Limit to the some timestamps\n",
    "for timestamp_ns in tqdm(timestamps[100:200]):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "\n",
    "    # Retrieve data for this timestamp and specific stream_id\n",
    "    box2d_collection_with_dt = (\n",
    "        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",
    "    )\n",
    "    \n",
    "    if box2d_collection_with_dt is None:\n",
    "        continue\n",
    "    if (\n",
    "        box2d_collection_with_dt is None\n",
    "        and box2d_collection_with_dt.box2d_collection or None\n",
    "    ):\n",
    "        continue\n",
    "\n",
    "    \n",
    "    # We have valid data, returned as a collection\n",
    "    # i.e for each hand_uid, we retrieve its BBOX and visibility\n",
    "    for hand_uid in hand_uids:\n",
    "        hand_name = \"left\" if hand_uid == LEFT_HAND_INDEX else \"right\"\n",
    "        axis_aligned_box2d = box2d_collection_with_dt.box2d_collection.box2ds[hand_uid]\n",
    "        bbox = axis_aligned_box2d.box2d\n",
    "        visibility_ratio = axis_aligned_box2d.visibility_ratio\n",
    "        if bbox is None:\n",
    "            continue\n",
    "\n",
    "        rr.log(\n",
    "            f\"{stream_id}_raw/bbox/{hand_name}\",\n",
    "            rr.Boxes2D(\n",
    "                mins=[bbox.left, bbox.top],\n",
    "                sizes=[bbox.width, bbox.height],\n",
    "                colors=object_box2d_colors[hand_uids.index(hand_uid)],\n",
    "            ),\n",
    "        )\n",
    "        rr.log(f\"visibility_ratio/{hand_name}\", rr.Scalar(visibility_ratio))\n",
    "        \n",
    "        # Log the corresponding image\n",
    "        image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "        # Retrieve the image data for a given timestamp\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        # Visualize the image data (it's a numpy array)\n",
    "        log_image(label=f\"{stream_id}_raw\", image=image_data)\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8bad34e-a8ab-437d-84ff-1c046ca35d51",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Section 4: Eye Gaze data (only for Aria data)\n",
    "#\n",
    "# Take home message\n",
    "# - Eye Gaze data is only available for Aria sequences\n",
    "# - Eye Gaze data is retrieved via the device_data_provider\n",
    "# - Eye Gaze data is a 3D ray that can be reprojected at any desired depth in a given image\n",
    "#\n",
    "\n",
    "from data_loaders.headsets import Headset\n",
    "from projectaria_tools.core.calibration import FISHEYE624\n",
    "\n",
    "if hot3d_data_provider.get_device_type() is not Headset.Aria:\n",
    "    pass\n",
    "\n",
    "device_data_provider = hot3d_data_provider.device_data_provider\n",
    "\n",
    "# Use RGB image\n",
    "stream_id = StreamId(\"214-1\")\n",
    "\n",
    "# Init a rerun context\n",
    "rr.init(\"Eye Gaze reprojection in RGB image\")\n",
    "rec = rr.memory_recording()\n",
    "\n",
    "# Limit to the some timestamps\n",
    "for timestamp_ns in tqdm(timestamps[100:120]):\n",
    "\n",
    "    rr.set_time_nanos(\"synchronization_time\", int(timestamp_ns))\n",
    "    rr.set_time_sequence(\"timestamp\", timestamp_ns)\n",
    "    \n",
    "    aria_eye_gaze_data = (\n",
    "        device_data_provider.get_eye_gaze(timestamp_ns)\n",
    "        if hot3d_data_provider.get_device_type() is Headset.Aria\n",
    "        else None\n",
    "    )\n",
    "    #\n",
    "    ## Eye Gaze image reprojection\n",
    "    #\n",
    "    if aria_eye_gaze_data is not None:\n",
    "\n",
    "        # We are showing EyeGaze reprojection only on the RGB image stream\n",
    "        if stream_id != StreamId(\"214-1\"):\n",
    "            continue\n",
    "\n",
    "        # Reproject EyeGaze for raw images\n",
    "        camera_model = FISHEYE624\n",
    "        \n",
    "        eye_gaze_reprojection_data = (\n",
    "            device_data_provider.get_eye_gaze_in_camera(\n",
    "                stream_id, timestamp_ns, camera_model=camera_model\n",
    "            )\n",
    "        )\n",
    "        if (\n",
    "            eye_gaze_reprojection_data is None\n",
    "            or not eye_gaze_reprojection_data.any()\n",
    "        ):\n",
    "            continue\n",
    "\n",
    "        rr.log(\n",
    "            f\"{stream_id}/eye-gaze_projection\",\n",
    "            rr.Points2D(eye_gaze_reprojection_data, radii=20),\n",
    "        )\n",
    "\n",
    "        # Log the corresponding image\n",
    "        image_stream_label = device_data_provider.get_image_stream_label(stream_id)\n",
    "        # Retrieve the image data for a given timestamp\n",
    "        image_data = device_data_provider.get_image(timestamp_ns, stream_id)\n",
    "        # Visualize the image data (it's a numpy array)\n",
    "        log_image(label=f\"{stream_id}\", image=image_data)\n",
    "\n",
    "# Showing the rerun window\n",
    "rr.notebook_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4d6ac37-e3b3-401a-83b7-e09a42a183a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# - Section 5: Camera reprojection (reprojection hand vertices to raw fish images)\n",
    "#\n",
    "# Take home message\n",
    "#\n",
    "# - Each image/streamId is having its own calibration you can retrieve and use\n",
    "# - Using project(X) enables you to project a 3D point to a 2D image\n",
    "#\n",
    "\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "from typing import Any, Optional\n",
    "\n",
    "import numpy as np\n",
    "from data_loaders.HeadsetPose3dProvider import HeadsetPose3dProvider\n",
    "\n",
    "from data_loaders.loader_hand_poses import Handedness, HandPose3dCollection\n",
    "\n",
    "# Todo move up later\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "from projectaria_tools.core.calibration import CameraCalibration\n",
    "from projectaria_tools.core.sophus import SE3\n",
    "from projectaria_tools.core.stream_id import StreamId\n",
    "\n",
    "\n",
    "image_streamid = StreamId(\"214-1\")\n",
    "# image_streamid = StreamId(\"1201-1\")\n",
    "\n",
    "# timestamp_ns = timestamps[len(timestamps) // 2]\n",
    "timestamp_ns = timestamps[420]\n",
    "\n",
    "# Retrieve the image stream label as string\n",
    "image_stream_label = device_data_provider.get_image_stream_label(image_streamid)\n",
    "\n",
    "# Retrieve the image data for a given timestamp\n",
    "image_data = device_data_provider.get_image(timestamp_ns, image_streamid)\n",
    "\n",
    "# Retrieve the hand vertices and project them on the image at this timestamp\n",
    "def retrieve_hand_data(timestamp_ns: int) -> Optional[HandPose3dCollection]:\n",
    "    \"\"\"\n",
    "    Retrieve the collection of Hand Pose at this timestamp (i.e. LEFT or RIGHT hand)\n",
    "    Note: They are 3D pose in world, and does not say if they are visible for a given camera or not (stream_id)\n",
    "    Visibility can either being determined by using camera visibility (are vertices visible), or using the 2d hands bounding box\n",
    "    \"\"\"\n",
    "    hand_poses_with_dt = None\n",
    "    if hand_data_provider is not None:\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",
    "        )\n",
    "\n",
    "        if hand_poses_with_dt is not None:\n",
    "            return hand_poses_with_dt.pose3d_collection\n",
    "    return None\n",
    "\n",
    "\n",
    "def retrieve_device_pose(\n",
    "    timestamp_ns: int,\n",
    "    stream_id: StreamId,\n",
    "    device_pose_provider: Optional[HeadsetPose3dProvider] = None,\n",
    "    device_data_provider: Optional[Any] = None,\n",
    ") -> Optional[tuple[SE3, CameraCalibration]]:\n",
    "    \"\"\"\n",
    "    Retrieve the pose of the device and apply the device_camera transformation on top of it for the provided stream_id\n",
    "    \"\"\"\n",
    "    headset_pose3d_with_dt = None\n",
    "    if device_pose_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",
    "        )\n",
    "\n",
    "        if headset_pose3d_with_dt is not None:\n",
    "            headset_pose3d = headset_pose3d_with_dt.pose3d\n",
    "\n",
    "            # Retrieve the camera calibration (intrinsics and extrinsics) for a given stream_id\n",
    "            [extrinsics, intrinsics] = device_data_provider.get_camera_calibration(\n",
    "                stream_id\n",
    "            )\n",
    "            # The pose of the given camera at this timestamp is (world_camera = world_device @ device_camera):\n",
    "            world_camera_pose = headset_pose3d.T_world_device @ extrinsics\n",
    "            return [world_camera_pose, intrinsics]\n",
    "    return None\n",
    "\n",
    "\n",
    "# Retrieve the data for this timestamp\n",
    "hand_data = retrieve_hand_data(timestamp_ns)\n",
    "device_pose = retrieve_device_pose(\n",
    "    timestamp_ns, image_streamid, device_pose_provider, device_data_provider\n",
    ")\n",
    "\n",
    "if hand_data is not None and device_pose is not None:\n",
    "\n",
    "    device_pose_extrinsic = device_pose[0]\n",
    "    device_pose_intrinsic = device_pose[1]\n",
    "\n",
    "    # Visualize the image\n",
    "    plt.imshow(image_data, interpolation=\"nearest\")\n",
    "\n",
    "    # For each possible hand pose (Left or Right)\n",
    "    # Project the vertices in the camera and plot the visible one\n",
    "    for hand_pose_data in hand_data.poses.values():\n",
    "        # Retrieve the hand vertices and project them on the image at this timestamp\n",
    "        # hand_mesh_vertices = hand_data_provider.get_hand_mesh_vertices(\n",
    "        #     hand_pose_data\n",
    "        # ).tolist()\n",
    "\n",
    "        # Use Landmarks\n",
    "        hand_landmarks = hand_data_provider.get_hand_landmarks(hand_pose_data)\n",
    "        # convert landmarks to connected lines for display\n",
    "        hand_mesh_vertices = np.array([])\n",
    "        for connectivity in LANDMARK_CONNECTIVITY:\n",
    "            connections = np.array([])\n",
    "            for it in connectivity:\n",
    "                if len(connections) == 0:\n",
    "                    connections = [hand_landmarks[it].numpy()]\n",
    "                else:\n",
    "                    connections = np.vstack((connections, hand_landmarks[it].numpy()))\n",
    "            if len(hand_mesh_vertices) == 0:\n",
    "                hand_mesh_vertices = connections\n",
    "            else:\n",
    "                hand_mesh_vertices = np.vstack((hand_mesh_vertices, connections))\n",
    "\n",
    "        hand_vertices_in_camera = []\n",
    "        for vertex_in_world in hand_mesh_vertices:\n",
    "            vertice_3d_camera_coordinates = (\n",
    "                device_pose_extrinsic.inverse() @ vertex_in_world\n",
    "            )\n",
    "            vertice_2d_camera_coordinates = device_pose_intrinsic.project(\n",
    "                vertice_3d_camera_coordinates\n",
    "            )\n",
    "            if vertice_2d_camera_coordinates is not None:\n",
    "                hand_vertices_in_camera.append(vertice_2d_camera_coordinates)\n",
    "        handedness_label = hand_pose_data.handedness_label()\n",
    "        print(\n",
    "            f\"{handedness_label} hand -> visible vertices: {len(hand_vertices_in_camera)}\"\n",
    "        )\n",
    "\n",
    "        # Plot the hand vertices\n",
    "        plt.scatter(\n",
    "            x=[x[0] for x in hand_vertices_in_camera],\n",
    "            y=[x[1] for x in hand_vertices_in_camera],\n",
    "            s=1,\n",
    "            c=\"r\" if hand_pose_data.handedness == Handedness.Right else \"b\",\n",
    "        )\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}