coco.py 12.9 KB
Newer Older
Kai Chen's avatar
Kai Chen committed
1
2
3
4
import os.path as osp

import mmcv
import numpy as np
Kai Chen's avatar
Kai Chen committed
5
from mmcv.parallel import DataContainer as DC
Kai Chen's avatar
Kai Chen committed
6
7
8
from pycocotools.coco import COCO
from torch.utils.data import Dataset

Kai Chen's avatar
Kai Chen committed
9
from .transforms import (ImageTransform, BboxTransform, MaskTransform,
Kai Chen's avatar
Kai Chen committed
10
                         Numpy2Tensor)
Kai Chen's avatar
Kai Chen committed
11
from .utils import to_tensor, show_ann, random_scale
Kai Chen's avatar
Kai Chen committed
12
13
14


class CocoDataset(Dataset):
Kai Chen's avatar
Kai Chen committed
15

Kai Chen's avatar
Kai Chen committed
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
    def __init__(self,
                 ann_file,
                 img_prefix,
                 img_scale,
                 img_norm_cfg,
                 size_divisor=None,
                 proposal_file=None,
                 num_max_proposals=1000,
                 flip_ratio=0,
                 with_mask=True,
                 with_crowd=True,
                 with_label=True,
                 test_mode=False,
                 debug=False):
        # path of the data file
        self.coco = COCO(ann_file)
        # filter images with no annotation during training
        if not test_mode:
            self.img_ids, self.img_infos = self._filter_imgs()
        else:
            self.img_ids = self.coco.getImgIds()
            self.img_infos = [
                self.coco.loadImgs(idx)[0] for idx in self.img_ids
            ]
        assert len(self.img_ids) == len(self.img_infos)
        # get the mapping from original category ids to labels
        self.cat_ids = self.coco.getCatIds()
        self.cat2label = {
            cat_id: i + 1
            for i, cat_id in enumerate(self.cat_ids)
        }
        # prefix of images path
        self.img_prefix = img_prefix
        # (long_edge, short_edge) or [(long1, short1), (long2, short2), ...]
        self.img_scales = img_scale if isinstance(img_scale,
                                                  list) else [img_scale]
        assert mmcv.is_list_of(self.img_scales, tuple)
        # color channel order and normalize configs
        self.img_norm_cfg = img_norm_cfg
        # proposals
pangjm's avatar
pangjm committed
56
57
58
59
60
61
62
63
        # TODO: revise _filter_imgs to be more flexible
        if proposal_file is not None:
            self.proposals = mmcv.load(proposal_file)
            ori_ids = self.coco.getImgIds()
            sorted_idx = [ori_ids.index(id) for id in self.img_ids]
            self.proposals = [self.proposals[idx] for idx in sorted_idx]
        else:
            self.proposals = None
Kai Chen's avatar
Kai Chen committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        self.num_max_proposals = num_max_proposals
        # flip ratio
        self.flip_ratio = flip_ratio
        assert flip_ratio >= 0 and flip_ratio <= 1
        # padding border to ensure the image size can be divided by
        # size_divisor (used for FPN)
        self.size_divisor = size_divisor
        # with crowd or not, False when using RetinaNet
        self.with_crowd = with_crowd
        # with mask or not
        self.with_mask = with_mask
        # with label is False for RPN
        self.with_label = with_label
        # in test mode or not
        self.test_mode = test_mode
        # debug mode or not
        self.debug = debug

        # set group flag for the sampler
        self._set_group_flag()
        # transforms
        self.img_transform = ImageTransform(
            size_divisor=self.size_divisor, **self.img_norm_cfg)
        self.bbox_transform = BboxTransform()
Kai Chen's avatar
Kai Chen committed
88
        self.mask_transform = MaskTransform()
Kai Chen's avatar
Kai Chen committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        self.numpy2tensor = Numpy2Tensor()

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

    def _filter_imgs(self, min_size=32):
        """Filter images too small or without ground truths."""
        img_ids = list(set([_['image_id'] for _ in self.coco.anns.values()]))
        valid_ids = []
        img_infos = []
        for i in img_ids:
            info = self.coco.loadImgs(i)[0]
            if min(info['width'], info['height']) >= min_size:
                valid_ids.append(i)
                img_infos.append(info)
        return valid_ids, img_infos

    def _load_ann_info(self, idx):
        img_id = self.img_ids[idx]
        ann_ids = self.coco.getAnnIds(imgIds=img_id)
        ann_info = self.coco.loadAnns(ann_ids)
        return ann_info

Kai Chen's avatar
Kai Chen committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    def _parse_ann_info(self, ann_info, with_mask=True):
        """Parse bbox and mask annotation.

        Args:
            ann_info (list[dict]): Annotation info of an image.
            with_mask (bool): Whether to parse mask annotations.

        Returns:
            dict: A dict containing the following keys: bboxes, bboxes_ignore,
                labels, masks, mask_polys, poly_lens.
        """
        gt_bboxes = []
        gt_labels = []
        gt_bboxes_ignore = []
Kai Chen's avatar
Kai Chen committed
126
127
128
129
        # Two formats are provided.
        # 1. mask: a binary map of the same size of the image.
        # 2. polys: each mask consists of one or several polys, each poly is a
        # list of float.
Kai Chen's avatar
Kai Chen committed
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
        if with_mask:
            gt_masks = []
            gt_mask_polys = []
            gt_poly_lens = []
        for i, ann in enumerate(ann_info):
            if ann.get('ignore', False):
                continue
            x1, y1, w, h = ann['bbox']
            if ann['area'] <= 0 or w < 1 or h < 1:
                continue
            bbox = [x1, y1, x1 + w - 1, y1 + h - 1]
            if ann['iscrowd']:
                gt_bboxes_ignore.append(bbox)
            else:
                gt_bboxes.append(bbox)
                gt_labels.append(self.cat2label[ann['category_id']])
            if with_mask:
                gt_masks.append(self.coco.annToMask(ann))
                mask_polys = [
                    p for p in ann['segmentation'] if len(p) >= 6
                ]  # valid polygons have >= 3 points (6 coordinates)
                poly_lens = [len(p) for p in mask_polys]
                gt_mask_polys.append(mask_polys)
                gt_poly_lens.extend(poly_lens)
        if gt_bboxes:
            gt_bboxes = np.array(gt_bboxes, dtype=np.float32)
            gt_labels = np.array(gt_labels, dtype=np.int64)
        else:
            gt_bboxes = np.zeros((0, 4), dtype=np.float32)
            gt_labels = np.array([], dtype=np.int64)

        if gt_bboxes_ignore:
            gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)
        else:
            gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)

        ann = dict(
            bboxes=gt_bboxes, labels=gt_labels, bboxes_ignore=gt_bboxes_ignore)

        if with_mask:
            ann['masks'] = gt_masks
            # poly format is not used in the current implementation
            ann['mask_polys'] = gt_mask_polys
            ann['poly_lens'] = gt_poly_lens
        return ann

Kai Chen's avatar
Kai Chen committed
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
    def _set_group_flag(self):
        """Set flag according to image aspect ratio.

        Images with aspect ratio greater than 1 will be set as group 1,
        otherwise group 0.
        """
        self.flag = np.zeros(len(self.img_ids), dtype=np.uint8)
        for i in range(len(self.img_ids)):
            img_info = self.img_infos[i]
            if img_info['width'] / img_info['height'] > 1:
                self.flag[i] = 1

    def _rand_another(self, idx):
        pool = np.where(self.flag == self.flag[idx])[0]
        return np.random.choice(pool)

    def __getitem__(self, idx):
        if self.test_mode:
            return self.prepare_test_img(idx)
        while True:
            img_info = self.img_infos[idx]
            ann_info = self._load_ann_info(idx)

            # load image
            img = mmcv.imread(osp.join(self.img_prefix, img_info['file_name']))
            if self.debug:
                show_ann(self.coco, img, ann_info)

            # load proposals if necessary
            if self.proposals is not None:
206
                proposals = self.proposals[idx][:self.num_max_proposals]
Kai Chen's avatar
Kai Chen committed
207
208
209
210
211
212
                # TODO: Handle empty proposals properly. Currently images with
                # no proposals are just ignored, but they can be used for
                # training in concept.
                if len(proposals) == 0:
                    idx = self._rand_another(idx)
                    continue
myownskyW7's avatar
myownskyW7 committed
213
214
215
216
                if not (proposals.shape[1] == 4 or proposals.shape[1] == 5):
                    raise AssertionError(
                        'proposals should have shapes (n, 4) or (n, 5), '
                        'but found {}'.format(proposals.shape))
217
218
219
220
221
                if proposals.shape[1] == 5:
                    scores = proposals[:, 4]
                    proposals = proposals[:, :4]
                else:
                    scores = None
Kai Chen's avatar
Kai Chen committed
222

Kai Chen's avatar
Kai Chen committed
223
            ann = self._parse_ann_info(ann_info, self.with_mask)
Kai Chen's avatar
Kai Chen committed
224
225
226
227
228
229
230
231
232
233
234
            gt_bboxes = ann['bboxes']
            gt_labels = ann['labels']
            gt_bboxes_ignore = ann['bboxes_ignore']
            # skip the image if there is no valid gt bbox
            if len(gt_bboxes) == 0:
                idx = self._rand_another(idx)
                continue

            # apply transforms
            flip = True if np.random.rand() < self.flip_ratio else False
            img_scale = random_scale(self.img_scales)  # sample a scale
Kai Chen's avatar
Kai Chen committed
235
            img, img_shape, pad_shape, scale_factor = self.img_transform(
Kai Chen's avatar
Kai Chen committed
236
237
238
239
                img, img_scale, flip)
            if self.proposals is not None:
                proposals = self.bbox_transform(proposals, img_shape,
                                                scale_factor, flip)
240
241
                proposals = np.hstack([proposals, scores[:, None]
                                       ]) if scores is not None else proposals
Kai Chen's avatar
Kai Chen committed
242
243
244
245
246
247
            gt_bboxes = self.bbox_transform(gt_bboxes, img_shape, scale_factor,
                                            flip)
            gt_bboxes_ignore = self.bbox_transform(gt_bboxes_ignore, img_shape,
                                                   scale_factor, flip)

            if self.with_mask:
Kai Chen's avatar
Kai Chen committed
248
249
                gt_masks = self.mask_transform(ann['masks'], pad_shape,
                                               scale_factor, flip)
Kai Chen's avatar
Kai Chen committed
250

Kai Chen's avatar
Kai Chen committed
251
            ori_shape = (img_info['height'], img_info['width'], 3)
Kai Chen's avatar
Kai Chen committed
252
            img_meta = dict(
Kai Chen's avatar
Kai Chen committed
253
254
                ori_shape=ori_shape,
                img_shape=img_shape,
Kai Chen's avatar
Kai Chen committed
255
                pad_shape=pad_shape,
Kai Chen's avatar
Kai Chen committed
256
257
                scale_factor=scale_factor,
                flip=flip)
Kai Chen's avatar
Kai Chen committed
258
259

            data = dict(
Kai Chen's avatar
Kai Chen committed
260
261
262
                img=DC(to_tensor(img), stack=True),
                img_meta=DC(img_meta, cpu_only=True),
                gt_bboxes=DC(to_tensor(gt_bboxes)))
Kai Chen's avatar
Kai Chen committed
263
            if self.proposals is not None:
Kai Chen's avatar
Kai Chen committed
264
                data['proposals'] = DC(to_tensor(proposals))
Kai Chen's avatar
Kai Chen committed
265
            if self.with_label:
Kai Chen's avatar
Kai Chen committed
266
                data['gt_labels'] = DC(to_tensor(gt_labels))
Kai Chen's avatar
Kai Chen committed
267
            if self.with_crowd:
Kai Chen's avatar
Kai Chen committed
268
                data['gt_bboxes_ignore'] = DC(to_tensor(gt_bboxes_ignore))
Kai Chen's avatar
Kai Chen committed
269
            if self.with_mask:
Kai Chen's avatar
Kai Chen committed
270
                data['gt_masks'] = DC(gt_masks, cpu_only=True)
Kai Chen's avatar
Kai Chen committed
271
272
273
274
            return data

    def prepare_test_img(self, idx):
        """Prepare an image for testing (multi-scale and flipping)"""
pangjm's avatar
pangjm committed
275
276
        img_info = self.img_infos[idx]
        img = mmcv.imread(osp.join(self.img_prefix, img_info['file_name']))
277
278
        if self.proposals is not None:
            proposal = self.proposals[idx][:self.num_max_proposals]
myownskyW7's avatar
myownskyW7 committed
279
280
281
282
            if not (proposal.shape[1] == 4 or proposal.shape[1] == 5):
                raise AssertionError(
                    'proposals should have shapes (n, 4) or (n, 5), '
                    'but found {}'.format(proposal.shape))
myownskyW7's avatar
myownskyW7 committed
283
284
        else:
            proposal = None
Kai Chen's avatar
Kai Chen committed
285

pangjm's avatar
pangjm committed
286
        def prepare_single(img, scale, flip, proposal=None):
Kai Chen's avatar
Kai Chen committed
287
            _img, img_shape, pad_shape, scale_factor = self.img_transform(
pangjm's avatar
pangjm committed
288
                img, scale, flip)
Kai Chen's avatar
Kai Chen committed
289
290
291
            _img = to_tensor(_img)
            _img_meta = dict(
                ori_shape=(img_info['height'], img_info['width'], 3),
pangjm's avatar
pangjm committed
292
                img_shape=img_shape,
Kai Chen's avatar
Kai Chen committed
293
                pad_shape=pad_shape,
pangjm's avatar
pangjm committed
294
295
                scale_factor=scale_factor,
                flip=flip)
Kai Chen's avatar
Kai Chen committed
296
            if proposal is not None:
297
298
299
300
301
                if proposal.shape[1] == 5:
                    score = proposal[:, 4]
                    proposal = proposal[:, :4]
                else:
                    score = None
pangjm's avatar
pangjm committed
302
303
                _proposal = self.bbox_transform(proposal, img_shape,
                                                scale_factor, flip)
304
305
                _proposal = np.hstack([_proposal, score[:, None]
                                       ]) if score is not None else _proposal
Kai Chen's avatar
Kai Chen committed
306
307
308
309
                _proposal = to_tensor(_proposal)
            else:
                _proposal = None
            return _img, _img_meta, _proposal
Kai Chen's avatar
Kai Chen committed
310
311
312
313

        imgs = []
        img_metas = []
        proposals = []
pangjm's avatar
pangjm committed
314
        for scale in self.img_scales:
Kai Chen's avatar
Kai Chen committed
315
316
317
318
319
            _img, _img_meta, _proposal = prepare_single(
                img, scale, False, proposal)
            imgs.append(_img)
            img_metas.append(DC(_img_meta, cpu_only=True))
            proposals.append(_proposal)
Kai Chen's avatar
Kai Chen committed
320
            if self.flip_ratio > 0:
Kai Chen's avatar
Kai Chen committed
321
322
323
324
325
326
327
328
329
                _img, _img_meta, _proposal = prepare_single(
                    img, scale, True, proposal)
                imgs.append(_img)
                img_metas.append(DC(_img_meta, cpu_only=True))
                proposals.append(_proposal)
        data = dict(img=imgs, img_meta=img_metas)
        if self.proposals is not None:
            data['proposals'] = proposals
        return data