x2coco.py 26 KB

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