Datasets:

File size: 10,523 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Dict, List, Optional

import numpy as np
from data_loaders.frameset import compute_frameset_for_timestamp
from data_loaders.io_utils import load_json
from PIL import Image
from projectaria_tools.core.calibration import (  # @manual
    CameraCalibration,
    DeviceCadExtrinsics,
    DeviceCalibration,
    distort_by_calibration,
    FISHEYE624,
    get_linear_camera_calibration,
    LINEAR,
)
from projectaria_tools.core.sensor_data import TimeDomain  # @manual
from projectaria_tools.core.sophus import SE3  # @manual
from projectaria_tools.core.stream_id import StreamId  # @manual

try:
    from pyvrs import ImageConversion, SyncVRSReader  # @manual
except ImportError:
    from pyvrs2 import SyncVRSReader  # @manual
    from vrsbindings import ImageConversion  # @manual


class QuestDataProvider:
    #recording.vrs-----vrs_filepath,
    #camera_models.json---device_calibration_filepath,
    def __init__(self, vrs_filepath: str, device_calibration_filepath: str) -> None:
        #打开VRS 文件
        self._vrs_reader = SyncVRSReader(vrs_filepath)
        # Configure Image conversion
        #把所有图像像素值归一化到 [0, 1]
        self._vrs_reader.set_image_conversion(ImageConversion.NORMALIZE)
        #转换成 8位灰度图
        self._vrs_reader.set_stream_type_image_conversion(
            8010, ImageConversion.NORMALIZE_GREY8
        )

        # extract the streamids corresponding to the image streams
        #判断这个流是否包含图像,只保留图像流,过滤掉 IMU、音频等其他流。
        image_stream_ids = []
        for stream_id in self._vrs_reader.stream_ids:
            if self._vrs_reader.might_contain_images(stream_id):
                image_stream_ids.append(stream_id)
        image_stream_ids = sorted(image_stream_ids)
        image_stream_ids = []
        for stream_id in self._vrs_reader.stream_ids:
            if self._vrs_reader.might_contain_images(stream_id):
                image_stream_ids.append(stream_id)
        image_stream_ids = sorted(image_stream_ids)
        # Filter the reader
        filtered_reader = self._vrs_reader.filtered_by_fields(
            stream_ids=image_stream_ids
        )
        self._vrs_reader = filtered_reader

        # Loading camera calibration data
        device_calibration_json = load_json(device_calibration_filepath)
        camera_calibration = {}
        for it in device_calibration_json:
            quaternion = it["T_Device_Camera"]["quaternion_wxyz"]
            translation = it["T_Device_Camera"]["translation_xyz"]
            image_height = it["imageHeight"]
            image_width = it["imageWidth"]
            label = it["label"]
            max_solid_angle = 1  # Limiting the fov to a constant value.
            # projection_model_type = it["projectionModelType"]
            projection_params = it["projectionParams"]
            serial_number = it["serialNumber"]
            #两个分开的数据合并成一个 SE3 
            #有误导性的命名,T_world_device 实际上是从相机坐标系到设备坐标系的变换??
            T_world_device = SE3.from_quat_and_translation(
                quaternion[0],
                quaternion[1:4],
                translation,
            )
            # Skip focal_y and rely on a single focal length for x,y
            projection_params = projection_params[:1] + projection_params[2:]

            # Build the corresponding camera calibration object
            camera_calibration[label] = CameraCalibration(
                label,
                FISHEYE624,
                projection_params,
                T_world_device,
                image_width,
                image_height,
                None,
                max_solid_angle,
                serial_number,
            )

        self._device_calibration = DeviceCalibration(
            camera_calibration,
            {},
            {},
            {},
            {},
            DeviceCadExtrinsics(),
            "",
            "",
        )

        # Pre-compute the sorted timestamps for each image stream
        self._stream_timestamps_sorted: Dict[str, List[int]] = {}
        for stream_id in self.get_image_stream_ids():
            self._stream_timestamps_sorted[str(stream_id)] = sorted(
                self.get_sequence_timestamps()
            )

    def get_device_calibration(self) -> DeviceCalibration:
        """
        Return the device calibration (factory calibration of all sensors)
        """
        return self._device_calibration
    #返回设备的相机标定数据,以及每个摄像头的内参
    def get_camera_calibration(
        self,
        stream_id: StreamId,
        camera_model=FISHEYE624,
    ) -> tuple[SE3, CameraCalibration]:
        """
        Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics]
        Note:
         - A corresponding pinhole camera can be requested by using camera_model = LINEAR.
         - This is the camera model used to generate the 'get_undistorted_image'.
        """
        if not (camera_model is FISHEYE624 or camera_model is LINEAR):
            raise ValueError(
                "Invalid camera_model type, only FISHEYE624 and LINEAR are supported"
            )

        device_calibration = self.get_device_calibration()
        # Map the string to the right label
        stream_label = self.get_image_stream_label(stream_id)
        stream_labels_str = [
            self.get_image_stream_label(x) for x in self.get_image_stream_ids()
        ]
        idx_stream = stream_labels_str.index(stream_label)
        corresponding_calibration_label = device_calibration.get_camera_labels()[
            idx_stream
        ]
        camera_calibration = device_calibration.get_camera_calib(
            corresponding_calibration_label
        )

        # Store the relative transform from device to camera
        T_device_camera = camera_calibration.get_transform_device_camera()

        # If a corresponding pinhole camera is requested, we build one on the fly
        if camera_model == LINEAR:
            focal_lengths = camera_calibration.get_focal_lengths()
            image_size = camera_calibration.get_image_size()
            camera_calibration = get_linear_camera_calibration(
                image_size[0], image_size[1], focal_lengths[0]
            )
        # else return the native FISHEYE624 camera model

        return [T_device_camera, camera_calibration]

    def get_image_stream_ids(self) -> List[StreamId]:
        # retrieve all streams ids and filter the one that are image based
        image_stream_ids = []
        for stream_id in self._vrs_reader.stream_ids:
            if self._vrs_reader.might_contain_images(stream_id):
                image_stream_ids.append(stream_id)
        image_stream_ids = sorted(image_stream_ids)
        return [StreamId(x) for x in image_stream_ids]

    def get_sequence_timestamps(self) -> List[int]:
        """
        Returns the list of "time code" timestamp for the sequence
        """
        timestamps = self._vrs_reader.get_timestamp_list()
        # convert timestamp from float to int in ns
        return sorted({int(x * 1e9) for x in timestamps})

    def get_frameset_from_timestamp(
        self,
        timestamp_ns: int,
        frameset_acceptable_time_diff_ns: int,
        time_domain: TimeDomain = TimeDomain.TIME_CODE,
    ) -> Dict[str, Optional[int]]:
        """
        Computes a frameset from a given timestamp within an acceptable time difference.
        The frameset consists of the closest timestamps for each stream that are within the acceptable time difference.
        For Quest3, the recommended acceptable time difference is 1e6 ns (or 1ms).
        Returns a dictionary mapping each str(StreamId) to its closest timestamp.
        """
        if time_domain is not TimeDomain.TIME_CODE:
            raise ValueError(
                f"{time_domain} is not supported. Only TIME_CODE is supported"
            )
        out_frameset = compute_frameset_for_timestamp(
            stream_timestamps_sorted=self._stream_timestamps_sorted,
            target_timestamp=timestamp_ns,
            frameset_acceptable_time_diff=frameset_acceptable_time_diff_ns,
        )
        return out_frameset

    def get_image_stream_label(self, stream_id: StreamId) -> str:
        return str(stream_id)

    def get_image(self, timestamp_ns: int, stream_id: StreamId) -> Optional[np.ndarray]:
        try:
            record = self._vrs_reader.read_record_by_time(
                stream_id=self.get_image_stream_label(stream_id),
                timestamp=timestamp_ns / 1e9,
            )
        except ValueError as e:
            print(
                f"No record found for timestamp {timestamp_ns} and stream {stream_id}. Caught exception: {e}"
            )
            record = None

        if record is not None and record.record_type == "data":
            grey8 = Image.fromarray(record.image_blocks[0])
            return np.array(grey8)
        else:
            print(f"No image found for timestamp {timestamp_ns} and stream {stream_id}")
        return None

    def get_undistorted_image(
        self, timestamp_ns: int, stream_id: StreamId
    ) -> Optional[np.ndarray]:
        image = self.get_image(timestamp_ns, stream_id)
        if image is None:
            return None

        [T_device_camera, native_camera_calibration] = self.get_camera_calibration(
            stream_id, camera_model=FISHEYE624
        )
        [T_device_camera, pinhole_camera_calibration] = self.get_camera_calibration(
            stream_id, camera_model=LINEAR
        )

        # Compute the actual undistorted image
        undistorted_image = distort_by_calibration(
            image, pinhole_camera_calibration, native_camera_calibration
        )
        return undistorted_image