File size: 13,520 Bytes
db6eb0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dc6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
db6eb0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dc6d2
 
db6eb0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3dc6d2
 
db6eb0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
175
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import copy
import json
import logging
import os
from collections import defaultdict
from typing import Dict, TypedDict

import datasets as ds

logger = logging.getLogger(__name__)

_CITATION = """\
@INPROCEEDINGS{caesar2018cvpr,
  title={COCO-Stuff: Thing and stuff classes in context},
  author={Caesar, Holger and Uijlings, Jasper and Ferrari, Vittorio},
  booktitle={Computer vision and pattern recognition (CVPR), 2018 IEEE conference on},
  organization={IEEE},
  year={2018}
}
"""

_DESCRIPTION = """\
COCO-Stuff augments all 164K images of the popular COCO dataset with pixel-level stuff annotations. These annotations can be used for scene understanding tasks like semantic segmentation, object detection and image captioning.
"""

_HOMEPAGE = "https://github.com/nightrome/cocostuff"

_LICENSE = """\
COCO-Stuff is a derivative work of the COCO dataset. The authors of COCO do not in any form endorse this work. Different licenses apply:
- COCO images: Flickr Terms of use
- COCO annotations: Creative Commons Attribution 4.0 License
- COCO-Stuff annotations & code: Creative Commons Attribution 4.0 License
"""


class URLs(TypedDict):
    train: str
    val: str
    stuffthingmaps_trainval: str
    stuff_trainval: str
    labels: str


_URLS: URLs = {
    "train": "http://images.cocodataset.org/zips/train2017.zip",
    "val": "http://images.cocodataset.org/zips/val2017.zip",
    "stuffthingmaps_trainval": "http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip",
    "stuff_trainval": "http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuff_trainval2017.zip",
    "labels": "https://raw.githubusercontent.com/nightrome/cocostuff/master/labels.txt",
}


class GenerateExamplesArguments(TypedDict):
    image_dirpath: str
    stuff_dirpath: str
    stuff_thing_maps_dirpath: str
    labels_path: str
    split: str


def _load_json(json_path: str):
    logger.info(f"Load json from {json_path}")
    with open(json_path, "r") as rf:
        json_data = json.load(rf)
    return json_data


def _load_labels(labels_path: str) -> Dict[int, str]:
    label_id_to_label_name: Dict[int, str] = {}

    logger.info(f"Load labels from {labels_path}")
    with open(labels_path, "r") as rf:
        for line in rf:
            label_id_str, label_name = line.strip().split(": ")
            label_id = int(label_id_str)

            # correspondence between .png annotation & category_id 路 Issue #17 路 nightrome/cocostuff https://github.com/nightrome/cocostuff/issues/17
            # Label matching, 182 or 183 labels? 路 Issue #8 路 nightrome/cocostuff https://github.com/nightrome/cocostuff/issues/8
            if label_id == 0:
                # for unlabeled class
                assert label_name == "unlabeled", label_name
                label_id_to_label_name[183] = label_name
            else:
                label_id_to_label_name[label_id] = label_name

    assert len(label_id_to_label_name) == 183

    return label_id_to_label_name


class CocoStuffDataset(ds.GeneratorBasedBuilder):

    VERSION = ds.Version("1.0.0")  # type: ignore

    BUILDER_CONFIGS = [
        ds.BuilderConfig(
            name="stuff-thing",
            version=VERSION,  # type: ignore
            description="Stuff+thing PNG-style annotations on COCO 2017 trainval",
        ),
        ds.BuilderConfig(
            name="stuff-only",
            version=VERSION,  # type: ignore
            description="Stuff-only COCO-style annotations on COCO 2017 trainval",
        ),
    ]

    def _info(self) -> ds.DatasetInfo:
        if self.config.name == "stuff-thing":
            features = ds.Features(
                {
                    "image": ds.Image(),
                    "image_id": ds.Value("int32"),
                    "image_filename": ds.Value("string"),
                    "width": ds.Value("int32"),
                    "height": ds.Value("int32"),
                    "stuff_map": ds.Image(),
                    "objects": [
                        {
                            "object_id": ds.Value("string"),
                            "x": ds.Value("int32"),
                            "y": ds.Value("int32"),
                            "w": ds.Value("int32"),
                            "h": ds.Value("int32"),
                            "name": ds.Value("string"),
                        }
                    ],
                }
            )
        elif self.config.name == "stuff-only":
            features = ds.Features(
                {
                    "image": ds.Image(),
                    "image_id": ds.Value("int32"),
                    "image_filename": ds.Value("string"),
                    "width": ds.Value("int32"),
                    "height": ds.Value("int32"),
                    "objects": [
                        {
                            "object_id": ds.Value("int32"),
                            "x": ds.Value("int32"),
                            "y": ds.Value("int32"),
                            "w": ds.Value("int32"),
                            "h": ds.Value("int32"),
                            "name": ds.Value("string"),
                        }
                    ],
                }
            )
        else:
            raise ValueError(f"Invalid dataset name: {self.config.name}")

        return ds.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def load_stuff_json(self, stuff_dirpath: str, split: str):
        return _load_json(
            json_path=os.path.join(stuff_dirpath, f"stuff_{split}2017.json")
        )

    def get_image_id_to_image_infos(self, images):

        image_id_to_image_infos = {}
        for img_dict in images:
            image_id = img_dict.pop("id")
            image_id_to_image_infos[image_id] = img_dict

        image_id_to_image_infos = dict(sorted(image_id_to_image_infos.items()))
        return image_id_to_image_infos

    def get_image_id_to_annotations(self, annotations):

        image_id_to_annotations = defaultdict(list)
        for ann_dict in annotations:
            image_id = ann_dict.pop("image_id")
            image_id_to_annotations[image_id].append(ann_dict)

        image_id_to_annotations = dict(sorted(image_id_to_annotations.items()))
        return image_id_to_annotations

    def _split_generators(self, dl_manager: ds.DownloadManager):
        downloaded_files = dl_manager.download_and_extract(_URLS)

        tng_image_dirpath = os.path.join(downloaded_files["train"], "train2017")
        val_image_dirpath = os.path.join(downloaded_files["val"], "val2017")

        stuff_dirpath = downloaded_files["stuff_trainval"]
        stuff_things_maps_dirpath = downloaded_files["stuffthingmaps_trainval"]
        labels_path = downloaded_files["labels"]

        tng_gen_kwargs: GenerateExamplesArguments = {
            "image_dirpath": tng_image_dirpath,
            "stuff_dirpath": stuff_dirpath,
            "stuff_thing_maps_dirpath": stuff_things_maps_dirpath,
            "labels_path": labels_path,
            "split": "train",
        }
        val_gen_kwargs: GenerateExamplesArguments = {
            "image_dirpath": val_image_dirpath,
            "stuff_dirpath": stuff_dirpath,
            "stuff_thing_maps_dirpath": stuff_things_maps_dirpath,
            "labels_path": labels_path,
            "split": "val",
        }
        return [
            ds.SplitGenerator(
                name=ds.Split.TRAIN,  # type: ignore
                gen_kwargs=tng_gen_kwargs,  # type: ignore
            ),
            ds.SplitGenerator(
                name=ds.Split.VALIDATION,  # type: ignore
                gen_kwargs=val_gen_kwargs,  # type: ignore
            ),
        ]

    def _generate_examples_for_stuff_thing(
        self,
        image_dirpath: str,
        stuff_dirpath: str,
        stuff_thing_maps_dirpath: str,
        labels_path: str,
        split: str,
    ):
        id_to_label = _load_labels(labels_path=labels_path)
        stuff_json = self.load_stuff_json(stuff_dirpath=stuff_dirpath, split=split)

        image_id_to_image_infos = self.get_image_id_to_image_infos(
            images=copy.deepcopy(stuff_json["images"])
        )
        image_id_to_stuff_annotations = self.get_image_id_to_annotations(
            annotations=copy.deepcopy(stuff_json["annotations"])
        )

        assert len(image_id_to_image_infos.keys()) >= len(
            image_id_to_stuff_annotations.keys()
        )

        for image_id in image_id_to_stuff_annotations.keys():

            img_info = image_id_to_image_infos[image_id]
            image_filename = img_info["file_name"]
            image_filepath = os.path.join(image_dirpath, image_filename)
            img_example_dict = {
                "image": image_filepath,
                "image_id": image_id,
                "image_filename": image_filename,
                "width": img_info["width"],
                "height": img_info["height"],
            }

            img_anns = image_id_to_stuff_annotations[image_id]
            bboxes = [list(map(int, ann["bbox"])) for ann in img_anns]
            category_ids = [ann["category_id"] for ann in img_anns]
            category_labels = list(map(lambda cid: id_to_label[cid], category_ids))

            assert len(bboxes) == len(category_ids) == len(category_labels)
            zip_it = zip(bboxes, category_ids, category_labels)
            objects_example = [
                {
                    "object_id": category_id,
                    "x": bbox[0],
                    "y": bbox[1],
                    "w": bbox[2],
                    "h": bbox[3],
                    "name": category_label,
                }
                for bbox, category_id, category_label in zip_it
            ]

            root, _ = os.path.splitext(img_example_dict["image_filename"])
            stuff_map_filepath = os.path.join(
                stuff_thing_maps_dirpath, f"{split}2017", f"{root}.png"
            )

            example_dict = {
                **img_example_dict,
                "objects": objects_example,
                "stuff_map": stuff_map_filepath,
            }
            yield image_id, example_dict

    def _generate_examples_for_stuff_only(
        self,
        image_dirpath: str,
        stuff_dirpath: str,
        labels_path: str,
        split: str,
    ):
        id_to_label = _load_labels(labels_path=labels_path)
        stuff_json = self.load_stuff_json(stuff_dirpath=stuff_dirpath, split=split)

        image_id_to_image_infos = self.get_image_id_to_image_infos(
            images=copy.deepcopy(stuff_json["images"])
        )
        image_id_to_stuff_annotations = self.get_image_id_to_annotations(
            annotations=copy.deepcopy(stuff_json["annotations"])
        )

        assert len(image_id_to_image_infos.keys()) >= len(
            image_id_to_stuff_annotations.keys()
        )

        for image_id in image_id_to_stuff_annotations.keys():

            img_info = image_id_to_image_infos[image_id]
            image_filename = img_info["file_name"]
            image_filepath = os.path.join(image_dirpath, image_filename)
            img_example_dict = {
                "image": image_filepath,
                "image_id": image_id,
                "image_filename": image_filename,
                "width": img_info["width"],
                "height": img_info["height"],
            }

            img_anns = image_id_to_stuff_annotations[image_id]
            bboxes = [list(map(int, ann["bbox"])) for ann in img_anns]
            category_ids = [ann["category_id"] for ann in img_anns]
            category_labels = list(map(lambda cid: id_to_label[cid], category_ids))

            assert len(bboxes) == len(category_ids) == len(category_labels)
            zip_it = zip(bboxes, category_ids, category_labels)
            objects_example = [
                {
                    "object_id": category_id,
                    "x": bbox[0],
                    "y": bbox[1],
                    "w": bbox[2],
                    "h": bbox[3],
                    "name": category_label,
                }
                for bbox, category_id, category_label in zip_it
            ]

            example_dict = {
                **img_example_dict,
                "objects": objects_example,
            }
            yield image_id, example_dict

    def _generate_examples(  # type: ignore
        self,
        image_dirpath: str,
        stuff_dirpath: str,
        stuff_thing_maps_dirpath: str,
        labels_path: str,
        split: str,
    ):
        logger.info(f"Generating examples for {split}.")

        if "stuff-thing" in self.config.name:
            return self._generate_examples_for_stuff_thing(
                image_dirpath=image_dirpath,
                stuff_dirpath=stuff_dirpath,
                stuff_thing_maps_dirpath=stuff_thing_maps_dirpath,
                labels_path=labels_path,
                split=split,
            )
        elif "stuff-only" in self.config.name:
            return self._generate_examples_for_stuff_only(
                image_dirpath=image_dirpath,
                stuff_dirpath=stuff_dirpath,
                labels_path=labels_path,
                split=split,
            )
        else:
            raise ValueError(f"Invalid dataset name: {self.config.name}")