Datasets:

File size: 6,478 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
# 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.

import csv
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Set

import numpy as np
from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions  # @manual
from projectaria_tools.core.sophus import SE3  # @manual

from .constants import POSE_DATA_CSV_COLUMNS
from .loader_poses_utils import check_csv_columns
from .pose_utils import lookup_timestamp


@dataclass
class ObjectPose3d:
    """
    Class to store pose of a single entity (object/headset/hand)
    """

    T_world_object: Optional[SE3] = None


@dataclass
class ObjectPose3dCollection:
    """
    Class to store the poses for a given timestamp
    """

    timestamp_ns: int
    poses: Dict[str, ObjectPose3d]

    @property
    def object_uid_list(self) -> Set[str]:
        return set(self.poses.keys())


ObjectPose3dTrajectory = Dict[int, ObjectPose3dCollection]


@dataclass
class ObjectPose3dCollectionWithDt:
    pose3d_collection: ObjectPose3dCollection
    time_delta_ns: int


class ObjectPose3dProvider(object):
    def __init__(self, pose3d_trajectory: ObjectPose3dTrajectory):
        self._pose3d_trajectory: ObjectPose3dTrajectory = pose3d_trajectory
        #排序时间戳
        self._sorted_timestamp_ns_list: List[int] = sorted(
            self._pose3d_trajectory.keys()
        )
        #所有出现过的物体ID
        self._object_uids_with_poses: Set = {
            x for v in self._pose3d_trajectory.values() for x in v.object_uid_list
        }

    #像属性一样访问,不用加括号
    @property
    def timestamp_ns_list(self) -> List[int]:
        return self._sorted_timestamp_ns_list

    @property
    def object_uids_with_poses(self) -> Set[str]:
        return set(self._object_uids_with_poses)

    def get_data_statistics(self) -> Dict[str, Any]:
        """
        Returns the stats of the trajectory
        """
        stats = {}
        stats["num_frames"] = len(self._sorted_timestamp_ns_list)
        stats["num_objects"] = len(self._object_uids_with_poses)
        stats["object_uids"] = [str(x) for x in self._object_uids_with_poses]
        return stats

    def get_pose_at_timestamp(
        self,
        timestamp_ns: int,
        time_query_options: TimeQueryOptions,
        time_domain: TimeDomain,
        acceptable_time_delta: Optional[int] = None,
    ) -> Optional[ObjectPose3dCollectionWithDt]:
        """
        Return the list of poses available at the given timestamp
        """
        if time_domain is not TimeDomain.TIME_CODE:
            raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.")

        pose3d_collection, time_delta_ns = lookup_timestamp(
            time_indexed_dict=self._pose3d_trajectory,
            sorted_timestamp_list=self._sorted_timestamp_ns_list,
            query_timestamp=timestamp_ns,
            time_query_options=time_query_options,
        )

        if (
            pose3d_collection is None
            or time_delta_ns is None
            or (
                acceptable_time_delta is not None
                and abs(time_delta_ns) > acceptable_time_delta
            )
        ):
            return None
        else:
            return ObjectPose3dCollectionWithDt(
                pose3d_collection=pose3d_collection, time_delta_ns=time_delta_ns
            )

#生成了一个pose3d_trajectory里面有物品在每个时间下的位置
def load_object_pose_trajectory_from_csv(filename: str) -> ObjectPose3dTrajectory:
    """Load Dynamic Objects meta data from a CSV file.

    Keyword arguments:
    filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv"
    """
    #空字典,后面逐行读 CSV 往里填数据
    pose3d_trajectory: ObjectPose3dTrajectory = {}
    # Open the CSV file for reading
    with open(filename, "r") as f:
        reader = csv.reader(f)

        # Read the header row
        #读表头
        header = next(reader)

        # Ensure we have the desired columns
        check_csv_columns(header, POSE_DATA_CSV_COLUMNS)

        # Read the rest of the rows in the CSV file
        for row in reader:
            #位置
            translation = [
                #"t_wo_x[m]" 这个字符串在 header 列表的第几位? 然后读取
                row[header.index("t_wo_x[m]")],
                row[header.index("t_wo_y[m]")],
                row[header.index("t_wo_z[m]")],
            ]
            #朝向
            quaternion_xyz = [
                ##"q_wo_x 这个字符串在 header 列表的第几位? 然后读取
                row[header.index("q_wo_x")],
                row[header.index("q_wo_y")],
                row[header.index("q_wo_z")],
            ]
            quaternion_w = row[header.index("q_wo_w")]
            timestamp_ns = int(row[header.index("timestamp[ns]")])
            object_uid = str(row[header.index("object_uid")])
            #把位置和朝向转换成 SE3 变换矩阵,se3 物品位置和朝向的信息    
            T_world_object = SE3.from_quat_and_translation(
                float(quaternion_w),
                np.array([float(o) for o in quaternion_xyz]),
                np.array([float(o) for o in translation]),
            )[0]

            pose3d = ObjectPose3d(T_world_object=T_world_object)
            #确保timestamp_ns有位置
            if timestamp_ns not in pose3d_trajectory:
                pose3d_trajectory[timestamp_ns] = ObjectPose3dCollection(
                    timestamp_ns=timestamp_ns, poses={}
                )

            pose3d_trajectory[timestamp_ns].poses[object_uid] = pose3d

    return pose3d_trajectory


def load_pose_provider_from_csv(filename: str) -> ObjectPose3dProvider:
    """
    Load the ObjectPose3dProvider from a csv file
    """
    return ObjectPose3dProvider(
        pose3d_trajectory=load_object_pose_trajectory_from_csv(filename)
    )