x2coco.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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 re
  22. import numpy as np
  23. import PIL.ImageDraw
  24. import xml.etree.ElementTree as ET
  25. from .base import MyEncoder, is_pic, get_encoding
  26. from paddlex.utils import path_normalization
  27. import paddlex.utils.logging as logging
  28. class X2COCO(object):
  29. def __init__(self):
  30. self.images_list = []
  31. self.categories_list = []
  32. self.annotations_list = []
  33. def generate_categories_field(self, label, labels_list):
  34. category = {}
  35. category["supercategory"] = "component"
  36. category["id"] = len(labels_list) + 1
  37. category["name"] = label
  38. return category
  39. def generate_rectangle_anns_field(self, points, label, image_id, object_id,
  40. label_to_num):
  41. annotation = {}
  42. seg_points = np.asarray(points).copy()
  43. seg_points[1, :] = np.asarray(points)[2, :]
  44. seg_points[2, :] = np.asarray(points)[1, :]
  45. annotation["segmentation"] = [list(seg_points.flatten())]
  46. annotation["iscrowd"] = 0
  47. annotation["image_id"] = image_id + 1
  48. annotation["bbox"] = list(
  49. map(float, [
  50. points[0][0], points[0][1], points[1][0] - points[0][0],
  51. points[1][1] - points[0][1]
  52. ]))
  53. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  54. annotation["category_id"] = label_to_num[label]
  55. annotation["id"] = object_id + 1
  56. return annotation
  57. def convert(self, image_dir, json_dir, dataset_save_dir):
  58. """转换。
  59. Args:
  60. image_dir (str): 图像文件存放的路径。
  61. json_dir (str): 与每张图像对应的json文件的存放路径。
  62. dataset_save_dir (str): 转换后数据集存放路径。
  63. """
  64. assert osp.exists(image_dir), "he image folder does not exist!"
  65. assert osp.exists(json_dir), "The json folder does not exist!"
  66. assert osp.exists(dataset_save_dir), "The save folder does not exist!"
  67. # Convert the image files.
  68. new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
  69. if osp.exists(new_image_dir):
  70. shutil.rmtree(new_image_dir)
  71. os.makedirs(new_image_dir)
  72. for img_name in os.listdir(image_dir):
  73. if is_pic(img_name):
  74. shutil.copyfile(
  75. osp.join(image_dir, img_name),
  76. osp.join(new_image_dir, img_name))
  77. # Convert the json files.
  78. self.parse_json(new_image_dir, json_dir)
  79. coco_data = {}
  80. coco_data["images"] = self.images_list
  81. coco_data["categories"] = self.categories_list
  82. coco_data["annotations"] = self.annotations_list
  83. json_path = osp.join(dataset_save_dir, "annotations.json")
  84. json.dump(coco_data, open(json_path, "w"), indent=4, 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_file, image_id):
  91. image = {}
  92. image["height"] = json_info["imageHeight"]
  93. image["width"] = json_info["imageWidth"]
  94. image["id"] = image_id + 1
  95. json_img_path = path_normalization(json_info["imagePath"])
  96. json_info["imagePath"] = osp.join(
  97. osp.split(json_img_path)[0], image_file)
  98. image["file_name"] = osp.split(json_info["imagePath"])[-1]
  99. return image
  100. def generate_polygon_anns_field(self, height, width, points, label,
  101. image_id, object_id, label_to_num):
  102. annotation = {}
  103. annotation["segmentation"] = [list(np.asarray(points).flatten())]
  104. annotation["iscrowd"] = 0
  105. annotation["image_id"] = image_id + 1
  106. annotation["bbox"] = list(
  107. map(float, self.get_bbox(height, width, points)))
  108. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  109. annotation["category_id"] = label_to_num[label]
  110. annotation["id"] = object_id + 1
  111. return annotation
  112. def get_bbox(self, height, width, points):
  113. polygons = points
  114. mask = np.zeros([height, width], dtype=np.uint8)
  115. mask = PIL.Image.fromarray(mask)
  116. xy = list(map(tuple, polygons))
  117. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  118. mask = np.array(mask, dtype=bool)
  119. index = np.argwhere(mask == 1)
  120. rows = index[:, 0]
  121. clos = index[:, 1]
  122. left_top_r = np.min(rows)
  123. left_top_c = np.min(clos)
  124. right_bottom_r = np.max(rows)
  125. right_bottom_c = np.max(clos)
  126. return [
  127. left_top_c, left_top_r, right_bottom_c - left_top_c,
  128. right_bottom_r - left_top_r
  129. ]
  130. def parse_json(self, img_dir, json_dir):
  131. image_id = -1
  132. object_id = -1
  133. labels_list = []
  134. label_to_num = {}
  135. for img_file in os.listdir(img_dir):
  136. img_name_part = osp.splitext(img_file)[0]
  137. json_file = osp.join(json_dir, img_name_part + ".json")
  138. if not osp.exists(json_file):
  139. os.remove(osp.join(img_dir, img_file))
  140. continue
  141. image_id = image_id + 1
  142. with open(json_file, mode='r', \
  143. encoding=get_encoding(json_file)) as j:
  144. json_info = json.load(j)
  145. img_info = self.generate_images_field(json_info, img_file,
  146. image_id)
  147. self.images_list.append(img_info)
  148. for shapes in json_info["shapes"]:
  149. object_id = object_id + 1
  150. label = shapes["label"]
  151. if label not in labels_list:
  152. self.categories_list.append(\
  153. self.generate_categories_field(label, labels_list))
  154. labels_list.append(label)
  155. label_to_num[label] = len(labels_list)
  156. points = shapes["points"]
  157. p_type = shapes["shape_type"]
  158. if p_type == "polygon":
  159. self.annotations_list.append(
  160. self.generate_polygon_anns_field(
  161. json_info["imageHeight"], json_info[
  162. "imageWidth"], points, label, image_id,
  163. object_id, label_to_num))
  164. if p_type == "rectangle":
  165. points.append([points[0][0], points[1][1]])
  166. points.append([points[1][0], points[0][1]])
  167. self.annotations_list.append(
  168. self.generate_rectangle_anns_field(
  169. points, label, image_id, object_id,
  170. label_to_num))
  171. class EasyData2COCO(X2COCO):
  172. """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
  173. """
  174. def __init__(self):
  175. super(EasyData2COCO, self).__init__()
  176. def generate_images_field(self, img_path, image_id):
  177. image = {}
  178. img = cv2.imread(img_path)
  179. image["height"] = img.shape[0]
  180. image["width"] = img.shape[1]
  181. image["id"] = image_id + 1
  182. img_path = path_normalization(img_path)
  183. image["file_name"] = osp.split(img_path)[-1]
  184. return image
  185. def generate_polygon_anns_field(self, points, segmentation, label,
  186. image_id, object_id, label_to_num):
  187. annotation = {}
  188. annotation["segmentation"] = segmentation
  189. annotation["iscrowd"] = 1 if len(segmentation) > 1 else 0
  190. annotation["image_id"] = image_id + 1
  191. annotation["bbox"] = list(
  192. map(float, [
  193. points[0][0], points[0][1], points[1][0] - points[0][0],
  194. points[1][1] - points[0][1]
  195. ]))
  196. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  197. annotation["category_id"] = label_to_num[label]
  198. annotation["id"] = object_id + 1
  199. return annotation
  200. def parse_json(self, img_dir, json_dir):
  201. from pycocotools.mask import decode
  202. image_id = -1
  203. object_id = -1
  204. labels_list = []
  205. label_to_num = {}
  206. for img_file in os.listdir(img_dir):
  207. img_name_part = osp.splitext(img_file)[0]
  208. json_file = osp.join(json_dir, img_name_part + ".json")
  209. if not osp.exists(json_file):
  210. os.remove(osp.join(img_dir, img_file))
  211. continue
  212. image_id = image_id + 1
  213. with open(json_file, mode='r', \
  214. encoding=get_encoding(json_file)) as j:
  215. json_info = json.load(j)
  216. img_info = self.generate_images_field(
  217. osp.join(img_dir, img_file), image_id)
  218. self.images_list.append(img_info)
  219. for shapes in json_info["labels"]:
  220. object_id = object_id + 1
  221. label = shapes["name"]
  222. if label not in labels_list:
  223. self.categories_list.append(\
  224. self.generate_categories_field(label, labels_list))
  225. labels_list.append(label)
  226. label_to_num[label] = len(labels_list)
  227. points = [[shapes["x1"], shapes["y1"]],
  228. [shapes["x2"], shapes["y2"]]]
  229. if "mask" not in shapes:
  230. points.append([points[0][0], points[1][1]])
  231. points.append([points[1][0], points[0][1]])
  232. self.annotations_list.append(
  233. self.generate_rectangle_anns_field(
  234. points, label, image_id, object_id,
  235. label_to_num))
  236. else:
  237. mask_dict = {}
  238. mask_dict[
  239. 'size'] = [img_info["height"], img_info["width"]]
  240. mask_dict['counts'] = shapes['mask'].encode()
  241. mask = decode(mask_dict)
  242. contours, hierarchy = cv2.findContours(
  243. (mask).astype(np.uint8), cv2.RETR_TREE,
  244. cv2.CHAIN_APPROX_SIMPLE)
  245. segmentation = []
  246. for contour in contours:
  247. contour_list = contour.flatten().tolist()
  248. if len(contour_list) > 4:
  249. segmentation.append(contour_list)
  250. self.annotations_list.append(
  251. self.generate_polygon_anns_field(
  252. points, segmentation, label, image_id,
  253. object_id, label_to_num))
  254. class JingLing2COCO(X2COCO):
  255. """将使用EasyData标注的检测或分割数据集转换为COCO数据集。
  256. """
  257. def __init__(self):
  258. super(JingLing2COCO, self).__init__()
  259. def generate_images_field(self, json_info, image_id):
  260. image = {}
  261. image["height"] = json_info["size"]["height"]
  262. image["width"] = json_info["size"]["width"]
  263. image["id"] = image_id + 1
  264. json_info["path"] = path_normalization(json_info["path"])
  265. image["file_name"] = osp.split(json_info["path"])[-1]
  266. return image
  267. def generate_polygon_anns_field(self, height, width, points, label,
  268. image_id, object_id, label_to_num):
  269. annotation = {}
  270. annotation["segmentation"] = [list(np.asarray(points).flatten())]
  271. annotation["iscrowd"] = 0
  272. annotation["image_id"] = image_id + 1
  273. annotation["bbox"] = list(
  274. map(float, self.get_bbox(height, width, points)))
  275. annotation["area"] = annotation["bbox"][2] * annotation["bbox"][3]
  276. annotation["category_id"] = label_to_num[label]
  277. annotation["id"] = object_id + 1
  278. return annotation
  279. def get_bbox(self, height, width, points):
  280. polygons = points
  281. mask = np.zeros([height, width], dtype=np.uint8)
  282. mask = PIL.Image.fromarray(mask)
  283. xy = list(map(tuple, polygons))
  284. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  285. mask = np.array(mask, dtype=bool)
  286. index = np.argwhere(mask == 1)
  287. rows = index[:, 0]
  288. clos = index[:, 1]
  289. left_top_r = np.min(rows)
  290. left_top_c = np.min(clos)
  291. right_bottom_r = np.max(rows)
  292. right_bottom_c = np.max(clos)
  293. return [
  294. left_top_c, left_top_r, right_bottom_c - left_top_c,
  295. right_bottom_r - left_top_r
  296. ]
  297. def parse_json(self, img_dir, json_dir):
  298. image_id = -1
  299. object_id = -1
  300. labels_list = []
  301. label_to_num = {}
  302. for img_file in os.listdir(img_dir):
  303. img_name_part = osp.splitext(img_file)[0]
  304. json_file = osp.join(json_dir, img_name_part + ".json")
  305. if not osp.exists(json_file):
  306. os.remove(osp.join(img_dir, img_file))
  307. continue
  308. image_id = image_id + 1
  309. with open(json_file, mode='r', \
  310. encoding=get_encoding(json_file)) as j:
  311. json_info = json.load(j)
  312. img_info = self.generate_images_field(json_info, image_id)
  313. self.images_list.append(img_info)
  314. anns_type = "bndbox"
  315. for i, obj in enumerate(json_info["outputs"]["object"]):
  316. if i == 0:
  317. if "polygon" in obj:
  318. anns_type = "polygon"
  319. else:
  320. if anns_type not in obj:
  321. continue
  322. object_id = object_id + 1
  323. label = obj["name"]
  324. if label not in labels_list:
  325. self.categories_list.append(\
  326. self.generate_categories_field(label, labels_list))
  327. labels_list.append(label)
  328. label_to_num[label] = len(labels_list)
  329. if anns_type == "polygon":
  330. points = []
  331. for j in range(int(len(obj["polygon"]) / 2.0)):
  332. points.append([
  333. obj["polygon"]["x" + str(j + 1)],
  334. obj["polygon"]["y" + str(j + 1)]
  335. ])
  336. self.annotations_list.append(
  337. self.generate_polygon_anns_field(
  338. json_info["size"]["height"], json_info["size"][
  339. "width"], points, label, image_id,
  340. object_id, label_to_num))
  341. if anns_type == "bndbox":
  342. points = []
  343. points.append(
  344. [obj["bndbox"]["xmin"], obj["bndbox"]["ymin"]])
  345. points.append(
  346. [obj["bndbox"]["xmax"], obj["bndbox"]["ymax"]])
  347. points.append(
  348. [obj["bndbox"]["xmin"], obj["bndbox"]["ymax"]])
  349. points.append(
  350. [obj["bndbox"]["xmax"], obj["bndbox"]["ymin"]])
  351. self.annotations_list.append(
  352. self.generate_rectangle_anns_field(
  353. points, label, image_id, object_id,
  354. label_to_num))
  355. class VOC2COCO(X2COCO):
  356. """将使用VOC标注的数据集转换为COCO数据集。
  357. """
  358. def __init__(self):
  359. super(VOC2COCO, self).__init__()
  360. def generate_categories_field(self, label, labels_list):
  361. category = {}
  362. category["supercategory"] = "component"
  363. category["id"] = len(labels_list) + 1
  364. category["name"] = label
  365. return category
  366. def generate_images_field(self, xml_info, image_file, image_id):
  367. image = {}
  368. image["height"] = xml_info["imageHeight"]
  369. image["width"] = xml_info["imageWidth"]
  370. image["id"] = image_id + 1
  371. image["imagePath"] = image_file
  372. image["file_name"] = osp.split(image_file)[-1]
  373. return image
  374. def generate_label_list(self, xml_dir):
  375. xml_dir_dir = os.path.abspath(
  376. os.path.join(os.path.dirname(xml_dir), os.path.pardir))
  377. self.labels_list = []
  378. self.label_to_num = {}
  379. if osp.exists(osp.join(xml_dir_dir, 'labels.txt')):
  380. with open(osp.join(xml_dir_dir, 'labels.txt'), 'r') as fr:
  381. while True:
  382. label = fr.readline().strip()
  383. if not label:
  384. break
  385. if label not in self.labels_list:
  386. self.categories_list.append(\
  387. self.generate_categories_field(label, self.labels_list))
  388. self.labels_list.append(label)
  389. self.label_to_num[label] = len(self.labels_list)
  390. return
  391. logging.info(
  392. 'labels.txt is not in the folder {}, so categories are ordered randomly in annotation.json.'.
  393. format(xml_dir_dir))
  394. return
  395. def parse_xml(self, xml_file):
  396. xml_info = {'im_info': {}, 'annotations': []}
  397. tree = ET.parse(xml_file)
  398. pattern = re.compile('<object>', re.IGNORECASE)
  399. obj_match = pattern.findall(str(ET.tostringlist(tree.getroot())))
  400. obj_tag = obj_match[0][1:-1]
  401. objs = tree.findall(obj_tag)
  402. pattern = re.compile('<size>', re.IGNORECASE)
  403. size_tag = pattern.findall(str(ET.tostringlist(tree.getroot())))[0][1:
  404. -1]
  405. size_element = tree.find(size_tag)
  406. pattern = re.compile('<width>', re.IGNORECASE)
  407. width_tag = pattern.findall(str(ET.tostringlist(size_element)))[0][1:
  408. -1]
  409. im_w = float(size_element.find(width_tag).text)
  410. pattern = re.compile('<height>', re.IGNORECASE)
  411. height_tag = pattern.findall(str(ET.tostringlist(size_element)))[0][1:
  412. -1]
  413. im_h = float(size_element.find(height_tag).text)
  414. xml_info['im_info']['imageWidth'] = im_w
  415. xml_info['im_info']['imageHeight'] = im_h
  416. for i, obj in enumerate(objs):
  417. pattern = re.compile('<name>', re.IGNORECASE)
  418. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][1:-1]
  419. cname = obj.find(name_tag).text.strip()
  420. pattern = re.compile('<bndbox>', re.IGNORECASE)
  421. box_tag = pattern.findall(str(ET.tostringlist(obj)))[0][1:-1]
  422. box_element = obj.find(box_tag)
  423. pattern = re.compile('<xmin>', re.IGNORECASE)
  424. xmin_tag = pattern.findall(str(ET.tostringlist(box_element)))[0][
  425. 1:-1]
  426. x1 = float(box_element.find(xmin_tag).text)
  427. pattern = re.compile('<ymin>', re.IGNORECASE)
  428. ymin_tag = pattern.findall(str(ET.tostringlist(box_element)))[0][
  429. 1:-1]
  430. y1 = float(box_element.find(ymin_tag).text)
  431. pattern = re.compile('<xmax>', re.IGNORECASE)
  432. xmax_tag = pattern.findall(str(ET.tostringlist(box_element)))[0][
  433. 1:-1]
  434. x2 = float(box_element.find(xmax_tag).text)
  435. pattern = re.compile('<ymax>', re.IGNORECASE)
  436. ymax_tag = pattern.findall(str(ET.tostringlist(box_element)))[0][
  437. 1:-1]
  438. y2 = float(box_element.find(ymax_tag).text)
  439. x1 = max(0, x1)
  440. y1 = max(0, y1)
  441. if im_w > 0.5 and im_h > 0.5:
  442. x2 = min(im_w - 1, x2)
  443. y2 = min(im_h - 1, y2)
  444. xml_info['annotations'].append({
  445. 'bbox': [[x1, y1], [x2, y2], [x1, y2], [x2, y1]],
  446. 'category': cname,
  447. })
  448. return xml_info
  449. def parse_json(self, img_dir, xml_dir, file_list=None):
  450. image_id = -1
  451. object_id = -1
  452. self.generate_label_list(xml_dir)
  453. for img_file in os.listdir(img_dir):
  454. if file_list is not None and img_file not in file_list:
  455. continue
  456. img_name_part = osp.splitext(img_file)[0]
  457. xml_file = osp.join(xml_dir, img_name_part + ".xml")
  458. if not osp.exists(xml_file):
  459. os.remove(osp.join(img_dir, img_file))
  460. continue
  461. image_id = image_id + 1
  462. xml_info = self.parse_xml(xml_file)
  463. img_info = self.generate_images_field(xml_info['im_info'],
  464. osp.join(img_dir, img_file),
  465. image_id)
  466. self.images_list.append(img_info)
  467. annos = xml_info['annotations']
  468. for anno in annos:
  469. object_id = object_id + 1
  470. label = anno["category"]
  471. if label not in self.labels_list:
  472. self.categories_list.append(\
  473. self.generate_categories_field(label, self.labels_list))
  474. self.labels_list.append(label)
  475. self.label_to_num[label] = len(self.labels_list)
  476. self.annotations_list.append(
  477. self.generate_rectangle_anns_field(anno[
  478. 'bbox'], label, image_id, object_id,
  479. self.label_to_num))
  480. def convert(self, image_dir, json_dir, dataset_save_dir):
  481. """转换。
  482. Args:
  483. image_dir (str): 图像文件存放的路径。
  484. json_dir (str): 与每张图像对应的json文件的存放路径。
  485. dataset_save_dir (str): 转换后数据集存放路径。
  486. """
  487. assert osp.exists(image_dir), "he image folder does not exist!"
  488. assert osp.exists(json_dir), "The json folder does not exist!"
  489. assert osp.exists(dataset_save_dir), "The save folder does not exist!"
  490. # Convert the image files.
  491. new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
  492. if osp.exists(new_image_dir):
  493. shutil.rmtree(new_image_dir)
  494. os.makedirs(new_image_dir)
  495. for img_name in os.listdir(image_dir):
  496. if is_pic(img_name):
  497. shutil.copyfile(
  498. osp.join(image_dir, img_name),
  499. osp.join(new_image_dir, img_name))
  500. # Convert the json files.
  501. xml_dir_dir = os.path.abspath(
  502. os.path.join(os.path.dirname(json_dir), os.path.pardir))
  503. for part in ['train', 'val', 'test']:
  504. part_list_file = osp.join(xml_dir_dir, '{}_list.txt'.format(part))
  505. if osp.exists(part_list_file):
  506. file_list = list()
  507. with open(part_list_file, 'r') as f:
  508. while True:
  509. line = f.readline()
  510. if not line:
  511. break
  512. if len(line.strip().split()) > 2:
  513. raise Exception(
  514. "A space is defined as the separator, but it exists in image or label name {}."
  515. .format(line))
  516. img_file = osp.join(
  517. image_dir, osp.split(line.strip().split()[0])[-1])
  518. xml_file = osp.join(
  519. json_dir, osp.split(line.strip().split()[1])[-1])
  520. img_file = path_normalization(img_file)
  521. xml_file = path_normalization(xml_file)
  522. if not is_pic(img_file):
  523. continue
  524. if not osp.isfile(xml_file):
  525. continue
  526. if not osp.exists(img_file):
  527. raise IOError('The image file {} is not exist!'.
  528. format(img_file))
  529. file_list.append(osp.split(img_file)[-1])
  530. self.parse_json(new_image_dir, json_dir, file_list)
  531. coco_data = {}
  532. coco_data["images"] = self.images_list
  533. coco_data["categories"] = self.categories_list
  534. coco_data["annotations"] = self.annotations_list
  535. json_path = osp.join(dataset_save_dir, "{}.json".format(part))
  536. json.dump(
  537. coco_data, open(json_path, "w"), indent=4, cls=MyEncoder)
  538. logging.info("xml files in {} are converted to the MSCOCO format stored in {}".format(\
  539. osp.join(xml_dir_dir, '{}_list.txt'.format(part)), osp.join(dataset_save_dir, "{}.json".format(part))))
  540. self.images_list = []
  541. self.annotations_list = []
  542. self.parse_json(new_image_dir, json_dir)
  543. coco_data = {}
  544. coco_data["images"] = self.images_list
  545. coco_data["categories"] = self.categories_list
  546. coco_data["annotations"] = self.annotations_list
  547. json_path = osp.join(dataset_save_dir, "annotations.json")
  548. json.dump(coco_data, open(json_path, "w"), indent=4, cls=MyEncoder)