point_data.py 6.62 KB
Newer Older
ZCMax's avatar
ZCMax committed
1
2
3
4
5
6
# Copyright (c) OpenMMLab. All rights reserved.
from collections.abc import Sized
from typing import Union

import numpy as np
import torch
7
from mmengine.structures import BaseDataElement
ZCMax's avatar
ZCMax committed
8
9
10
11
12
13
14

IndexType = Union[str, slice, int, list, torch.LongTensor,
                  torch.cuda.LongTensor, torch.BoolTensor,
                  torch.cuda.BoolTensor, np.ndarray]


class PointData(BaseDataElement):
15
    """Data structure for point-level annotations or predictions.
ZCMax's avatar
ZCMax committed
16
17
18
19
20
21
22

    All data items in ``data_fields`` of ``PointData`` meet the following
    requirements:

    - They are all one dimension.
    - They should have the same length.

23
24
25
26
    `PointData` is used to save point-level semantic and instance mask,
    it also can save `instances_labels` and `instances_scores` temporarily.
    In the future, we would consider to move the instance-level info into
    `gt_instances_3d` and `pred_instances_3d`.
ZCMax's avatar
ZCMax committed
27
28
29

    Examples:
        >>> metainfo = dict(
30
        ...     sample_idx=random.randint(0, 100))
ZCMax's avatar
ZCMax committed
31
32
33
34
        >>> points = np.random.randint(0, 255, (100, 3))
        >>> point_data = PointData(metainfo=metainfo,
        ...                        points=points)
        >>> print(len(point_data))
35
        100
ZCMax's avatar
ZCMax committed
36
37

        >>> # slice
38
39
        >>> slice_data = point_data[10:60]
        >>> assert len(slice_data) == 50
ZCMax's avatar
ZCMax committed
40
41

        >>> # set
42
43
44
45
        >>> point_data.pts_semantic_mask = torch.randint(0, 255, (100,))
        >>> point_data.pts_instance_mask = torch.randint(0, 255, (100,))
        >>> assert tuple(point_data.pts_semantic_mask.shape) == (100,)
        >>> assert tuple(point_data.pts_instance_mask.shape) == (100,)
ZCMax's avatar
ZCMax committed
46
47
    """

48
    def __setattr__(self, name: str, value: Sized) -> None:
ZCMax's avatar
ZCMax committed
49
50
        """setattr is only used to set data.

51
52
        The value must have the attribute of `__len__` and have the same length
        of `PointData`.
ZCMax's avatar
ZCMax committed
53
54
55
56
57
        """
        if name in ('_metainfo_fields', '_data_fields'):
            if not hasattr(self, name):
                super().__setattr__(name, value)
            else:
58
59
                raise AttributeError(f'{name} has been used as a '
                                     'private attribute, which is immutable.')
ZCMax's avatar
ZCMax committed
60
61
62

        else:
            assert isinstance(value,
63
64
                              Sized), 'value must contain `__len__` attribute'
            # TODO: make sure the input value share the same length
ZCMax's avatar
ZCMax committed
65
66
67
68
69
70
71
            super().__setattr__(name, value)

    __setitem__ = __setattr__

    def __getitem__(self, item: IndexType) -> 'PointData':
        """
        Args:
72
73
74
            item (str, int, list, :obj:`slice`, :obj:`numpy.ndarray`,
                :obj:`torch.LongTensor`, :obj:`torch.BoolTensor`):
                Get the corresponding values according to item.
ZCMax's avatar
ZCMax committed
75
76

        Returns:
77
            :obj:`PointData`: Corresponding values.
ZCMax's avatar
ZCMax committed
78
79
80
81
        """
        if isinstance(item, list):
            item = np.array(item)
        if isinstance(item, np.ndarray):
82
83
84
85
86
            # The default int type of numpy is platform dependent, int32 for
            # windows and int64 for linux. `torch.Tensor` requires the index
            # should be int64, therefore we simply convert it to int64 here.
            # Mode details in https://github.com/numpy/numpy/issues/9464
            item = item.astype(np.int64) if item.dtype == np.int32 else item
ZCMax's avatar
ZCMax committed
87
88
89
90
91
92
93
94
            item = torch.from_numpy(item)
        assert isinstance(
            item, (str, slice, int, torch.LongTensor, torch.cuda.LongTensor,
                   torch.BoolTensor, torch.cuda.BoolTensor))

        if isinstance(item, str):
            return getattr(self, item)

95
96
        if isinstance(item, int):
            if item >= len(self) or item < -len(self):  # type: ignore
ZCMax's avatar
ZCMax committed
97
98
99
100
101
102
103
104
105
106
                raise IndexError(f'Index {item} out of range!')
            else:
                # keep the dimension
                item = slice(item, None, len(self))

        new_data = self.__class__(metainfo=self.metainfo)
        if isinstance(item, torch.Tensor):
            assert item.dim() == 1, 'Only support to get the' \
                                    ' values along the first dimension.'
            if isinstance(item, (torch.BoolTensor, torch.cuda.BoolTensor)):
107
108
                assert len(item) == len(self), 'The shape of the ' \
                                               'input(BoolTensor) ' \
ZCMax's avatar
ZCMax committed
109
                                               f'{len(item)} ' \
110
111
112
                                               'does not match the shape ' \
                                               'of the indexed tensor ' \
                                               'in results_field ' \
ZCMax's avatar
ZCMax committed
113
                                               f'{len(self)} at ' \
114
                                               'first dimension.'
ZCMax's avatar
ZCMax committed
115
116
117
118
119
120
121
122
123

            for k, v in self.items():
                if isinstance(v, torch.Tensor):
                    new_data[k] = v[item]
                elif isinstance(v, np.ndarray):
                    new_data[k] = v[item.cpu().numpy()]
                elif isinstance(
                        v, (str, list, tuple)) or (hasattr(v, '__getitem__')
                                                   and hasattr(v, 'cat')):
124
                    # convert to indexes from BoolTensor
ZCMax's avatar
ZCMax committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
                    if isinstance(item,
                                  (torch.BoolTensor, torch.cuda.BoolTensor)):
                        indexes = torch.nonzero(item).view(
                            -1).cpu().numpy().tolist()
                    else:
                        indexes = item.cpu().numpy().tolist()
                    slice_list = []
                    if indexes:
                        for index in indexes:
                            slice_list.append(slice(index, None, len(v)))
                    else:
                        slice_list.append(slice(None, 0, None))
                    r_list = [v[s] for s in slice_list]
                    if isinstance(v, (str, list, tuple)):
                        new_value = r_list[0]
                        for r in r_list[1:]:
                            new_value = new_value + r
                    else:
                        new_value = v.cat(r_list)
                    new_data[k] = new_value
                else:
                    raise ValueError(
                        f'The type of `{k}` is `{type(v)}`, which has no '
                        'attribute of `cat`, so it does not '
149
                        'support slice with `bool`')
ZCMax's avatar
ZCMax committed
150
151
152
153
        else:
            # item is a slice
            for k, v in self.items():
                new_data[k] = v[item]
154
        return new_data  # type: ignore
ZCMax's avatar
ZCMax committed
155
156

    def __len__(self) -> int:
157
        """int: The length of `PointData`."""
ZCMax's avatar
ZCMax committed
158
159
160
161
        if len(self._data_fields) > 0:
            return len(self.values()[0])
        else:
            return 0