File size: 6,806 Bytes
fd86475 |
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 |
import gravdataset
import os
from gravdataset.features import Features, Sequence, Value
from pycocotools.coco import COCO
_DESCRIPTION = 'COCO dataset for detection and instance segmentation task.'
_URLS = {
'COCO2014': {
'train_prefix': 'train2014',
'train_meta': 'annotations/instances_train2014.json',
'val_prefix': 'val2014',
'val_meta': 'annotations/instances_val2014.json'
},
'COCO2017': {
'train_prefix': 'train2017',
'train_meta': 'annotations/instances_train2017.json',
'val_prefix': 'val2017',
'val_meta': 'annotations/instances_val2017.json'
},
}
_CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush')
class Coco(gravdataset.GeneratorBasedBuilder):
"""COCO dataset for detection and instance segmentation task."""
VERSION = gravdataset.Version('0.1.0')
BUILDER_CONFIGS = [
gravdataset.BuilderConfig(
name='COCO2014',
version=VERSION,
description='COCO2014 dataset for det and segm'),
gravdataset.BuilderConfig(
name='COCO2017',
version=VERSION,
description='COCO2017 dataset for det and segm'),
]
# It's not mandatory to have a default configuration.
# Just use one if it make sense.
DEFAULT_CONFIG_NAME = 'train'
def _info(self):
return gravdataset.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
meta_info=dict(classes=_CLASSES),
features=Features({
'img_info': {
'filename': Value('string'),
'height': Value('int32'),
'width': Value('int32'),
},
'ann_info': {
'bboxes': Sequence(Sequence(Value('float64'))),
'labels': Sequence(Value('int64')),
'masks': Sequence(Sequence(Sequence(Value('float64')))),
'bboxes_ignore': Sequence(Sequence(Value('float64'))),
'label_ignore': Sequence(Value('int64')),
'masks_ignore': Sequence(
{
'counts': Sequence(Value('int64')),
'size': Sequence(Value('int64'))
}
),
'seg_map': Value('string')
}
}))
def _split_generators(self, dl_manager):
train_prefix = _URLS[self.config.name]['train_prefix']
train_meta = _URLS[self.config.name]['train_meta']
val_prefix = _URLS[self.config.name]['val_prefix']
val_meta = _URLS[self.config.name]['val_meta']
train_meta = dl_manager.download(train_meta)
val_meta = dl_manager.download(val_meta)
return [
gravdataset.SplitGenerator(
name='train',
# These kwargs will be passed to _generate_examples
gen_kwargs={
'img_prefix': train_prefix,
'ann_file': train_meta
}),
gravdataset.SplitGenerator(
name='val',
# These kwargs will be passed to _generate_examples
gen_kwargs={
'img_prefix': val_prefix,
'ann_file': val_meta
}),
]
def _generate_examples(self, img_prefix, ann_file):
"""Parser coco format annotation file."""
coco = COCO(ann_file)
cat_ids = coco.getCatIds(_CLASSES)
cat2label = {cat_id: i for i, cat_id in enumerate(cat_ids)}
img_ids = coco.getImgIds()
index = 0
for i in img_ids:
sample = dict(img_info=dict())
info = coco.loadImgs([i])[0]
sample['img_info']['filename'] = os.path.join(
img_prefix, info['file_name'])
sample['img_info']['height'] = info['height']
sample['img_info']['width'] = info['width']
ann_ids = coco.getAnnIds([i])
ann_info = coco.loadAnns(ann_ids)
gt_bboxes = []
gt_labels = []
gt_bboxes_ignore = []
gt_label_ignore = []
gt_masks_ann = []
gt_masks_ignore = []
for i, ann in enumerate(ann_info):
if ann.get('ignore', False):
continue
x1, y1, w, h = ann['bbox']
inter_w = max(0, min(x1 + w, info['width']) - max(x1, 0))
inter_h = max(0, min(y1 + h, info['height']) - max(y1, 0))
if inter_w * inter_h == 0:
continue
if ann['area'] <= 0 or w < 1 or h < 1:
continue
if ann['category_id'] not in cat_ids:
continue
bbox = [x1, y1, x1 + w, y1 + h]
if ann.get('iscrowd', False):
gt_bboxes_ignore.append(bbox)
gt_label_ignore.append(cat2label[ann['category_id']])
gt_masks_ignore.append(ann.get('segmentation', None))
else:
gt_bboxes.append(bbox)
gt_labels.append(cat2label[ann['category_id']])
gt_masks_ann.append(ann.get('segmentation', None))
seg_map = sample['img_info']['filename'].rsplit('.', 1)[0] + '.png'
sample['ann_info'] = dict(
bboxes=gt_bboxes,
labels=gt_labels,
bboxes_ignore=gt_bboxes_ignore,
label_ignore=gt_label_ignore,
masks=gt_masks_ann,
masks_ignore=gt_masks_ignore,
seg_map=seg_map)
yield index, sample
index += 1
|