Datasets:

File size: 7,748 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
# 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
import logging
import os
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Set

from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions  # @manual
from projectaria_tools.core.stream_id import StreamId  # @manual

from .AlignedBox2d import AlignedBox2d
from .constants import BOX2D_DATA_CSV_COLUMNS
from .io_utils import float_or_none, is_float
from .loader_poses_utils import check_csv_columns
from .pose_utils import lookup_timestamp

logger = logging.getLogger(__name__)
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s",
)

#物体在图像上的 2D 边界框
@dataclass
class ObjectBox2d:
    box2d: Optional[AlignedBox2d]
    visibility_ratio: float


@dataclass
class ObjectBox2dCollection:
    timestamp_ns: int
    box2ds: Dict[str, ObjectBox2d]

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


ObjectBox2dTrajectory = Dict[
    int, ObjectBox2dCollection
]  # trajectory for a single stream
ObjectBox2dTrajectoryCollection = Dict[
    str, ObjectBox2dTrajectory
]  # trajectories for multiple streams


@dataclass
class ObjectBox2dCollectionWithDt:
    box2d_collection: ObjectBox2dCollection
    time_delta_ns: int


class ObjectBox2dProvider:
    def __init__(
        self, box2d_trajectory_collection: ObjectBox2dTrajectoryCollection
    ) -> None:
        #真正存数据的,但没有进行排序
        self._box2d_trajectory_collection = box2d_trajectory_collection
        #对时间戳进行排序,纯时间序列
        self._sorted_timestamp_ns_list: Dict[str, List[int]] = {}
        for stream_id in self._box2d_trajectory_collection.keys():
            self._sorted_timestamp_ns_list[stream_id] = sorted(
                self._box2d_trajectory_collection[stream_id].keys()
            )
        #生成一个set,里面是所有出现过的物体ID
        self._object_uids_with_box2ds: Set = {
            x
            for box2d_trajectory in self._box2d_trajectory_collection.values()
            for v in box2d_trajectory.values()
            for x in v.object_uid_list
        }

    def get_timestamp_ns_list(self, stream_id: StreamId) -> Optional[List[int]]:
        return self._sorted_timestamp_ns_list.get(str(stream_id), None)

    @property
    def stream_ids(self) -> List[StreamId]:
        return [StreamId(x) for x in self._box2d_trajectory_collection.keys()]

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

    def get_data_statistics(self) -> Dict[str, Any]:
        """
        Returns the stats for Object 2D bounding boxes
        """
        stats = {}
        stats["num_frames"] = {
            k: len(v) for k, v in self._sorted_timestamp_ns_list.items()
        }
        stats["stream_ids"] = [str(x) for x in self.stream_ids]
        stats["num_objects"] = len(self.object_uids)
        stats["object_uids"] = [str(x) for x in self.object_uids]
        return stats

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

        if stream_id not in self.stream_ids:
            raise ValueError(f"Box2d trajectory not available for stream {stream_id}.")

        box2d_collection, time_delta_ns = lookup_timestamp(
            time_indexed_dict=self._box2d_trajectory_collection[str(stream_id)],
            sorted_timestamp_list=self.get_timestamp_ns_list(stream_id=stream_id),
            query_timestamp=timestamp_ns,
            time_query_options=time_query_options,
        )

        if (
            box2d_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 ObjectBox2dCollectionWithDt(
                box2d_collection=box2d_collection, time_delta_ns=time_delta_ns
            )

# box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[object_uid] = (
#             object_box2d
#         )
def parse_box2ds_from_csv_reader(csv_reader) -> ObjectBox2dTrajectoryCollection:
    box2d_trajectory_collection: ObjectBox2dTrajectoryCollection = {}

    # Read the header row
    header = next(csv_reader)

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

    # Read the rest of the rows in the CSV file
    for row in csv_reader:
        stream_id = str(StreamId(row[header.index("stream_id")]))
        timestamp_ns = int(row[header.index("timestamp[ns]")])
        object_uid = str(row[header.index("object_uid")])
        visibility_ratio = float_or_none(row[header.index("visibility_ratio[%]")])
        
        #读取和存储已有的框
        if is_float(row[header.index("x_min[pixel]")]):
            x_min_px = float(row[header.index("x_min[pixel]")])
            x_max_px = float(row[header.index("x_max[pixel]")])
            y_min_px = float(row[header.index("y_min[pixel]")])
            y_max_px = float(row[header.index("y_max[pixel]")])

            box2d = AlignedBox2d(
                left=x_min_px, top=y_min_px, right=x_max_px, bottom=y_max_px
            )
        else:
            box2d = None

        object_box2d = ObjectBox2d(
            box2d=box2d,
            visibility_ratio=visibility_ratio,
        )

        if stream_id not in box2d_trajectory_collection:
            box2d_trajectory_collection[stream_id] = {}

        if timestamp_ns not in box2d_trajectory_collection[stream_id]:
            box2d_trajectory_collection[stream_id][timestamp_ns] = (
                ObjectBox2dCollection(timestamp_ns=timestamp_ns, box2ds={})
            )
        #由于ObjectBox2dCollection用的所对象,所以使用"."
        box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[object_uid] = (
            object_box2d
        )
    return box2d_trajectory_collection


def load_box2d_trajectory_from_csv(filename: str) -> Optional[ObjectBox2dProvider]:
    """Load Objects 2D bounding box meta data from a CSV file.

    Keyword arguments:
    filename -- the csv file i.e. sequence_folder + "/box2d_objects.csv"
    """

    if not os.path.exists(filename):
        logger.warn(f"filename: {filename} does not exist.")
        return None

    # Open the CSV file for reading
    with open(filename, "r") as f:
        csv_reader = csv.reader(f)
        box2d_trajectory_collection = parse_box2ds_from_csv_reader(
            csv_reader=csv_reader
        )
        return ObjectBox2dProvider(
            box2d_trajectory_collection=box2d_trajectory_collection
        )