x2coco.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import cv2
  17. import json
  18. import os
  19. import os.path as osp
  20. import shutil
  21. import numpy as np
  22. import PIL.ImageDraw
  23. from .base import MyEncoder, is_pic, get_encoding
  24. class X2COCO(object):
  25. def __init__(self):
  26. self.images_list = []
  27. self.categories_list = []
  28. self.annotations_list = []
  29. def generate_categories_field(self, label, labels_list):
  30. category = {}
  31. category["supercategory"] = "component"
  32. category["id"] = len(labels_list) + 1
  33. category["name"] = label
  34. return category
  35. def generate_rectangle_anns_field(self, points, label, image_id, object_id, label_to_num):
  36. annotation = {}
  37. seg_points = np.asarray(points).copy()
  38. seg_points[1, :] = np.asarray(points)[2, :]
  39. seg_points[2, :] = np.asarray(points)[1, :]
  40. annotation["segmentation"] = [list(seg_points.flatten())]
  41. annotation["iscrowd"] = 0
  42. annotation["image_id"] = image_id + 1
  43. annotation["bbox"] = list(
  44. map(float, [
  45. points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
  46. 1] - points[0][1]
  47. ]))
  48. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  49. annotation["category_id"] = label_to_num[label]
  50. annotation["id"] = object_id + 1
  51. return annotation
  52. def convert(self, image_dir, json_dir, dataset_save_dir):
  53. """转换。
  54. Args:
  55. image_dir (str): 图像文件存放的路径。
  56. json_dir (str): 与每张图像对应的json文件的存放路径。
  57. dataset_save_dir (str): 转换后数据集存放路径。
  58. """
  59. assert osp.exists(image_dir), "he image folder does not exist!"
  60. assert osp.exists(json_dir), "The json folder does not exist!"
  61. assert osp.exists(dataset_save_dir), "The save folder does not exist!"
  62. # Convert the image files.
  63. new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
  64. if osp.exists(new_image_dir):
  65. shutil.rmtree(new_image_dir)
  66. os.makedirs(new_image_dir)
  67. for img_name in os.listdir(image_dir):
  68. if is_pic(img_name):
  69. shutil.copyfile(
  70. osp.join(image_dir, img_name),
  71. osp.join(new_image_dir, img_name))
  72. # Convert the json files.
  73. self.parse_json(new_image_dir, json_dir)
  74. coco_data = {}
  75. coco_data["images"] = self.images_list
  76. coco_data["categories"] = self.categories_list
  77. coco_data["annotations"] = self.annotations_list
  78. json_path = osp.join(dataset_save_dir, "annotations.json")
  79. json.dump(
  80. coco_data,
  81. open(json_path, "w"),
  82. indent=4,
  83. cls=MyEncoder)
  84. class LabelMe2COCO(X2COCO):
  85. """将使用LabelMe标注的数据集转换为COCO数据集。
  86. """
  87. def __init__(self):
  88. super(LabelMe2COCO, self).__init__()
  89. def generate_images_field(self, json_info, image_id):
  90. image = {}
  91. image["height"] = json_info["imageHeight"]
  92. image["width"] = json_info["imageWidth"]
  93. image["id"] = image_id + 1
  94. image["file_name"] = json_info["imagePath"].split("/")[-1]
  95. return image
  96. def generate_polygon_anns_field(self, height, width,
  97. points, label, image_id,
  98. object_id, label_to_num):
  99. annotation = {}
  100. annotation["segmentation"] = [list(np.asarray(points).flatten())]
  101. annotation["iscrowd"] = 0
  102. annotation["image_id"] = image_id + 1
  103. annotation["bbox"] = list(map(float, self.get_bbox(height, width, points)))
  104. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  105. annotation["category_id"] = label_to_num[label]
  106. annotation["id"] = object_id + 1
  107. return annotation
  108. def get_bbox(self, height, width, points):
  109. polygons = points
  110. mask = np.zeros([height, width], dtype=np.uint8)
  111. mask = PIL.Image.fromarray(mask)
  112. xy = list(map(tuple, polygons))
  113. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  114. mask = np.array(mask, dtype=bool)
  115. index = np.argwhere(mask == 1)
  116. rows = index[:, 0]
  117. clos = index[:, 1]
  118. left_top_r = np.min(rows)
  119. left_top_c = np.min(clos)
  120. right_bottom_r = np.max(rows)
  121. right_bottom_c = np.max(clos)
  122. return [
  123. left_top_c, left_top_r, right_bottom_c - left_top_c,
  124. right_bottom_r - left_top_r
  125. ]
  126. def parse_json(self, img_dir, json_dir):
  127. image_id = -1
  128. object_id = -1
  129. labels_list = []
  130. label_to_num = {}
  131. for img_file in os.listdir(img_dir):
  132. img_name_part = osp.splitext(img_file)[0]
  133. json_file = osp.join(json_dir, img_name_part + ".json")
  134. if not osp.exists(json_file):
  135. os.remove(os.remove(osp.join(image_dir, img_file)))
  136. continue
  137. image_id = image_id + 1
  138. with open(json_file, mode='r', \
  139. encoding=get_encoding(json_file)) as j:
  140. json_info = json.load(j)
  141. img_info = self.generate_images_field(json_info, image_id)
  142. self.images_list.append(img_info)
  143. for shapes in json_info["shapes"]:
  144. object_id = object_id + 1
  145. label = shapes["label"]
  146. if label not in labels_list:
  147. self.categories_list.append(\
  148. self.generate_categories_field(label, labels_list))
  149. labels_list.append(label)
  150. label_to_num[label] = len(labels_list)
  151. points = shapes["points"]
  152. p_type = shapes["shape_type"]
  153. if p_type == "polygon":
  154. self.annotations_list.append(
  155. self.generate_polygon_anns_field(json_info["imageHeight"], json_info[
  156. "imageWidth"], points, label, image_id,
  157. object_id, label_to_num))
  158. if p_type == "rectangle":
  159. points.append([points[0][0], points[1][1]])
  160. points.append([points[1][0], points[0][1]])
  161. self.annotations_list.append(
  162. self.generate_rectangle_anns_field(points, label, image_id,
  163. object_id, label_to_num))
  164. class EasyData2COCO(X2COCO):
  165. """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
  166. """
  167. def __init__(self):
  168. super(EasyData2COCO, self).__init__()
  169. def generate_images_field(self, img_path, image_id):
  170. image = {}
  171. img = cv2.imread(img_path)
  172. image["height"] = img.shape[0]
  173. image["width"] = img.shape[1]
  174. image["id"] = image_id + 1
  175. image["file_name"] = osp.split(img_path)[-1]
  176. return image
  177. def generate_polygon_anns_field(self, points, segmentation,
  178. label, image_id, object_id,
  179. label_to_num):
  180. annotation = {}
  181. annotation["segmentation"] = segmentation
  182. annotation["iscrowd"] = 1 if len(segmentation) > 1 else 0
  183. annotation["image_id"] = image_id + 1
  184. annotation["bbox"] = list(map(float, [
  185. points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
  186. 1] - points[0][1]
  187. ]))
  188. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  189. annotation["category_id"] = label_to_num[label]
  190. annotation["id"] = object_id + 1
  191. return annotation
  192. def parse_json(self, img_dir, json_dir):
  193. from pycocotools.mask import decode
  194. image_id = -1
  195. object_id = -1
  196. labels_list = []
  197. label_to_num = {}
  198. for img_file in os.listdir(img_dir):
  199. img_name_part = osp.splitext(img_file)[0]
  200. json_file = osp.join(json_dir, img_name_part + ".json")
  201. if not osp.exists(json_file):
  202. os.remove(os.remove(osp.join(image_dir, img_file)))
  203. continue
  204. image_id = image_id + 1
  205. with open(json_file, mode='r', \
  206. encoding=get_encoding(json_file)) as j:
  207. json_info = json.load(j)
  208. img_info = self.generate_images_field(osp.join(img_dir, img_file), image_id)
  209. self.images_list.append(img_info)
  210. for shapes in json_info["labels"]:
  211. object_id = object_id + 1
  212. label = shapes["name"]
  213. if label not in labels_list:
  214. self.categories_list.append(\
  215. self.generate_categories_field(label, labels_list))
  216. labels_list.append(label)
  217. label_to_num[label] = len(labels_list)
  218. points = [[shapes["x1"], shapes["y1"]],
  219. [shapes["x2"], shapes["y2"]]]
  220. if "mask" not in shapes:
  221. points.append([points[0][0], points[1][1]])
  222. points.append([points[1][0], points[0][1]])
  223. self.annotations_list.append(
  224. self.generate_rectangle_anns_field(points, label, image_id,
  225. object_id, label_to_num))
  226. else:
  227. mask_dict = {}
  228. mask_dict['size'] = [img_info["height"], img_info["width"]]
  229. mask_dict['counts'] = shapes['mask'].encode()
  230. mask = decode(mask_dict)
  231. contours, hierarchy = cv2.findContours(
  232. (mask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  233. segmentation = []
  234. for contour in contours:
  235. contour_list = contour.flatten().tolist()
  236. if len(contour_list) > 4:
  237. segmentation.append(contour_list)
  238. self.annotations_list.append(
  239. self.generate_polygon_anns_field(points, segmentation, label, image_id, object_id,
  240. label_to_num))