|
| 1 | +import json |
| 2 | +from itertools import chain |
| 3 | +from pathlib import Path |
| 4 | +from typing import Iterable, Dict, List, Callable, Any |
| 5 | +from collections import defaultdict |
| 6 | + |
| 7 | +from tqdm import tqdm |
| 8 | + |
| 9 | +from taming.data.annotated_objects_dataset import AnnotatedObjectsDataset |
| 10 | +from taming.data.helper_types import Annotation, ImageDescription, Category |
| 11 | + |
| 12 | +COCO_PATH_STRUCTURE = { |
| 13 | + 'train': { |
| 14 | + 'top_level': '', |
| 15 | + 'person_annotations': 'annotations/person_keypoints_train2017.json', |
| 16 | + 'instances_annotations': 'annotations/instances_train2017.json', |
| 17 | + 'stuff_annotations': 'annotations/stuff_train2017.json', |
| 18 | + 'files': 'train2017' |
| 19 | + }, |
| 20 | + 'validation': { |
| 21 | + 'top_level': '', |
| 22 | + 'person_annotations': 'annotations/person_keypoints_val2017.json', |
| 23 | + 'instances_annotations': 'annotations/instances_val2017.json', |
| 24 | + 'stuff_annotations': 'annotations/stuff_val2017.json', |
| 25 | + 'files': 'val2017' |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | + |
| 30 | +def load_image_descriptions(description_json: List[Dict]) -> Dict[str, ImageDescription]: |
| 31 | + return { |
| 32 | + str(img['id']): ImageDescription( |
| 33 | + id=img['id'], |
| 34 | + license=img.get('license'), |
| 35 | + file_name=img['file_name'], |
| 36 | + coco_url=img['coco_url'], |
| 37 | + original_size=(img['width'], img['height']), |
| 38 | + date_captured=img.get('date_captured'), |
| 39 | + flickr_url=img.get('flickr_url') |
| 40 | + ) |
| 41 | + for img in description_json |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | +def load_categories(category_json: Iterable) -> Dict[str, Category]: |
| 46 | + return {str(cat['id']): Category(id=str(cat['id']), super_category=cat['supercategory'], name=cat['name']) |
| 47 | + for cat in category_json if cat['name'] != 'other'} |
| 48 | + |
| 49 | + |
| 50 | +def load_annotations(annotations_json: List[Dict], image_descriptions: Dict[str, ImageDescription], |
| 51 | + category_no_for_id: Callable[[str], int], split: str) -> Dict[str, List[Annotation]]: |
| 52 | + annotations = defaultdict(list) |
| 53 | + total = sum(len(a) for a in annotations_json) |
| 54 | + for ann in tqdm(chain(*annotations_json), f'Loading {split} annotations', total=total): |
| 55 | + image_id = str(ann['image_id']) |
| 56 | + if image_id not in image_descriptions: |
| 57 | + raise ValueError(f'image_id [{image_id}] has no image description.') |
| 58 | + category_id = ann['category_id'] |
| 59 | + try: |
| 60 | + category_no = category_no_for_id(str(category_id)) |
| 61 | + except KeyError: |
| 62 | + continue |
| 63 | + |
| 64 | + width, height = image_descriptions[image_id].original_size |
| 65 | + bbox = (ann['bbox'][0] / width, ann['bbox'][1] / height, ann['bbox'][2] / width, ann['bbox'][3] / height) |
| 66 | + |
| 67 | + annotations[image_id].append( |
| 68 | + Annotation( |
| 69 | + id=ann['id'], |
| 70 | + area=bbox[2]*bbox[3], # use bbox area |
| 71 | + is_group_of=ann['iscrowd'], |
| 72 | + image_id=ann['image_id'], |
| 73 | + bbox=bbox, |
| 74 | + category_id=str(category_id), |
| 75 | + category_no=category_no |
| 76 | + ) |
| 77 | + ) |
| 78 | + return dict(annotations) |
| 79 | + |
| 80 | + |
| 81 | +class AnnotatedObjectsCoco(AnnotatedObjectsDataset): |
| 82 | + def __init__(self, use_things: bool = True, use_stuff: bool = True, **kwargs): |
| 83 | + """ |
| 84 | + @param data_path: is the path to the following folder structure: |
| 85 | + coco/ |
| 86 | + ├── annotations |
| 87 | + │ ├── instances_train2017.json |
| 88 | + │ ├── instances_val2017.json |
| 89 | + │ ├── stuff_train2017.json |
| 90 | + │ └── stuff_val2017.json |
| 91 | + ├── train2017 |
| 92 | + │ ├── 000000000009.jpg |
| 93 | + │ ├── 000000000025.jpg |
| 94 | + │ └── ... |
| 95 | + ├── val2017 |
| 96 | + │ ├── 000000000139.jpg |
| 97 | + │ ├── 000000000285.jpg |
| 98 | + │ └── ... |
| 99 | + @param: split: one of 'train' or 'validation' |
| 100 | + @param: desired image size (give square images) |
| 101 | + """ |
| 102 | + super().__init__(**kwargs) |
| 103 | + self.use_things = use_things |
| 104 | + self.use_stuff = use_stuff |
| 105 | + |
| 106 | + with open(self.paths['instances_annotations']) as f: |
| 107 | + inst_data_json = json.load(f) |
| 108 | + with open(self.paths['stuff_annotations']) as f: |
| 109 | + stuff_data_json = json.load(f) |
| 110 | + |
| 111 | + category_jsons = [] |
| 112 | + annotation_jsons = [] |
| 113 | + if self.use_things: |
| 114 | + category_jsons.append(inst_data_json['categories']) |
| 115 | + annotation_jsons.append(inst_data_json['annotations']) |
| 116 | + if self.use_stuff: |
| 117 | + category_jsons.append(stuff_data_json['categories']) |
| 118 | + annotation_jsons.append(stuff_data_json['annotations']) |
| 119 | + |
| 120 | + self.categories = load_categories(chain(*category_jsons)) |
| 121 | + self.filter_categories() |
| 122 | + self.setup_category_id_and_number() |
| 123 | + |
| 124 | + self.image_descriptions = load_image_descriptions(inst_data_json['images']) |
| 125 | + annotations = load_annotations(annotation_jsons, self.image_descriptions, self.get_category_number, self.split) |
| 126 | + self.annotations = self.filter_object_number(annotations, self.min_object_area, |
| 127 | + self.min_objects_per_image, self.max_objects_per_image) |
| 128 | + self.image_ids = list(self.annotations.keys()) |
| 129 | + self.clean_up_annotations_and_image_descriptions() |
| 130 | + |
| 131 | + def get_path_structure(self) -> Dict[str, str]: |
| 132 | + if self.split not in COCO_PATH_STRUCTURE: |
| 133 | + raise ValueError(f'Split [{self.split} does not exist for COCO data.]') |
| 134 | + return COCO_PATH_STRUCTURE[self.split] |
| 135 | + |
| 136 | + def get_image_path(self, image_id: str) -> Path: |
| 137 | + return self.paths['files'].joinpath(self.image_descriptions[str(image_id)].file_name) |
| 138 | + |
| 139 | + def get_image_description(self, image_id: str) -> Dict[str, Any]: |
| 140 | + # noinspection PyProtectedMember |
| 141 | + return self.image_descriptions[image_id]._asdict() |
0 commit comments