Datasets:

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

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 HAND_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",
)


@dataclass
class HandBox2d:
    box2d: AlignedBox2d
    visibility_ratio: float


@dataclass
class HandBox2dCollection:
    timestamp_ns: int
    box2ds: Dict[int, HandBox2d]


HandBox2dTrajectory = Dict[int, HandBox2dCollection]  # trajectory for a single stream
HandBox2dTrajectoryCollection = Dict[
    str, HandBox2dTrajectory
]  # trajectories for multiple streams


@dataclass
class HandBox2dCollectionWithDt:
    box2d_collection: HandBox2dCollection
    time_delta_ns: int

#box2ds: Dict[int, HandBox2d]
class HandBox2dProvider:
    def __init__(
        self, box2d_trajectory_collection: HandBox2dTrajectoryCollection
    ) -> 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()
            )

    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()]

    def get_data_statistics(self) -> Dict[str, Any]:
        """
        Returns the stats for Hand 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]
        return stats

    def get_bbox_at_timestamp(
        self,
        stream_id: StreamId,
        timestamp_ns: int,
        time_query_options: TimeQueryOptions,
        time_domain: TimeDomain,
    ) -> Optional[HandBox2dCollectionWithDt]:
        """
        Return the list of poses 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:
            return None
        else:
            return HandBox2dCollectionWithDt(
                box2d_collection=box2d_collection, time_delta_ns=time_delta_ns
            )


def parse_box2ds_from_csv_reader(csv_reader) -> HandBox2dTrajectoryCollection:
    box2d_trajectory_collection: HandBox2dTrajectoryCollection = {}

    # Read the header row
    header = next(csv_reader)

    # Ensure we have the desired columns
    check_csv_columns(header, HAND_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]")])
        hand_index = int(row[header.index("hand_index")])
        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 = HandBox2d(
            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] = HandBox2dCollection(
                timestamp_ns=timestamp_ns, box2ds={}
            )

        box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[hand_index] = (
            object_box2d
        )
    return box2d_trajectory_collection


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

    Keyword arguments:
    filename -- the csv file i.e. sequence_folder + "/box2d_hands.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 HandBox2dProvider(
            box2d_trajectory_collection=box2d_trajectory_collection
        )