|
| 1 | +# Copyright 2023 cansik. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +import os |
| 17 | +import time |
| 18 | +from collections import defaultdict |
| 19 | +from typing import Optional, Sequence |
| 20 | + |
| 21 | +import cv2 |
| 22 | +import numpy as np |
| 23 | +from pycocotools.coco import COCO |
| 24 | + |
| 25 | +from .coco import CocoDataset |
| 26 | +from .xml_dataset import get_file_list |
| 27 | + |
| 28 | + |
| 29 | +class CocoYolo(COCO): |
| 30 | + def __init__(self, annotation): |
| 31 | + """ |
| 32 | + Constructor of Microsoft COCO helper class for |
| 33 | + reading and visualizing annotations. |
| 34 | + :param annotation: annotation dict |
| 35 | + :return: |
| 36 | + """ |
| 37 | + # load dataset |
| 38 | + super().__init__() |
| 39 | + self.dataset, self.anns, self.cats, self.imgs = dict(), dict(), dict(), dict() |
| 40 | + self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list) |
| 41 | + dataset = annotation |
| 42 | + assert type(dataset) == dict, "annotation file format {} not supported".format( |
| 43 | + type(dataset) |
| 44 | + ) |
| 45 | + self.dataset = dataset |
| 46 | + self.createIndex() |
| 47 | + |
| 48 | + |
| 49 | +class YoloDataset(CocoDataset): |
| 50 | + def __init__(self, class_names, **kwargs): |
| 51 | + self.class_names = class_names |
| 52 | + super(YoloDataset, self).__init__(**kwargs) |
| 53 | + |
| 54 | + @staticmethod |
| 55 | + def _find_image( |
| 56 | + image_prefix: str, |
| 57 | + image_types: Sequence[str] = (".png", ".jpg", ".jpeg", ".bmp", ".tiff"), |
| 58 | + ) -> Optional[str]: |
| 59 | + for image_type in image_types: |
| 60 | + path = f"{image_prefix}{image_type}" |
| 61 | + if os.path.exists(path): |
| 62 | + return path |
| 63 | + return None |
| 64 | + |
| 65 | + def yolo_to_coco(self, ann_path): |
| 66 | + """ |
| 67 | + convert xml annotations to coco_api |
| 68 | + :param ann_path: |
| 69 | + :return: |
| 70 | + """ |
| 71 | + logging.info("loading annotations into memory...") |
| 72 | + tic = time.time() |
| 73 | + ann_file_names = get_file_list(ann_path, type=".txt") |
| 74 | + logging.info("Found {} annotation files.".format(len(ann_file_names))) |
| 75 | + image_info = [] |
| 76 | + categories = [] |
| 77 | + annotations = [] |
| 78 | + for idx, supercat in enumerate(self.class_names): |
| 79 | + categories.append( |
| 80 | + {"supercategory": supercat, "id": idx + 1, "name": supercat} |
| 81 | + ) |
| 82 | + ann_id = 1 |
| 83 | + |
| 84 | + for idx, txt_name in enumerate(ann_file_names): |
| 85 | + ann_file = os.path.join(ann_path, txt_name) |
| 86 | + image_file = self._find_image(os.path.splitext(ann_file)[0]) |
| 87 | + |
| 88 | + if image_file is None: |
| 89 | + logging.warning(f"Could not find image for {ann_file}") |
| 90 | + continue |
| 91 | + |
| 92 | + with open(ann_file, "r") as f: |
| 93 | + lines = f.readlines() |
| 94 | + |
| 95 | + image = cv2.imread(image_file) |
| 96 | + height, width = image.shape[:2] |
| 97 | + |
| 98 | + file_name = os.path.basename(image_file) |
| 99 | + info = { |
| 100 | + "file_name": file_name, |
| 101 | + "height": height, |
| 102 | + "width": width, |
| 103 | + "id": idx + 1, |
| 104 | + } |
| 105 | + image_info.append(info) |
| 106 | + for line in lines: |
| 107 | + data = [float(t) for t in line.split(" ")] |
| 108 | + cat_id = int(data[0]) |
| 109 | + locations = np.array(data[1:]).reshape((len(data) // 2, 2)) |
| 110 | + bbox = locations[0:2] |
| 111 | + |
| 112 | + bbox[0] -= bbox[1] * 0.5 |
| 113 | + |
| 114 | + bbox = np.round(bbox * np.array([width, height])).astype(int) |
| 115 | + x, y = bbox[0][0], bbox[0][1] |
| 116 | + w, h = bbox[1][0], bbox[1][1] |
| 117 | + |
| 118 | + if cat_id >= len(self.class_names): |
| 119 | + logging.warning( |
| 120 | + f"Category {cat_id} is not defined in config ({txt_name})" |
| 121 | + ) |
| 122 | + continue |
| 123 | + |
| 124 | + if w < 0 or h < 0: |
| 125 | + logging.warning( |
| 126 | + "WARNING! Find error data in file {}! Box w and " |
| 127 | + "h should > 0. Pass this box annotation.".format(txt_name) |
| 128 | + ) |
| 129 | + continue |
| 130 | + |
| 131 | + coco_box = [max(x, 0), max(y, 0), min(w, width), min(h, height)] |
| 132 | + ann = { |
| 133 | + "image_id": idx + 1, |
| 134 | + "bbox": coco_box, |
| 135 | + "category_id": cat_id + 1, |
| 136 | + "iscrowd": 0, |
| 137 | + "id": ann_id, |
| 138 | + "area": coco_box[2] * coco_box[3], |
| 139 | + } |
| 140 | + annotations.append(ann) |
| 141 | + ann_id += 1 |
| 142 | + |
| 143 | + coco_dict = { |
| 144 | + "images": image_info, |
| 145 | + "categories": categories, |
| 146 | + "annotations": annotations, |
| 147 | + } |
| 148 | + logging.info( |
| 149 | + "Load {} txt files and {} boxes".format(len(image_info), len(annotations)) |
| 150 | + ) |
| 151 | + logging.info("Done (t={:0.2f}s)".format(time.time() - tic)) |
| 152 | + return coco_dict |
| 153 | + |
| 154 | + def get_data_info(self, ann_path): |
| 155 | + """ |
| 156 | + Load basic information of dataset such as image path, label and so on. |
| 157 | + :param ann_path: coco json file path |
| 158 | + :return: image info: |
| 159 | + [{'file_name': '000000000139.jpg', |
| 160 | + 'height': 426, |
| 161 | + 'width': 640, |
| 162 | + 'id': 139}, |
| 163 | + ... |
| 164 | + ] |
| 165 | + """ |
| 166 | + coco_dict = self.yolo_to_coco(ann_path) |
| 167 | + self.coco_api = CocoYolo(coco_dict) |
| 168 | + self.cat_ids = sorted(self.coco_api.getCatIds()) |
| 169 | + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} |
| 170 | + self.cats = self.coco_api.loadCats(self.cat_ids) |
| 171 | + self.img_ids = sorted(self.coco_api.imgs.keys()) |
| 172 | + img_info = self.coco_api.loadImgs(self.img_ids) |
| 173 | + return img_info |
0 commit comments