x2coco.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. from paddlex.utils import path_normalization
  25. class X2COCO(object):
  26. def __init__(self):
  27. self.images_list = []
  28. self.categories_list = []
  29. self.annotations_list = []
  30. def generate_categories_field(self, label, labels_list):
  31. category = {}
  32. category["supercategory"] = "component"
  33. category["id"] = len(labels_list) + 1
  34. category["name"] = label
  35. return category
  36. def generate_rectangle_anns_field(self, points, label, image_id, object_id, label_to_num):
  37. annotation = {}
  38. seg_points = np.asarray(points).copy()
  39. seg_points[1, :] = np.asarray(points)[2, :]
  40. seg_points[2, :] = np.asarray(points)[1, :]
  41. annotation["segmentation"] = [list(seg_points.flatten())]
  42. annotation["iscrowd"] = 0
  43. annotation["image_id"] = image_id + 1
  44. annotation["bbox"] = list(
  45. map(float, [
  46. points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
  47. 1] - points[0][1]
  48. ]))
  49. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  50. annotation["category_id"] = label_to_num[label]
  51. annotation["id"] = object_id + 1
  52. return annotation
  53. def convert(self, image_dir, json_dir, dataset_save_dir):
  54. """转换。
  55. Args:
  56. image_dir (str): 图像文件存放的路径。
  57. json_dir (str): 与每张图像对应的json文件的存放路径。
  58. dataset_save_dir (str): 转换后数据集存放路径。
  59. """
  60. assert osp.exists(image_dir), "he image folder does not exist!"
  61. assert osp.exists(json_dir), "The json folder does not exist!"
  62. assert osp.exists(dataset_save_dir), "The save folder does not exist!"
  63. # Convert the image files.
  64. new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
  65. if osp.exists(new_image_dir):
  66. shutil.rmtree(new_image_dir)
  67. os.makedirs(new_image_dir)
  68. for img_name in os.listdir(image_dir):
  69. if is_pic(img_name):
  70. shutil.copyfile(
  71. osp.join(image_dir, img_name),
  72. osp.join(new_image_dir, img_name))
  73. # Convert the json files.
  74. self.parse_json(new_image_dir, json_dir)
  75. coco_data = {}
  76. coco_data["images"] = self.images_list
  77. coco_data["categories"] = self.categories_list
  78. coco_data["annotations"] = self.annotations_list
  79. json_path = osp.join(dataset_save_dir, "annotations.json")
  80. json.dump(
  81. coco_data,
  82. open(json_path, "w"),
  83. indent=4,
  84. cls=MyEncoder)
  85. class LabelMe2COCO(X2COCO):
  86. """将使用LabelMe标注的数据集转换为COCO数据集。
  87. """
  88. def __init__(self):
  89. super(LabelMe2COCO, self).__init__()
  90. def generate_images_field(self, json_info, image_id):
  91. image = {}
  92. image["height"] = json_info["imageHeight"]
  93. image["width"] = json_info["imageWidth"]
  94. image["id"] = image_id + 1
  95. json_info["imagePath"] = path_normalization(json_info["imagePath"])
  96. image["file_name"] = osp.split(json_info["imagePath"])[-1]
  97. return image
  98. def generate_polygon_anns_field(self, height, width,
  99. points, label, image_id,
  100. object_id, label_to_num):
  101. annotation = {}
  102. annotation["segmentation"] = [list(np.asarray(points).flatten())]
  103. annotation["iscrowd"] = 0
  104. annotation["image_id"] = image_id + 1
  105. annotation["bbox"] = list(map(float, self.get_bbox(height, width, points)))
  106. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  107. annotation["category_id"] = label_to_num[label]
  108. annotation["id"] = object_id + 1
  109. return annotation
  110. def get_bbox(self, height, width, points):
  111. polygons = points
  112. mask = np.zeros([height, width], dtype=np.uint8)
  113. mask = PIL.Image.fromarray(mask)
  114. xy = list(map(tuple, polygons))
  115. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  116. mask = np.array(mask, dtype=bool)
  117. index = np.argwhere(mask == 1)
  118. rows = index[:, 0]
  119. clos = index[:, 1]
  120. left_top_r = np.min(rows)
  121. left_top_c = np.min(clos)
  122. right_bottom_r = np.max(rows)
  123. right_bottom_c = np.max(clos)
  124. return [
  125. left_top_c, left_top_r, right_bottom_c - left_top_c,
  126. right_bottom_r - left_top_r
  127. ]
  128. def parse_json(self, img_dir, json_dir):
  129. image_id = -1
  130. object_id = -1
  131. labels_list = []
  132. label_to_num = {}
  133. for img_file in os.listdir(img_dir):
  134. img_name_part = osp.splitext(img_file)[0]
  135. json_file = osp.join(json_dir, img_name_part + ".json")
  136. if not osp.exists(json_file):
  137. os.remove(osp.join(image_dir, img_file))
  138. continue
  139. image_id = image_id + 1
  140. with open(json_file, mode='r', \
  141. encoding=get_encoding(json_file)) as j:
  142. json_info = json.load(j)
  143. img_info = self.generate_images_field(json_info, image_id)
  144. self.images_list.append(img_info)
  145. for shapes in json_info["shapes"]:
  146. object_id = object_id + 1
  147. label = shapes["label"]
  148. if label not in labels_list:
  149. self.categories_list.append(\
  150. self.generate_categories_field(label, labels_list))
  151. labels_list.append(label)
  152. label_to_num[label] = len(labels_list)
  153. points = shapes["points"]
  154. p_type = shapes["shape_type"]
  155. if p_type == "polygon":
  156. self.annotations_list.append(
  157. self.generate_polygon_anns_field(json_info["imageHeight"], json_info[
  158. "imageWidth"], points, label, image_id,
  159. object_id, label_to_num))
  160. if p_type == "rectangle":
  161. points.append([points[0][0], points[1][1]])
  162. points.append([points[1][0], points[0][1]])
  163. self.annotations_list.append(
  164. self.generate_rectangle_anns_field(points, label, image_id,
  165. object_id, label_to_num))
  166. class EasyData2COCO(X2COCO):
  167. """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
  168. """
  169. def __init__(self):
  170. super(EasyData2COCO, self).__init__()
  171. def generate_images_field(self, img_path, image_id):
  172. image = {}
  173. img = cv2.imread(img_path)
  174. image["height"] = img.shape[0]
  175. image["width"] = img.shape[1]
  176. image["id"] = image_id + 1
  177. img_path = path_normalization(img_path)
  178. image["file_name"] = osp.split(img_path)[-1]
  179. return image
  180. def generate_polygon_anns_field(self, points, segmentation,
  181. label, image_id, object_id,
  182. label_to_num):
  183. annotation = {}
  184. annotation["segmentation"] = segmentation
  185. annotation["iscrowd"] = 1 if len(segmentation) > 1 else 0
  186. annotation["image_id"] = image_id + 1
  187. annotation["bbox"] = list(map(float, [
  188. points[0][0], points[0][1], points[1][0] - points[0][0], points[1][
  189. 1] - points[0][1]
  190. ]))
  191. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  192. annotation["category_id"] = label_to_num[label]
  193. annotation["id"] = object_id + 1
  194. return annotation
  195. def parse_json(self, img_dir, json_dir):
  196. from pycocotools.mask import decode
  197. image_id = -1
  198. object_id = -1
  199. labels_list = []
  200. label_to_num = {}
  201. for img_file in os.listdir(img_dir):
  202. img_name_part = osp.splitext(img_file)[0]
  203. json_file = osp.join(json_dir, img_name_part + ".json")
  204. if not osp.exists(json_file):
  205. os.remove(osp.join(image_dir, img_file))
  206. continue
  207. image_id = image_id + 1
  208. with open(json_file, mode='r', \
  209. encoding=get_encoding(json_file)) as j:
  210. json_info = json.load(j)
  211. img_info = self.generate_images_field(osp.join(img_dir, img_file), image_id)
  212. self.images_list.append(img_info)
  213. for shapes in json_info["labels"]:
  214. object_id = object_id + 1
  215. label = shapes["name"]
  216. if label not in labels_list:
  217. self.categories_list.append(\
  218. self.generate_categories_field(label, labels_list))
  219. labels_list.append(label)
  220. label_to_num[label] = len(labels_list)
  221. points = [[shapes["x1"], shapes["y1"]],
  222. [shapes["x2"], shapes["y2"]]]
  223. if "mask" not in shapes:
  224. points.append([points[0][0], points[1][1]])
  225. points.append([points[1][0], points[0][1]])
  226. self.annotations_list.append(
  227. self.generate_rectangle_anns_field(points, label, image_id,
  228. object_id, label_to_num))
  229. else:
  230. mask_dict = {}
  231. mask_dict['size'] = [img_info["height"], img_info["width"]]
  232. mask_dict['counts'] = shapes['mask'].encode()
  233. mask = decode(mask_dict)
  234. contours, hierarchy = cv2.findContours(
  235. (mask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  236. segmentation = []
  237. for contour in contours:
  238. contour_list = contour.flatten().tolist()
  239. if len(contour_list) > 4:
  240. segmentation.append(contour_list)
  241. self.annotations_list.append(
  242. self.generate_polygon_anns_field(points, segmentation, label, image_id, object_id,
  243. label_to_num))
  244. class JingLing2COCO(X2COCO):
  245. """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
  246. """
  247. def __init__(self):
  248. super(JingLing2COCO, self).__init__()
  249. def generate_images_field(self, json_info, image_id):
  250. image = {}
  251. image["height"] = json_info["size"]["height"]
  252. image["width"] = json_info["size"]["width"]
  253. image["id"] = image_id + 1
  254. json_info["path"] = path_normalization(json_info["path"])
  255. image["file_name"] = osp.split(json_info["path"])[-1]
  256. return image
  257. def generate_polygon_anns_field(self, height, width,
  258. points, label, image_id,
  259. object_id, label_to_num):
  260. annotation = {}
  261. annotation["segmentation"] = [list(np.asarray(points).flatten())]
  262. annotation["iscrowd"] = 0
  263. annotation["image_id"] = image_id + 1
  264. annotation["bbox"] = list(map(float, self.get_bbox(height, width, points)))
  265. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  266. annotation["category_id"] = label_to_num[label]
  267. annotation["id"] = object_id + 1
  268. return annotation
  269. def get_bbox(self, height, width, points):
  270. polygons = points
  271. mask = np.zeros([height, width], dtype=np.uint8)
  272. mask = PIL.Image.fromarray(mask)
  273. xy = list(map(tuple, polygons))
  274. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  275. mask = np.array(mask, dtype=bool)
  276. index = np.argwhere(mask == 1)
  277. rows = index[:, 0]
  278. clos = index[:, 1]
  279. left_top_r = np.min(rows)
  280. left_top_c = np.min(clos)
  281. right_bottom_r = np.max(rows)
  282. right_bottom_c = np.max(clos)
  283. return [
  284. left_top_c, left_top_r, right_bottom_c - left_top_c,
  285. right_bottom_r - left_top_r
  286. ]
  287. def parse_json(self, img_dir, json_dir):
  288. image_id = -1
  289. object_id = -1
  290. labels_list = []
  291. label_to_num = {}
  292. for img_file in os.listdir(img_dir):
  293. img_name_part = osp.splitext(img_file)[0]
  294. json_file = osp.join(json_dir, img_name_part + ".json")
  295. if not osp.exists(json_file):
  296. os.remove(osp.join(image_dir, img_file))
  297. continue
  298. image_id = image_id + 1
  299. with open(json_file, mode='r', \
  300. encoding=get_encoding(json_file)) as j:
  301. json_info = json.load(j)
  302. img_info = self.generate_images_field(json_info, image_id)
  303. self.images_list.append(img_info)
  304. anns_type = "bndbox"
  305. for i, obj in enumerate(json_info["outputs"]["object"]):
  306. if i == 0:
  307. if "polygon" in obj:
  308. anns_type = "polygon"
  309. else:
  310. if anns_type not in obj:
  311. continue
  312. object_id = object_id + 1
  313. label = obj["name"]
  314. if label not in labels_list:
  315. self.categories_list.append(\
  316. self.generate_categories_field(label, labels_list))
  317. labels_list.append(label)
  318. label_to_num[label] = len(labels_list)
  319. if anns_type == "polygon":
  320. points = []
  321. for j in range(int(len(obj["polygon"]) / 2.0)):
  322. points.append([obj["polygon"]["x" + str(j + 1)],
  323. obj["polygon"]["y" + str(j + 1)]])
  324. self.annotations_list.append(
  325. self.generate_polygon_anns_field(json_info["size"]["height"],
  326. json_info["size"]["width"],
  327. points,
  328. label,
  329. image_id,
  330. object_id,
  331. label_to_num))
  332. if anns_type == "bndbox":
  333. points = []
  334. points.append([obj["bndbox"]["xmin"], obj["bndbox"]["ymin"]])
  335. points.append([obj["bndbox"]["xmax"], obj["bndbox"]["ymax"]])
  336. points.append([obj["bndbox"]["xmin"], obj["bndbox"]["ymax"]])
  337. points.append([obj["bndbox"]["xmax"], obj["bndbox"]["ymin"]])
  338. self.annotations_list.append(
  339. self.generate_rectangle_anns_field(points, label, image_id,
  340. object_id, label_to_num))