Datasets:

Languages:
English
License:
File size: 21,339 Bytes
14fe0b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
from builtins import isinstance
import os
import glob
import json
import logging
import zipfile
import functools
import collections

import datasets

logger = logging.getLogger(__name__)

_VERSION = datasets.Version("1.0.0", "")

_URL = "https://cocodataset.org/#home"

# Copied from https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/object_detection/coco.py
_CITATION = """\
@article{DBLP:journals/corr/LinMBHPRDZ14,
  author    = {Tsung{-}Yi Lin and
               Michael Maire and
               Serge J. Belongie and
               Lubomir D. Bourdev and
               Ross B. Girshick and
               James Hays and
               Pietro Perona and
               Deva Ramanan and
               Piotr Doll{\'{a}}r and
               C. Lawrence Zitnick},
  title     = {Microsoft {COCO:} Common Objects in Context},
  journal   = {CoRR},
  volume    = {abs/1405.0312},
  year      = {2014},
  url       = {http://arxiv.org/abs/1405.0312},
  archivePrefix = {arXiv},
  eprint    = {1405.0312},
  timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},
  biburl    = {https://dblp.org/rec/bib/journals/corr/LinMBHPRDZ14},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""

# Copied from https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/object_detection/coco.py
_DESCRIPTION = """COCO is a large-scale object detection, segmentation, and
captioning dataset.
Note:
 * Some images from the train and validation sets don't have annotations.
 * Coco 2014 and 2017 uses the same images, but different train/val/test splits
 * The test split don't have any annotations (only images).
 * Coco defines 91 classes but the data only uses 80 classes.
 * Panotptic annotations defines defines 200 classes but only uses 133.
"""

# Copied from https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/object_detection/coco.py
_CONFIG_DESCRIPTION = """
This version contains images, bounding boxes and labels for the {year} version.
"""

Split = collections.namedtuple(
    'Split', ['name', 'images', 'annotations', 'annotation_type']
)

# stuffing class 'none' for index 0
CAT = [
    "none",
    "person",
    "bicycle",
    "car",
    "motorcycle",
    "airplane",
    "bus",
    "train",
    "truck",
    "boat",
    "traffic light",
    "fire hydrant",
    "street sign",
    "stop sign",
    "parking meter",
    "bench",
    "bird",
    "cat",
    "dog",
    "horse",
    "sheep",
    "cow",
    "elephant",
    "bear",
    "zebra",
    "giraffe",
    "hat",
    "backpack",
    "umbrella",
    "shoe",
    "eye glasses",
    "handbag",
    "tie",
    "suitcase",
    "frisbee",
    "skis",
    "snowboard",
    "sports ball",
    "kite",
    "baseball bat",
    "baseball glove",
    "skateboard",
    "surfboard",
    "tennis racket",
    "bottle",
    "plate",
    "wine glass",
    "cup",
    "fork",
    "knife",
    "spoon",
    "bowl",
    "banana",
    "apple",
    "sandwich",
    "orange",
    "broccoli",
    "carrot",
    "hot dog",
    "pizza",
    "donut",
    "cake",
    "chair",
    "couch",
    "potted plant",
    "bed",
    "mirror",
    "dining table",
    "window",
    "desk",
    "toilet",
    "door",
    "tv",
    "laptop",
    "mouse",
    "remote",
    "keyboard",
    "cell phone",
    "microwave",
    "oven",
    "toaster",
    "sink",
    "refrigerator",
    "blender",
    "book",
    "clock",
    "vase",
    "scissors",
    "teddy bear",
    "hair drier",
    "toothbrush",
    "hair brush",
]

SUPER_CAT = [
    "none",
    "person",
    "vehicle",
    "outdoor",
    "animal",
    "accessory",
    "sports",
    "kitchen",
    "food",
    "furniture",
    "electronic",
    "appliance",
    "indoor",
]

CAT2SUPER_CAT = [
    "none",
    "person",
    "vehicle",
    "vehicle",
    "vehicle",
    "vehicle",
    "vehicle",
    "vehicle",
    "vehicle",
    "vehicle",
    "outdoor",
    "outdoor",
    "outdoor",
    "outdoor",
    "outdoor",
    "outdoor",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "animal",
    "accessory",
    "accessory",
    "accessory",
    "accessory",
    "accessory",
    "accessory",
    "accessory",
    "accessory",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "sports",
    "kitchen",
    "kitchen",
    "kitchen",
    "kitchen",
    "kitchen",
    "kitchen",
    "kitchen",
    "kitchen",
    "food",
    "food",
    "food",
    "food",
    "food",
    "food",
    "food",
    "food",
    "food",
    "food",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "furniture",
    "electronic",
    "electronic",
    "electronic",
    "electronic",
    "electronic",
    "electronic",
    "appliance",
    "appliance",
    "appliance",
    "appliance",
    "appliance",
    "appliance",
    "indoor",
    "indoor",
    "indoor",
    "indoor",
    "indoor",
    "indoor",
    "indoor",
    "indoor",
]






class AnnotationType(object):
    """Enum of the annotation format types.
    Splits are annotated with different formats.
    """

    BBOXES = 'bboxes'
    PANOPTIC = 'panoptic'
    NONE = 'none'



DETECTION_FEATURE = datasets.Features(
    {
        "image": datasets.Image(),
        "image/filename": datasets.Value("string"),
        "image/id": datasets.Value("int64"),
        "objects": datasets.Sequence(feature=datasets.Features({
            "id": datasets.Value("int64"),
            "area": datasets.Value("float32"),
            "bbox": datasets.Sequence(
                feature=datasets.Value("float32")
            ),
            "label": datasets.ClassLabel(names=CAT),
            "super_cat_label": datasets.ClassLabel(names=SUPER_CAT),
            "is_crowd": datasets.Value("bool"),
        })),
    }
)

PANOPTIC_FEATURE = datasets.Features(
    {
        "image": datasets.Image(),
        "image/filename": datasets.Value("string"),
        "image/id": datasets.Value("int64"),
        "panoptic_objects": datasets.Sequence(feature=datasets.Features({
            "id": datasets.Value("int64"),
            "area": datasets.Value("float32"),
            "bbox": datasets.Sequence(
                feature=datasets.Value("float32")
            ),
            "label": datasets.ClassLabel(names=CAT),
            "super_cat_label": datasets.ClassLabel(names=SUPER_CAT),
            "is_crowd": datasets.Value("bool"),
        })),
        "panoptic_image": datasets.Image(),
        "panoptic_image/filename": datasets.Value("string"),
    }
)
# More info could be added, like segmentation (as png mask), captions,
# person key-points, more metadata (original flickr url,...).



# Copied from https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/object_detection/coco.py
class CocoConfig(datasets.BuilderConfig):
  """BuilderConfig for CocoConfig."""

  def __init__(self, features, splits=None, has_panoptic=False, **kwargs):
    super(CocoConfig, self).__init__(
        **kwargs
    )
    self.features = features
    self.splits = splits
    self.has_panoptic = has_panoptic


# Copied from https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/object_detection/coco.py
class Coco(datasets.GeneratorBasedBuilder):
    """Base MS Coco dataset."""

    BUILDER_CONFIGS = [
      CocoConfig(
          name='2014',
          features=DETECTION_FEATURE,
          description=_CONFIG_DESCRIPTION.format(year=2014),
          version=_VERSION,
          splits=[
              Split(
                  name=datasets.Split.TRAIN,
                  images='train2014',
                  annotations='annotations_trainval2014',
                  annotation_type=AnnotationType.BBOXES,
              ),
              Split(
                  name=datasets.Split.VALIDATION,
                  images='val2014',
                  annotations='annotations_trainval2014',
                  annotation_type=AnnotationType.BBOXES,
              ),
              Split(
                  name=datasets.Split.TEST,
                  images='test2014',
                  annotations='image_info_test2014',
                  annotation_type=AnnotationType.NONE,
              ),
              # Coco2014 contains an extra test split
              Split(
                  name='test2015',
                  images='test2015',
                  annotations='image_info_test2015',
                  annotation_type=AnnotationType.NONE,
              ),
          ],
      ),
      CocoConfig(
          name='2017',
          features=DETECTION_FEATURE,
          description=_CONFIG_DESCRIPTION.format(year=2017),
          version=_VERSION,
          splits=[
              Split(
                  name=datasets.Split.TRAIN,
                  images='train2017',
                  annotations='annotations_trainval2017',
                  annotation_type=AnnotationType.BBOXES,
              ),
              Split(
                  name=datasets.Split.VALIDATION,
                  images='val2017',
                  annotations='annotations_trainval2017',
                  annotation_type=AnnotationType.BBOXES,
              ),
              Split(
                  name=datasets.Split.TEST,
                  images='test2017',
                  annotations='image_info_test2017',
                  annotation_type=AnnotationType.NONE,
              ),
          ],
      ),
      CocoConfig(
          name='2017_panoptic',
          features=PANOPTIC_FEATURE,
          description=_CONFIG_DESCRIPTION.format(year=2017),
          version=_VERSION,
          has_panoptic=True,
          splits=[
              Split(
                  name=datasets.Split.TRAIN,
                  images='train2017',
                  annotations='panoptic_annotations_trainval2017',
                  annotation_type=AnnotationType.PANOPTIC,
              ),
              Split(
                  name=datasets.Split.VALIDATION,
                  images='val2017',
                  annotations='panoptic_annotations_trainval2017',
                  annotation_type=AnnotationType.PANOPTIC,
              ),
          ],
      ),
  ]

    DEFAULT_CONFIG_NAME = "2017"

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=self.config.features,
            supervised_keys=None,  # Probably needs to be fixed.
            homepage=_URL,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager):

        # DownloadManager memoize the url, so duplicate urls will only be downloaded
        # once.
        if dl_manager.manual_dir is None:
            # Merge urls from all splits together
            urls = {}
            for split in self.config.splits:
                urls['{}_images'.format(split.name)] = 'zips/{}.zip'.format(split.images)
                urls['{}_annotations'.format(split.name)] = 'annotations/{}.zip'.format(
                    split.annotations
                )
            
            logging.info("download and extract coco dataset")
            root_url = 'http://images.cocodataset.org/'
            extracted_paths = dl_manager.download_and_extract(
                {key: root_url + url for key, url in urls.items()}
            )
        else:
            logging.info(f"use manual directory: {dl_manager.manual_dir}")
            extracted_paths = {}
            for split in self.config.splits:
                extracted_paths['{}_images'.format(split.name)] = dl_manager.manual_dir
                extracted_paths['{}_annotations'.format(split.name)] = dl_manager.manual_dir

        splits = []
        for split in self.config.splits:
            image_dir = extracted_paths['{}_images'.format(split.name)]
            annotations_dir = extracted_paths['{}_annotations'.format(split.name)]
            if self.config.has_panoptic:
                if dl_manager.manual_dir is None:
                    logging.info("extract panoptic data")
                    panoptic_image_zip_path = os.path.join(
                        annotations_dir,
                        'annotations',
                        'panoptic_{}.zip'.format(split.images),
                    )
                    panoptic_dir = dl_manager.extract(panoptic_image_zip_path)
                    panoptic_dir = os.path.join(
                        panoptic_dir, 'panoptic_{}'.format(split.images)
                    )
                else:
                    logging.info("use extracted data")
                    panoptic_dir = os.path.join(annotations_dir, 'annotations', 'panoptic_{}.zip'.format(split.images))
            else:
                panoptic_dir = None
            splits.append(
                datasets.SplitGenerator(
                    name=split.name, 
                    gen_kwargs={
                        'image_dir': image_dir,
                        'annotation_dir': annotations_dir,
                        'split_name': split.images,
                        'annotation_type': split.annotation_type,
                        'panoptic_dir': panoptic_dir,
                    }
                )
            )
        return splits

    def _generate_examples(self, image_dir, annotation_dir, split_name, annotation_type, panoptic_dir):
        """Generate examples as dicts.
        Args:
        image_dir: `str`, directory containing the images
        annotation_dir: `str`, directory containing annotations
        split_name: `str`, <split_name><year> (ex: train2014, val2017)
        annotation_type: `AnnotationType`, the annotation format (NONE, BBOXES,
            PANOPTIC)
        panoptic_dir: If annotation_type is PANOPTIC, contains the panoptic image
            directory
        Yields:
        example key and data
        """

        if annotation_type == AnnotationType.BBOXES:
            instance_filename = 'instances_{}.json'
        elif annotation_type == AnnotationType.PANOPTIC:
            instance_filename = 'panoptic_{}.json'
        elif annotation_type == AnnotationType.NONE:  # No annotation for test sets
            instance_filename = 'image_info_{}.json'

        # Load the annotations (label names, images metadata,...)
        instance_path = os.path.join(
            annotation_dir,
            'annotations',
            instance_filename.format(split_name),
        )
        coco_annotation = ANNOTATION_CLS[annotation_type](instance_path)
        # Each category is a dict:
        # {
        #    'id': 51,  # From 1-91, some entry missing
        #    'name': 'bowl',
        #    'supercategory': 'kitchen',
        # }
        categories = coco_annotation.categories
        # Each image is a dict:
        # {
        #     'id': 262145,
        #     'file_name': 'COCO_train2017_000000262145.jpg'
        #     'flickr_url': 'http://farm8.staticflickr.com/7187/xyz.jpg',
        #     'coco_url': 'http://images.cocodataset.org/train2017/xyz.jpg',
        #     'license': 2,
        #     'date_captured': '2013-11-20 02:07:55',
        #     'height': 427,
        #     'width': 640,
        # }
        images = coco_annotation.images

        # TODO(b/121375022): ClassLabel names should also contains 'id' and
        # and 'supercategory' (in addition to 'name')
        # Warning: As Coco only use 80 out of the 91 labels, the c['id'] and
        # dataset names ids won't match.
        if self.config.has_panoptic:
            objects_key = 'panoptic_objects'
        else:
            objects_key = 'objects'
        # self.info.features[objects_key]['label'].names = [
        #     c['name'] for c in categories
        # ]
        
        # TODO(b/121375022): Conversion should be done by ClassLabel
        # categories_id2name = {c['id']: c['name'] for c in categories}

        # Iterate over all images
        annotation_skipped = 0
        for image_info in sorted(images, key=lambda x: x['id']):
            if annotation_type == AnnotationType.BBOXES:
                # Each instance annotation is a dict:
                # {
                #     'iscrowd': 0,
                #     'bbox': [116.95, 305.86, 285.3, 266.03],
                #     'image_id': 480023,
                #     'segmentation': [[312.29, 562.89, 402.25, ...]],
                #     'category_id': 58,
                #     'area': 54652.9556,
                #     'id': 86,
                # }
                instances = coco_annotation.get_annotations(img_id=image_info['id'])
            elif annotation_type == AnnotationType.PANOPTIC:
                # Each panoptic annotation is a dict:
                # {
                #     'file_name': '000000037777.png',
                #     'image_id': 37777,
                #     'segments_info': [
                #         {
                #             'area': 353,
                #             'category_id': 52,
                #             'iscrowd': 0,
                #             'id': 6202563,
                #             'bbox': [221, 179, 37, 27],
                #         },
                #         ...
                #     ]
                # }
                panoptic_annotation = coco_annotation.get_annotations(
                    img_id=image_info['id']
                )
                instances = panoptic_annotation['segments_info']
            else:
                instances = []  # No annotations

            if not instances:
                annotation_skipped += 1

            def build_bbox(x, y, width, height):
                # pylint: disable=cell-var-from-loop
                # build_bbox is only used within the loop so it is ok to use image_info
                return [
                    y,
                    x,
                    (y + height),
                    (x + width),
                ]
                # pylint: enable=cell-var-from-loop

            example = {
                'image': os.path.abspath(os.path.join(image_dir, split_name, image_info['file_name'])),
                'image/filename': image_info['file_name'],
                'image/id': image_info['id'],
                objects_key: [
                    {  # pylint: disable=g-complex-comprehension
                        'id': instance['id'],
                        'area': instance['area'],
                        'bbox': build_bbox(*instance['bbox']),
                        'label': instance['category_id'],
                        'super_cat_label': SUPER_CAT.index(CAT2SUPER_CAT[instance['category_id']]),
                        'is_crowd': bool(instance['iscrowd']),
                    }
                    for instance in instances
                ],
            }
            if self.config.has_panoptic:
                panoptic_filename = panoptic_annotation['file_name']
                panoptic_image_path = os.path.join(panoptic_dir, panoptic_filename)
                example['panoptic_image'] = panoptic_image_path
                example['panoptic_image/filename'] = panoptic_filename

            yield image_info['file_name'], example

        logging.info(
            '%d/%d images do not contains any annotations',
            annotation_skipped,
            len(images),
        )


class CocoAnnotation(object):
  """Coco annotation helper class."""

  def __init__(self, annotation_path):
    with open(annotation_path, "r") as f:
      data = json.load(f)
    self._data = data

  @property
  def categories(self):
    """Return the category dicts, as sorted in the file."""
    return self._data['categories']

  @property
  def images(self):
    """Return the image dicts, as sorted in the file."""
    return self._data['images']

  def get_annotations(self, img_id):
    """Return all annotations associated with the image id string."""
    raise NotImplementedError  # AnotationType.NONE don't have annotations


class CocoAnnotationBBoxes(CocoAnnotation):
  """Coco annotation helper class."""

  def __init__(self, annotation_path):
    super(CocoAnnotationBBoxes, self).__init__(annotation_path)

    img_id2annotations = collections.defaultdict(list)
    for a in self._data['annotations']:
      img_id2annotations[a['image_id']].append(a)
    self._img_id2annotations = {
        k: list(sorted(v, key=lambda a: a['id']))
        for k, v in img_id2annotations.items()
    }

  def get_annotations(self, img_id):
    """Return all annotations associated with the image id string."""
    # Some images don't have any annotations. Return empty list instead.
    return self._img_id2annotations.get(img_id, [])


class CocoAnnotationPanoptic(CocoAnnotation):
  """Coco annotation helper class."""

  def __init__(self, annotation_path):
    super(CocoAnnotationPanoptic, self).__init__(annotation_path)
    self._img_id2annotations = {
        a['image_id']: a for a in self._data['annotations']
    }

  def get_annotations(self, img_id):
    """Return all annotations associated with the image id string."""
    return self._img_id2annotations[img_id]


ANNOTATION_CLS = {
    AnnotationType.NONE: CocoAnnotation,
    AnnotationType.BBOXES: CocoAnnotationBBoxes,
    AnnotationType.PANOPTIC: CocoAnnotationPanoptic,
}