sunrgbd_data_utils.py 8.51 KB
Newer Older
liyinhao's avatar
liyinhao committed
1
import concurrent.futures as futures
2
3
import os

liyinhao's avatar
liyinhao committed
4
import mmcv
5
6
7
8
import numpy as np
import scipy.io as sio


9
def random_sampling(points, num_points, replace=None, return_choices=False):
liyinhao's avatar
liyinhao committed
10
    """Random Sampling.
liyinhao's avatar
liyinhao committed
11

12
    Sampling point cloud to a certain number of points.
liyinhao's avatar
liyinhao committed
13
14

    Args:
15
        points (ndarray): Point cloud.
16
        num_points (int): The number of samples.
liyinhao's avatar
liyinhao committed
17
18
19
20
        replace (bool): Whether the sample is with or without replacement.
        return_choices (bool): Whether to return choices.

    Returns:
21
        points (ndarray): Point cloud after sampling.
22
    """
liyinhao's avatar
liyinhao committed
23

24
    if replace is None:
25
26
        replace = (points.shape[0] < num_points)
    choices = np.random.choice(points.shape[0], num_points, replace=replace)
27
    if return_choices:
28
        return points[choices], choices
29
    else:
30
        return points[choices]
31
32


liyinhao's avatar
liyinhao committed
33
class SUNRGBDInstance(object):
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

    def __init__(self, line):
        data = line.split(' ')
        data[1:] = [float(x) for x in data[1:]]
        self.classname = data[0]
        self.xmin = data[1]
        self.ymin = data[2]
        self.xmax = data[1] + data[3]
        self.ymax = data[2] + data[4]
        self.box2d = np.array([self.xmin, self.ymin, self.xmax, self.ymax])
        self.centroid = np.array([data[5], data[6], data[7]])
        self.w = data[8]
        self.l = data[9]  # noqa: E741
        self.h = data[10]
        self.orientation = np.zeros((3, ))
        self.orientation[0] = data[11]
        self.orientation[1] = data[12]
        self.heading_angle = -1 * np.arctan2(self.orientation[1],
                                             self.orientation[0])
        self.box3d = np.concatenate([
            self.centroid,
            np.array([self.l * 2, self.w * 2, self.h * 2, self.heading_angle])
        ])


liyinhao's avatar
liyinhao committed
59
class SUNRGBDData(object):
liyinhao's avatar
liyinhao committed
60
    """SUNRGBD Data
liyinhao's avatar
liyinhao committed
61
62
63
64
65
66
67

    Generate scannet infos for sunrgbd_converter

    Args:
        root_path (str): Root path of the raw data.
        split (str): Set split type of the data. Default: 'train'.
        use_v1 (bool): Whether to use v1. Default: False.
liyinhao's avatar
liyinhao committed
68
    """
69
70
71
72
73

    def __init__(self, root_path, split='train', use_v1=False):
        self.root_dir = root_path
        self.split = split
        self.split_dir = os.path.join(root_path)
74
75
76
77
78
79
80
        self.classes = [
            'bed', 'table', 'sofa', 'chair', 'toilet', 'desk', 'dresser',
            'night_stand', 'bookshelf', 'bathtub'
        ]
        self.cat2label = {cat: self.classes.index(cat) for cat in self.classes}
        self.label2cat = {
            label: self.classes[label]
liyinhao's avatar
liyinhao committed
81
            for label in range(len(self.classes))
82
83
        }
        assert split in ['train', 'val', 'test']
84
85
86
        split_file = os.path.join(self.root_dir, f'{split}_data_idx.txt')
        mmcv.check_file_exist(split_file)
        self.sample_id_list = map(int, mmcv.list_from_file(split_file))
87
88
89
90
91
92
93
94
95
96
97
98
        self.image_dir = os.path.join(self.split_dir, 'image')
        self.calib_dir = os.path.join(self.split_dir, 'calib')
        self.depth_dir = os.path.join(self.split_dir, 'depth')
        if use_v1:
            self.label_dir = os.path.join(self.split_dir, 'label_v1')
        else:
            self.label_dir = os.path.join(self.split_dir, 'label')

    def __len__(self):
        return len(self.sample_id_list)

    def get_image(self, idx):
liyinhao's avatar
liyinhao committed
99
        img_filename = os.path.join(self.image_dir, f'{idx:06d}.jpg')
liyinhao's avatar
liyinhao committed
100
        return mmcv.imread(img_filename)
101
102
103
104
105
106

    def get_image_shape(self, idx):
        image = self.get_image(idx)
        return np.array(image.shape[:2], dtype=np.int32)

    def get_depth(self, idx):
liyinhao's avatar
liyinhao committed
107
        depth_filename = os.path.join(self.depth_dir, f'{idx:06d}.mat')
108
109
110
111
        depth = sio.loadmat(depth_filename)['instance']
        return depth

    def get_calibration(self, idx):
liyinhao's avatar
liyinhao committed
112
        calib_filepath = os.path.join(self.calib_dir, f'{idx:06d}.txt')
113
114
115
116
117
118
119
        lines = [line.rstrip() for line in open(calib_filepath)]
        Rt = np.array([float(x) for x in lines[0].split(' ')])
        Rt = np.reshape(Rt, (3, 3), order='F')
        K = np.array([float(x) for x in lines[1].split(' ')])
        return K, Rt

    def get_label_objects(self, idx):
liyinhao's avatar
liyinhao committed
120
        label_filename = os.path.join(self.label_dir, f'{idx:06d}.txt')
121
        lines = [line.rstrip() for line in open(label_filename)]
liyinhao's avatar
liyinhao committed
122
        objects = [SUNRGBDInstance(line) for line in lines]
123
124
        return objects

liyinhao's avatar
liyinhao committed
125
    def get_infos(self, num_workers=4, has_label=True, sample_id_list=None):
liyinhao's avatar
liyinhao committed
126
        """Get data infos.
liyinhao's avatar
liyinhao committed
127
128
129
130
131
132

        This method gets information from the raw data.

        Args:
            num_workers (int): Number of threads to be used. Default: 4.
            has_label (bool): Whether the data has label. Default: True.
liyinhao's avatar
liyinhao committed
133
134
            sample_id_list (List[int]): Index list of the sample.
                Default: None.
liyinhao's avatar
liyinhao committed
135
136
137

        Returns:
            infos (List[dict]): Information of the raw data.
liyinhao's avatar
liyinhao committed
138
        """
139
140

        def process_single_scene(sample_idx):
liyinhao's avatar
liyinhao committed
141
            print(f'{self.split} sample_idx: {sample_idx}')
142
            # convert depth to points
liyinhao's avatar
liyinhao committed
143
            SAMPLE_NUM = 50000
144
145
            # TODO: Check whether can move the point
            #  sampling process during training.
146
147
148
            pc_upright_depth = self.get_depth(sample_idx)
            pc_upright_depth_subsampled = random_sampling(
                pc_upright_depth, SAMPLE_NUM)
149
            np.save(
liyinhao's avatar
liyinhao committed
150
                os.path.join(self.root_dir, 'lidar', f'{sample_idx:06d}.npy'),
151
                pc_upright_depth_subsampled)
152
153
154
155

            info = dict()
            pc_info = {'num_features': 6, 'lidar_idx': sample_idx}
            info['point_cloud'] = pc_info
liyinhao's avatar
liyinhao committed
156
            img_name = os.path.join(self.image_dir, f'{sample_idx:06d}')
157
            img_path = os.path.join(self.image_dir, img_name)
158
159
            image_info = {
                'image_idx': sample_idx,
160
161
                'image_shape': self.get_image_shape(sample_idx),
                'image_path': img_path
162
163
164
165
166
167
168
169
170
171
172
173
            }
            info['image'] = image_info

            K, Rt = self.get_calibration(sample_idx)
            calib_info = {'K': K, 'Rt': Rt}
            info['calib'] = calib_info

            if has_label:
                obj_list = self.get_label_objects(sample_idx)
                annotations = {}
                annotations['gt_num'] = len([
                    obj.classname for obj in obj_list
174
                    if obj.classname in self.cat2label.keys()
175
176
177
178
                ])
                if annotations['gt_num'] != 0:
                    annotations['name'] = np.array([
                        obj.classname for obj in obj_list
179
                        if obj.classname in self.cat2label.keys()
180
181
182
                    ])
                    annotations['bbox'] = np.concatenate([
                        obj.box2d.reshape(1, 4) for obj in obj_list
183
                        if obj.classname in self.cat2label.keys()
184
185
186
187
                    ],
                                                         axis=0)
                    annotations['location'] = np.concatenate([
                        obj.centroid.reshape(1, 3) for obj in obj_list
188
                        if obj.classname in self.cat2label.keys()
189
190
191
192
                    ],
                                                             axis=0)
                    annotations['dimensions'] = 2 * np.array([
                        [obj.l, obj.h, obj.w] for obj in obj_list
193
                        if obj.classname in self.cat2label.keys()
194
195
196
                    ])  # lhw(depth) format
                    annotations['rotation_y'] = np.array([
                        obj.heading_angle for obj in obj_list
197
                        if obj.classname in self.cat2label.keys()
198
199
200
201
                    ])
                    annotations['index'] = np.arange(
                        len(obj_list), dtype=np.int32)
                    annotations['class'] = np.array([
202
203
                        self.cat2label[obj.classname] for obj in obj_list
                        if obj.classname in self.cat2label.keys()
204
205
206
207
                    ])
                    annotations['gt_boxes_upright_depth'] = np.stack(
                        [
                            obj.box3d for obj in obj_list
208
                            if obj.classname in self.cat2label.keys()
209
210
211
212
213
214
                        ],
                        axis=0)  # (K,8)
                info['annos'] = annotations
            return info

        lidar_save_dir = os.path.join(self.root_dir, 'lidar')
215
        mmcv.mkdir_or_exist(lidar_save_dir)
216
217
218
219
220
        sample_id_list = sample_id_list if \
            sample_id_list is not None else self.sample_id_list
        with futures.ThreadPoolExecutor(num_workers) as executor:
            infos = executor.map(process_single_scene, sample_id_list)
        return list(infos)