coco.py 6.7 KB
Newer Older
G
Guanghua Yu 已提交
1 2 3 4 5 6 7 8 9 10 11 12
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. 
#   
# 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   
13 14 15 16
# limitations under the License.

import os
import numpy as np
G
Guanghua Yu 已提交
17
import logging
18
from ppdet.core.workspace import register, serializable
G
Guanghua Yu 已提交
19
from .dataset import DetDataset
20 21 22 23 24 25

logger = logging.getLogger(__name__)


@register
@serializable
G
Guanghua Yu 已提交
26
class COCODataSet(DetDataset):
27
    def __init__(self,
G
Guanghua Yu 已提交
28
                 dataset_dir=None,
29 30
                 image_dir=None,
                 anno_path=None,
31 32 33
                 mixup_epoch=-1,
                 cutmix_epoch=-1,
                 mosaic_epoch=-1,
K
Kaipeng Deng 已提交
34
                 sample_num=-1):
35 36 37 38 39 40 41 42
        super(COCODataSet, self).__init__(
            dataset_dir,
            image_dir,
            anno_path,
            sample_num,
            mixup_epoch=mixup_epoch,
            cutmix_epoch=cutmix_epoch,
            mosaic_epoch=mosaic_epoch)
W
wangguanzhong 已提交
43
        self.load_image_only = False
G
Guanghua Yu 已提交
44
        self.load_semantic = False
45

G
Guanghua Yu 已提交
46
    def parse_dataset(self, with_background=True):
47 48 49 50 51
        anno_path = os.path.join(self.dataset_dir, self.anno_path)
        image_dir = os.path.join(self.dataset_dir, self.image_dir)

        assert anno_path.endswith('.json'), \
            'invalid coco annotation file: ' + anno_path
W
wangguanzhong 已提交
52
        from pycocotools.coco import COCO
53 54 55 56 57 58 59 60 61
        coco = COCO(anno_path)
        img_ids = coco.getImgIds()
        cat_ids = coco.getCatIds()
        records = []
        ct = 0

        # when with_background = True, mapping category to classid, like:
        #   background:0, first_class:1, second_class:2, ...
        catid2clsid = dict({
K
Kaipeng Deng 已提交
62
            catid: i + int(with_background)
63 64 65 66 67 68 69
            for i, catid in enumerate(cat_ids)
        })
        cname2cid = dict({
            coco.loadCats(catid)[0]['name']: clsid
            for catid, clsid in catid2clsid.items()
        })

W
wangguanzhong 已提交
70 71 72 73 74
        if 'annotations' not in coco.dataset:
            self.load_image_only = True
            logger.warn('Annotation file: {} does not contains ground truth '
                        'and load image information only.'.format(anno_path))

75 76 77 78 79 80
        for img_id in img_ids:
            img_anno = coco.loadImgs(img_id)[0]
            im_fname = img_anno['file_name']
            im_w = float(img_anno['width'])
            im_h = float(img_anno['height'])

G
Guanghua Yu 已提交
81 82 83
            im_path = os.path.join(image_dir,
                                   im_fname) if image_dir else im_fname
            if not os.path.exists(im_path):
W
wangguanzhong 已提交
84
                logger.warn('Illegal image file: {}, and it will be '
G
Guanghua Yu 已提交
85
                            'ignored'.format(im_path))
W
wangguanzhong 已提交
86 87 88 89 90 91 92
                continue

            if im_w < 0 or im_h < 0:
                logger.warn('Illegal width: {} or height: {} in annotation, '
                            'and im_id: {} will be ignored'.format(im_w, im_h,
                                                                   img_id))
                continue
W
wangguanzhong 已提交
93

94
            coco_rec = {
G
Guanghua Yu 已提交
95
                'im_file': im_path,
96 97 98 99 100
                'im_id': np.array([img_id]),
                'h': im_h,
                'w': im_w,
            }

W
wangguanzhong 已提交
101 102 103
            if not self.load_image_only:
                ins_anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=False)
                instances = coco.loadAnns(ins_anno_ids)
G
Guanghua Yu 已提交
104

W
wangguanzhong 已提交
105 106
                bboxes = []
                for inst in instances:
G
Guanghua Yu 已提交
107 108 109 110 111 112
                    # check gt bbox
                    if 'bbox' not in inst.keys():
                        continue
                    else:
                        if not any(np.array(inst['bbox'])):
                            continue
W
wangguanzhong 已提交
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
                    x, y, box_w, box_h = inst['bbox']
                    x1 = max(0, x)
                    y1 = max(0, y)
                    x2 = min(im_w - 1, x1 + max(0, box_w - 1))
                    y2 = min(im_h - 1, y1 + max(0, box_h - 1))
                    if inst['area'] > 0 and x2 >= x1 and y2 >= y1:
                        inst['clean_bbox'] = [x1, y1, x2, y2]
                        bboxes.append(inst)
                    else:
                        logger.warn(
                            'Found an invalid bbox in annotations: im_id: {}, '
                            'area: {} x1: {}, y1: {}, x2: {}, y2: {}.'.format(
                                img_id, float(inst['area']), x1, y1, x2, y2))
                num_bbox = len(bboxes)

                gt_bbox = np.zeros((num_bbox, 4), dtype=np.float32)
                gt_class = np.zeros((num_bbox, 1), dtype=np.int32)
                gt_score = np.ones((num_bbox, 1), dtype=np.float32)
                is_crowd = np.zeros((num_bbox, 1), dtype=np.int32)
                difficult = np.zeros((num_bbox, 1), dtype=np.int32)
                gt_poly = [None] * num_bbox

                for i, box in enumerate(bboxes):
                    catid = box['category_id']
                    gt_class[i][0] = catid2clsid[catid]
                    gt_bbox[i, :] = box['clean_bbox']
                    is_crowd[i][0] = box['iscrowd']
G
Guanghua Yu 已提交
140
                    # check RLE format 
W
wangguanzhong 已提交
141
                    if 'segmentation' in box and box['iscrowd'] == 1:
G
Guanghua Yu 已提交
142
                        gt_poly[i] = [[0.0, 0.0], ]
W
wangguanzhong 已提交
143
                    elif 'segmentation' in box:
W
wangguanzhong 已提交
144 145
                        gt_poly[i] = box['segmentation']

G
Guanghua Yu 已提交
146 147 148
                if not any(gt_poly):
                    continue

W
wangguanzhong 已提交
149 150 151 152 153 154 155
                coco_rec.update({
                    'is_crowd': is_crowd,
                    'gt_class': gt_class,
                    'gt_bbox': gt_bbox,
                    'gt_score': gt_score,
                    'gt_poly': gt_poly,
                })
G
Guanghua Yu 已提交
156 157 158 159 160
                # TODO: remove load_semantic
                if self.load_semantic:
                    seg_path = os.path.join(self.dataset_dir, 'stuffthingmaps',
                                            'train2017', im_fname[:-3] + 'png')
                    coco_rec.update({'semantic': seg_path})
W
wangguanzhong 已提交
161

162
            logger.debug('Load file: {}, im_id: {}, h: {}, w: {}.'.format(
G
Guanghua Yu 已提交
163
                im_path, img_id, im_h, im_w))
164 165 166 167 168
            records.append(coco_rec)
            ct += 1
            if self.sample_num > 0 and ct >= self.sample_num:
                break
        assert len(records) > 0, 'not found any coco record in %s' % (anno_path)
Y
Yang Zhang 已提交
169
        logger.debug('{} samples in file {}'.format(ct, anno_path))
170
        self.roidbs, self.cname2cid = records, cname2cid