x2coco.py 16.2 KB
Newer Older
S
sunyanfang01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import cv2
import json
import os
import os.path as osp
import shutil
import numpy as np
import PIL.ImageDraw
from .base import MyEncoder, is_pic, get_encoding
S
fix  
SunAhong1993 已提交
25
from paddlex.utils import path_normalization
S
sunyanfang01 已提交
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
        
        
class X2COCO(object):
    def __init__(self):
        self.images_list = []
        self.categories_list = []
        self.annotations_list = []
    
    def generate_categories_field(self, label, labels_list):
        category = {}
        category["supercategory"] = "component"
        category["id"] = len(labels_list) + 1
        category["name"] = label
        return category
    
    def generate_rectangle_anns_field(self, points, label, image_id, object_id, label_to_num):
        annotation = {}
        seg_points = np.asarray(points).copy()
        seg_points[1, :] = np.asarray(points)[2, :]
        seg_points[2, :] = np.asarray(points)[1, :]
        annotation["segmentation"] = [list(seg_points.flatten())]
        annotation["iscrowd"] = 0
        annotation["image_id"] = image_id + 1
        annotation["bbox"] = list(
            map(float, [
                points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
                    1] - points[0][1]
            ]))
        annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
        annotation["category_id"] = label_to_num[label]
        annotation["id"] = object_id + 1
        return annotation
    
S
sunyanfang01 已提交
59 60 61 62 63 64 65 66 67
    def convert(self, image_dir, json_dir, dataset_save_dir):
        """转换。
        Args:
            image_dir (str): 图像文件存放的路径。
            json_dir (str): 与每张图像对应的json文件的存放路径。
            dataset_save_dir (str): 转换后数据集存放路径。
        """
        assert osp.exists(image_dir), "he image folder does not exist!"
        assert osp.exists(json_dir), "The json folder does not exist!"
S
sunyanfang01 已提交
68 69 70 71 72 73
        assert osp.exists(dataset_save_dir), "The save folder does not exist!"
        # Convert the image files.
        new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
        if osp.exists(new_image_dir):
            shutil.rmtree(new_image_dir)
        os.makedirs(new_image_dir)
S
sunyanfang01 已提交
74
        for img_name in os.listdir(image_dir):
S
sunyanfang01 已提交
75 76
            if is_pic(img_name):
                shutil.copyfile(
S
sunyanfang01 已提交
77
                            osp.join(image_dir, img_name),
S
sunyanfang01 已提交
78 79
                            osp.join(new_image_dir, img_name))
        # Convert the json files.
S
sunyanfang01 已提交
80
        self.parse_json(new_image_dir, json_dir)
S
sunyanfang01 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93
        coco_data = {}
        coco_data["images"] = self.images_list
        coco_data["categories"] = self.categories_list
        coco_data["annotations"] = self.annotations_list
        json_path = osp.join(dataset_save_dir, "annotations.json")
        json.dump(
            coco_data,
            open(json_path, "w"),
            indent=4,
            cls=MyEncoder)
    
    
class LabelMe2COCO(X2COCO):
S
sunyanfang01 已提交
94 95
    """将使用LabelMe标注的数据集转换为COCO数据集。
    """
S
sunyanfang01 已提交
96 97 98
    def __init__(self):
        super(LabelMe2COCO, self).__init__()
        
S
sunyanfang01 已提交
99
    def generate_images_field(self, json_info, image_file, image_id):
S
sunyanfang01 已提交
100 101 102 103
        image = {}
        image["height"] = json_info["imageHeight"]
        image["width"] = json_info["imageWidth"]
        image["id"] = image_id + 1
S
sunyanfang01 已提交
104 105
        json_img_path = path_normalization(json_info["imagePath"])
        json_info["imagePath"] = osp.join(osp.split(json_img_path)[0], image_file)
S
SunAhong1993 已提交
106
        image["file_name"] = osp.split(json_info["imagePath"])[-1]
S
sunyanfang01 已提交
107 108 109 110 111 112 113 114 115
        return image
    
    def generate_polygon_anns_field(self, height, width, 
                                    points, label, image_id, 
                                    object_id, label_to_num):
        annotation = {}
        annotation["segmentation"] = [list(np.asarray(points).flatten())]
        annotation["iscrowd"] = 0
        annotation["image_id"] = image_id + 1
S
sunyanfang01 已提交
116
        annotation["bbox"] = list(map(float, self.get_bbox(height, width, points)))
S
sunyanfang01 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
        annotation["category_id"] = label_to_num[label]
        annotation["id"] = object_id + 1
        return annotation
    
    def get_bbox(self, height, width, points):
        polygons = points
        mask = np.zeros([height, width], dtype=np.uint8)
        mask = PIL.Image.fromarray(mask)
        xy = list(map(tuple, polygons))
        PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
        mask = np.array(mask, dtype=bool)
        index = np.argwhere(mask == 1)
        rows = index[:, 0]
        clos = index[:, 1]
        left_top_r = np.min(rows)
        left_top_c = np.min(clos)
        right_bottom_r = np.max(rows)
        right_bottom_c = np.max(clos)
        return [
            left_top_c, left_top_r, right_bottom_c - left_top_c,
            right_bottom_r - left_top_r
        ]
    
S
sunyanfang01 已提交
141
    def parse_json(self, img_dir, json_dir):
S
sunyanfang01 已提交
142 143 144 145 146 147 148 149
        image_id = -1
        object_id = -1
        labels_list = []
        label_to_num = {}
        for img_file in os.listdir(img_dir):
            img_name_part = osp.splitext(img_file)[0]
            json_file = osp.join(json_dir, img_name_part + ".json")
            if not osp.exists(json_file):
碧雨若风's avatar
碧雨若风 已提交
150
                os.remove(osp.join(img_dir, img_file))
S
sunyanfang01 已提交
151 152 153 154 155
                continue
            image_id = image_id + 1
            with open(json_file, mode='r', \
                              encoding=get_encoding(json_file)) as j:
                json_info = json.load(j)
S
sunyanfang01 已提交
156
                img_info = self.generate_images_field(json_info, img_file, image_id)
S
sunyanfang01 已提交
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
                self.images_list.append(img_info)
                for shapes in json_info["shapes"]:
                    object_id = object_id + 1
                    label = shapes["label"]
                    if label not in labels_list:
                        self.categories_list.append(\
                            self.generate_categories_field(label, labels_list))
                        labels_list.append(label)
                        label_to_num[label] = len(labels_list)
                    points = shapes["points"]
                    p_type = shapes["shape_type"]
                    if p_type == "polygon":
                        self.annotations_list.append(
                            self.generate_polygon_anns_field(json_info["imageHeight"], json_info[
                                "imageWidth"], points, label, image_id,
                                                object_id, label_to_num))
                    if p_type == "rectangle":
                        points.append([points[0][0], points[1][1]])
                        points.append([points[1][0], points[0][1]])
                        self.annotations_list.append(
                            self.generate_rectangle_anns_field(points, label, image_id,
                                                  object_id, label_to_num))
                        
    
class EasyData2COCO(X2COCO):
S
sunyanfang01 已提交
182 183
    """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
    """
S
sunyanfang01 已提交
184 185 186 187 188 189 190 191 192
    def __init__(self):
        super(EasyData2COCO, self).__init__()        
    
    def generate_images_field(self, img_path, image_id):
        image = {}
        img = cv2.imread(img_path)
        image["height"] = img.shape[0]
        image["width"] = img.shape[1]
        image["id"] = image_id + 1
S
fix  
SunAhong1993 已提交
193
        img_path = path_normalization(img_path)
S
sunyanfang01 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        image["file_name"] = osp.split(img_path)[-1]
        return image
    
    def generate_polygon_anns_field(self, points, segmentation, 
                                    label, image_id, object_id,
                                    label_to_num):
        annotation = {}
        annotation["segmentation"] = segmentation
        annotation["iscrowd"] = 1 if len(segmentation) > 1 else 0
        annotation["image_id"] = image_id + 1
        annotation["bbox"] = list(map(float, [
                points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
                    1] - points[0][1]
            ]))
        annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
        annotation["category_id"] = label_to_num[label]
        annotation["id"] = object_id + 1
        return annotation
        
S
sunyanfang01 已提交
213
    def parse_json(self, img_dir, json_dir):
S
sunyanfang01 已提交
214 215 216 217 218 219 220 221 222
        from pycocotools.mask import decode
        image_id = -1
        object_id = -1
        labels_list = []
        label_to_num = {}
        for img_file in os.listdir(img_dir):
            img_name_part = osp.splitext(img_file)[0]
            json_file = osp.join(json_dir, img_name_part + ".json")
            if not osp.exists(json_file):
碧雨若风's avatar
碧雨若风 已提交
223
                os.remove(osp.join(img_dir, img_file))
S
sunyanfang01 已提交
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
                continue
            image_id = image_id + 1
            with open(json_file, mode='r', \
                              encoding=get_encoding(json_file)) as j:
                json_info = json.load(j)
                img_info = self.generate_images_field(osp.join(img_dir, img_file), image_id)
                self.images_list.append(img_info)
                for shapes in json_info["labels"]:
                    object_id = object_id + 1
                    label = shapes["name"]
                    if label not in labels_list:
                        self.categories_list.append(\
                            self.generate_categories_field(label, labels_list))
                        labels_list.append(label)
                        label_to_num[label] = len(labels_list)
                    points = [[shapes["x1"], shapes["y1"]],
                              [shapes["x2"], shapes["y2"]]]
                    if "mask" not in shapes:
                        points.append([points[0][0], points[1][1]])
                        points.append([points[1][0], points[0][1]])
                        self.annotations_list.append(
                            self.generate_rectangle_anns_field(points, label, image_id,
                                                  object_id, label_to_num))
                    else:
                        mask_dict = {}
                        mask_dict['size'] = [img_info["height"], img_info["width"]]
                        mask_dict['counts'] = shapes['mask'].encode()
                        mask = decode(mask_dict)
                        contours, hierarchy = cv2.findContours(
                                (mask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
                        segmentation = []
                        for contour in contours:
                            contour_list = contour.flatten().tolist()
                            if len(contour_list) > 4:
                                segmentation.append(contour_list)
                        self.annotations_list.append(
                            self.generate_polygon_anns_field(points, segmentation, label, image_id, object_id,
S
sunyanfang01 已提交
261
                                                label_to_num))
S
SunAhong1993 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274
                        

class JingLing2COCO(X2COCO):
    """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
    """
    def __init__(self):
        super(JingLing2COCO, self).__init__()
        
    def generate_images_field(self, json_info, image_id):
        image = {}
        image["height"] = json_info["size"]["height"]
        image["width"] = json_info["size"]["width"]
        image["id"] = image_id + 1
S
fix  
SunAhong1993 已提交
275
        json_info["path"] = path_normalization(json_info["path"])
S
SunAhong1993 已提交
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
        image["file_name"] = osp.split(json_info["path"])[-1]
        return image
    
    def generate_polygon_anns_field(self, height, width, 
                                    points, label, image_id, 
                                    object_id, label_to_num):
        annotation = {}
        annotation["segmentation"] = [list(np.asarray(points).flatten())]
        annotation["iscrowd"] = 0
        annotation["image_id"] = image_id + 1
        annotation["bbox"] = list(map(float, self.get_bbox(height, width, points)))
        annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
        annotation["category_id"] = label_to_num[label]
        annotation["id"] = object_id + 1
        return annotation
    
    def get_bbox(self, height, width, points):
        polygons = points
        mask = np.zeros([height, width], dtype=np.uint8)
        mask = PIL.Image.fromarray(mask)
        xy = list(map(tuple, polygons))
        PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
        mask = np.array(mask, dtype=bool)
        index = np.argwhere(mask == 1)
        rows = index[:, 0]
        clos = index[:, 1]
        left_top_r = np.min(rows)
        left_top_c = np.min(clos)
        right_bottom_r = np.max(rows)
        right_bottom_c = np.max(clos)
        return [
            left_top_c, left_top_r, right_bottom_c - left_top_c,
            right_bottom_r - left_top_r
        ]
        
    def parse_json(self, img_dir, json_dir):
        image_id = -1
        object_id = -1
        labels_list = []
        label_to_num = {}
        for img_file in os.listdir(img_dir):
            img_name_part = osp.splitext(img_file)[0]
            json_file = osp.join(json_dir, img_name_part + ".json")
            if not osp.exists(json_file):
碧雨若风's avatar
碧雨若风 已提交
320
                os.remove(osp.join(img_dir, img_file))
S
SunAhong1993 已提交
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
                continue
            image_id = image_id + 1
            with open(json_file, mode='r', \
                              encoding=get_encoding(json_file)) as j:
                json_info = json.load(j)
                img_info = self.generate_images_field(json_info, image_id)
                self.images_list.append(img_info)
                anns_type = "bndbox"
                for i, obj in enumerate(json_info["outputs"]["object"]):
                    if i == 0:
                        if "polygon" in obj:
                            anns_type = "polygon" 
                    else:
                        if anns_type not in obj:
                            continue
                    object_id = object_id + 1
                    label = obj["name"]
                    if label not in labels_list:
                        self.categories_list.append(\
                            self.generate_categories_field(label, labels_list))
                        labels_list.append(label)
                        label_to_num[label] = len(labels_list)
                    if anns_type == "polygon":
                        points = []
                        for j in range(int(len(obj["polygon"]) / 2.0)):
                            points.append([obj["polygon"]["x" + str(j + 1)], 
                                           obj["polygon"]["y" + str(j + 1)]])
                        self.annotations_list.append(
                            self.generate_polygon_anns_field(json_info["size"]["height"], 
                                                             json_info["size"]["width"], 
                                                             points, 
                                                             label, 
                                                             image_id,
                                                             object_id, 
                                                             label_to_num))
                    if anns_type == "bndbox":
                        points = []
                        points.append([obj["bndbox"]["xmin"], obj["bndbox"]["ymin"]])
                        points.append([obj["bndbox"]["xmax"], obj["bndbox"]["ymax"]])
                        points.append([obj["bndbox"]["xmin"], obj["bndbox"]["ymax"]])
                        points.append([obj["bndbox"]["xmax"], obj["bndbox"]["ymin"]])
                        self.annotations_list.append(
                            self.generate_rectangle_anns_field(points, label, image_id,
S
sunyanfang01 已提交
364
                                                  object_id, label_to_num))