File size: 4,575 Bytes
6bb5048
 
 
 
 
 
 
 
58002d8
 
 
 
6bb5048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38bed2a
6bb5048
 
 
6f767b9
6bb5048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os

import datasets
from pycocotools.coco import COCO

_DESCRIPTION = 'A tiny coco2017 dataset example.'

_URLS = {
    'train': 'train2017.zip',
    'train_meta': 'annotations/instances_train2017.json',
    'val': 'val2017.zip',
    '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 TinyCoco(datasets.GeneratorBasedBuilder):
    """TODO: Short description of my dataset."""

    VERSION = datasets.Version('0.1.0')

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name='train', version=VERSION, description='Training set'),
        datasets.BuilderConfig(
            name='val', version=VERSION, description='Validation set'),
    ]
    # It's not mandatory to have a default configuration.
    # Just use one if it make sense.
    DEFAULT_CONFIG_NAME = 'train'

    def _info(self):
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION+f'\nCLASSES: ({",".join(_CLASSES)})'
        )

    def _split_generators(self, dl_manager):
        data_dir = dl_manager.download_and_extract(_URLS[self.config.name])
        meta = dl_manager.download(_URLS[self.config.name + '_meta'])
        return [
            datasets.SplitGenerator(
                name=self.config.name,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    'img_prefix': data_dir,
                    'ann_file': 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()
            info = coco.loadImgs([i])[0]
            sample['filename'] = os.path.join(img_prefix, info['file_name'])
            sample['height'] = info['height']
            sample['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 = []
            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, sample['width']) - max(x1, 0))
                inter_h = max(0, min(y1 + h, sample['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']])
                else:
                    gt_bboxes.append(bbox)
                    gt_labels.append(cat2label[ann['category_id']])
                    gt_masks_ann.append(ann.get('segmentation', None))

            sample['ann'] = dict(
                bboxes=gt_bboxes,
                labels=gt_labels,
                bboxes_ignore=gt_bboxes_ignore,
                label_ignore=gt_label_ignore)
            yield index, sample
            index += 1