x2coco.py 16 KB

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