voc.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # copyright (c) 2020 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. from __future__ import absolute_import
  15. import copy
  16. import os
  17. import os.path as osp
  18. import random
  19. import re
  20. import numpy as np
  21. import cv2
  22. import json
  23. from collections import OrderedDict
  24. import xml.etree.ElementTree as ET
  25. import paddlex.utils.logging as logging
  26. from paddlex.utils import path_normalization
  27. from .dataset import Dataset
  28. from .dataset import is_pic
  29. from .dataset import get_encoding
  30. class VOCDetection(Dataset):
  31. """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。
  32. Args:
  33. data_dir (str): 数据集所在的目录路径。
  34. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  35. label_list (str): 描述数据集包含的类别信息文件路径。
  36. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  37. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  38. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
  39. 一半。
  40. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
  41. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  42. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  43. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  44. """
  45. def __init__(self,
  46. data_dir,
  47. file_list,
  48. label_list,
  49. transforms=None,
  50. num_workers='auto',
  51. buffer_size=100,
  52. parallel_method='process',
  53. shuffle=False):
  54. from pycocotools.coco import COCO
  55. super(VOCDetection, self).__init__(
  56. transforms=transforms,
  57. num_workers=num_workers,
  58. buffer_size=buffer_size,
  59. parallel_method=parallel_method,
  60. shuffle=shuffle)
  61. self.file_list = list()
  62. self.labels = list()
  63. self._epoch = 0
  64. annotations = {}
  65. annotations['images'] = []
  66. annotations['categories'] = []
  67. annotations['annotations'] = []
  68. self.cname2cid = OrderedDict()
  69. self.cid2cname = OrderedDict()
  70. label_id = 1
  71. with open(label_list, 'r', encoding=get_encoding(label_list)) as fr:
  72. for line in fr.readlines():
  73. self.cname2cid[line.strip()] = label_id
  74. self.cid2cname[label_id] = line.strip()
  75. label_id += 1
  76. self.labels.append(line.strip())
  77. logging.info("Starting to read file list from dataset...")
  78. for k, v in self.cname2cid.items():
  79. annotations['categories'].append({
  80. 'supercategory': 'component',
  81. 'id': v,
  82. 'name': k
  83. })
  84. ct = 0
  85. self.ann_ct = 0
  86. with open(file_list, 'r', encoding=get_encoding(file_list)) as fr:
  87. while True:
  88. line = fr.readline()
  89. if not line:
  90. break
  91. if len(line.strip().split()) > 2:
  92. raise Exception(
  93. "A space is defined as the separator, but it exists in image or label name {}."
  94. .format(line))
  95. img_file, xml_file = [osp.join(data_dir, x) \
  96. for x in line.strip().split()[:2]]
  97. img_file = path_normalization(img_file)
  98. xml_file = path_normalization(xml_file)
  99. if not is_pic(img_file):
  100. continue
  101. if not osp.isfile(xml_file):
  102. continue
  103. if not osp.exists(img_file):
  104. logging.warning('The image file {} is not exist!'.format(
  105. img_file))
  106. continue
  107. if not osp.exists(xml_file):
  108. logging.warning('The annotation file {} is not exist!'.
  109. format(xml_file))
  110. continue
  111. tree = ET.parse(xml_file)
  112. if tree.find('id') is None:
  113. im_id = np.array([ct])
  114. else:
  115. ct = int(tree.find('id').text)
  116. im_id = np.array([int(tree.find('id').text)])
  117. pattern = re.compile('<object>', re.IGNORECASE)
  118. obj_match = pattern.findall(
  119. str(ET.tostringlist(tree.getroot())))
  120. if len(obj_match) == 0:
  121. continue
  122. obj_tag = obj_match[0][1:-1]
  123. objs = tree.findall(obj_tag)
  124. pattern = re.compile('<size>', re.IGNORECASE)
  125. size_tag = pattern.findall(
  126. str(ET.tostringlist(tree.getroot())))[0][1:-1]
  127. size_element = tree.find(size_tag)
  128. pattern = re.compile('<width>', re.IGNORECASE)
  129. width_tag = pattern.findall(
  130. str(ET.tostringlist(size_element)))[0][1:-1]
  131. im_w = float(size_element.find(width_tag).text)
  132. pattern = re.compile('<height>', re.IGNORECASE)
  133. height_tag = pattern.findall(
  134. str(ET.tostringlist(size_element)))[0][1:-1]
  135. im_h = float(size_element.find(height_tag).text)
  136. gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
  137. gt_class = np.zeros((len(objs), 1), dtype=np.int32)
  138. gt_score = np.ones((len(objs), 1), dtype=np.float32)
  139. is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
  140. difficult = np.zeros((len(objs), 1), dtype=np.int32)
  141. for i, obj in enumerate(objs):
  142. pattern = re.compile('<name>', re.IGNORECASE)
  143. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  144. 1:-1]
  145. cname = obj.find(name_tag).text.strip()
  146. gt_class[i][0] = self.cname2cid[cname]
  147. pattern = re.compile('<difficult>', re.IGNORECASE)
  148. diff_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  149. 1:-1]
  150. try:
  151. _difficult = int(obj.find(diff_tag).text)
  152. except Exception:
  153. _difficult = 0
  154. pattern = re.compile('<bndbox>', re.IGNORECASE)
  155. box_tag = pattern.findall(str(ET.tostringlist(obj)))[0][1:
  156. -1]
  157. box_element = obj.find(box_tag)
  158. pattern = re.compile('<xmin>', re.IGNORECASE)
  159. xmin_tag = pattern.findall(
  160. str(ET.tostringlist(box_element)))[0][1:-1]
  161. x1 = float(box_element.find(xmin_tag).text)
  162. pattern = re.compile('<ymin>', re.IGNORECASE)
  163. ymin_tag = pattern.findall(
  164. str(ET.tostringlist(box_element)))[0][1:-1]
  165. y1 = float(box_element.find(ymin_tag).text)
  166. pattern = re.compile('<xmax>', re.IGNORECASE)
  167. xmax_tag = pattern.findall(
  168. str(ET.tostringlist(box_element)))[0][1:-1]
  169. x2 = float(box_element.find(xmax_tag).text)
  170. pattern = re.compile('<ymax>', re.IGNORECASE)
  171. ymax_tag = pattern.findall(
  172. str(ET.tostringlist(box_element)))[0][1:-1]
  173. y2 = float(box_element.find(ymax_tag).text)
  174. x1 = max(0, x1)
  175. y1 = max(0, y1)
  176. if im_w > 0.5 and im_h > 0.5:
  177. x2 = min(im_w - 1, x2)
  178. y2 = min(im_h - 1, y2)
  179. gt_bbox[i] = [x1, y1, x2, y2]
  180. is_crowd[i][0] = 0
  181. difficult[i][0] = _difficult
  182. annotations['annotations'].append({
  183. 'iscrowd': 0,
  184. 'image_id': int(im_id[0]),
  185. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  186. 'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
  187. 'category_id': self.cname2cid[cname],
  188. 'id': self.ann_ct,
  189. 'difficult': _difficult
  190. })
  191. self.ann_ct += 1
  192. im_info = {
  193. 'im_id': im_id,
  194. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  195. }
  196. label_info = {
  197. 'is_crowd': is_crowd,
  198. 'gt_class': gt_class,
  199. 'gt_bbox': gt_bbox,
  200. 'gt_score': gt_score,
  201. 'gt_poly': [],
  202. 'difficult': difficult
  203. }
  204. voc_rec = (im_info, label_info)
  205. if len(objs) != 0:
  206. self.file_list.append([img_file, voc_rec])
  207. ct += 1
  208. annotations['images'].append({
  209. 'height': im_h,
  210. 'width': im_w,
  211. 'id': int(im_id[0]),
  212. 'file_name': osp.split(img_file)[1]
  213. })
  214. if not len(self.file_list) > 0:
  215. raise Exception('not found any voc record in %s' % (file_list))
  216. logging.info("{} samples in file {}".format(
  217. len(self.file_list), file_list))
  218. self.num_samples = len(self.file_list)
  219. self.coco_gt = COCO()
  220. self.coco_gt.dataset = annotations
  221. self.coco_gt.createIndex()
  222. def add_negative_samples(self, image_dir):
  223. """将背景图片加入训练
  224. Args:
  225. image_dir (str):背景图片所在的文件夹目录。
  226. """
  227. import cv2
  228. if not osp.exists(image_dir):
  229. raise Exception("{} background images directory does not exist.".
  230. format(image_dir))
  231. image_list = os.listdir(image_dir)
  232. max_img_id = max(self.coco_gt.getImgIds())
  233. for image in image_list:
  234. if not is_pic(image):
  235. continue
  236. # False ground truth
  237. gt_bbox = np.array([[0, 0, 1e-05, 1e-05]], dtype=np.float32)
  238. gt_class = np.array([[0]], dtype=np.int32)
  239. gt_score = np.ones((1, 1), dtype=np.float32)
  240. is_crowd = np.array([[0]], dtype=np.int32)
  241. difficult = np.zeros((1, 1), dtype=np.int32)
  242. gt_poly = [[[0, 0, 0, 1e-05, 1e-05, 1e-05, 1e-05, 0]]]
  243. max_img_id += 1
  244. im_fname = osp.join(image_dir, image)
  245. img_data = cv2.imread(im_fname, cv2.IMREAD_UNCHANGED)
  246. im_h, im_w, im_c = img_data.shape
  247. im_info = {
  248. 'im_id': np.array([max_img_id]).astype('int32'),
  249. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  250. }
  251. label_info = {
  252. 'is_crowd': is_crowd,
  253. 'gt_class': gt_class,
  254. 'gt_bbox': gt_bbox,
  255. 'gt_score': gt_score,
  256. 'difficult': difficult,
  257. 'gt_poly': gt_poly
  258. }
  259. coco_rec = (im_info, label_info)
  260. self.file_list.append([im_fname, coco_rec])
  261. self.num_samples = len(self.file_list)
  262. def generate_image(self, templates, background, save_dir='dataset_clone'):
  263. """将目标物体粘贴在背景图片上生成新的图片,并加入到数据集中
  264. Args:
  265. templates (list|tuple):可以将多张图像上的目标物体同时粘贴在同一个背景图片上,
  266. 因此templates是一个列表,其中每个元素是一个dict,表示一张图片的目标物体。
  267. 一张图片的目标物体有`image`和`annos`两个关键字,`image`的键值是图像的路径,
  268. 或者是解码后的排列格式为(H, W, C)且类型为uint8且为BGR格式的数组。
  269. 图像上可以有多个目标物体,因此`annos`的键值是一个列表,列表中每个元素是一个dict,
  270. 表示一个目标物体的信息。该dict包含`polygon`和`category`两个关键字,
  271. 其中`polygon`表示目标物体的边缘坐标,例如[[0, 0], [0, 1], [1, 1], [1, 0]],
  272. `category`表示目标物体的类别,例如'dog'。
  273. background (dict): 背景图片可以有真值,因此background是一个dict,包含`image`和`annos`
  274. 两个关键字,`image`的键值是背景图像的路径,或者是解码后的排列格式为(H, W, C)
  275. 且类型为uint8且为BGR格式的数组。若背景图片上没有真值,则`annos`的键值是空列表[],
  276. 若有,则`annos`的键值是由多个dict组成的列表,每个dict表示一个物体的信息,
  277. 包含`bbox`和`category`两个关键字,`bbox`的键值是物体框左上角和右下角的坐标,即
  278. [x1, y1, x2, y2],`category`表示目标物体的类别,例如'dog'。
  279. save_dir (str):新图片及其标注文件的存储目录。默认值为`dataset_clone`。
  280. """
  281. if not osp.exists(save_dir):
  282. os.makedirs(save_dir)
  283. image_dir = osp.join(save_dir, 'JPEGImages_clone')
  284. anno_dir = osp.join(save_dir, 'Annotations_clone')
  285. json_path = osp.join(save_dir, "annotations.json")
  286. logging.info("Gegerated images will be saved in {}".format(image_dir))
  287. logging.info(
  288. "Annotation of generated images will be saved as xml files in {}".
  289. format(anno_dir))
  290. logging.info(
  291. "Annotation of images (loaded before and generated now) will be saved as a COCO json file {}".
  292. format(json_path))
  293. if not osp.exists(image_dir):
  294. os.makedirs(image_dir)
  295. if not osp.exists(anno_dir):
  296. os.makedirs(anno_dir)
  297. num_objs = len(background['annos'])
  298. for temp in templates:
  299. num_objs += len(temp['annos'])
  300. gt_bbox = np.zeros((num_objs, 4), dtype=np.float32)
  301. gt_class = np.zeros((num_objs, 1), dtype=np.int32)
  302. gt_score = np.ones((num_objs, 1), dtype=np.float32)
  303. is_crowd = np.zeros((num_objs, 1), dtype=np.int32)
  304. difficult = np.zeros((num_objs, 1), dtype=np.int32)
  305. i = -1
  306. for i, back_anno in enumerate(background['annos']):
  307. gt_bbox[i] = back_anno['bbox']
  308. gt_class[i][0] = self.cname2cid[back_anno['category']]
  309. max_img_id = max(self.coco_gt.getImgIds())
  310. max_img_id += 1
  311. back_im = background['image']
  312. if isinstance(back_im, np.ndarray):
  313. if len(back_im.shape) != 3:
  314. raise Exception(
  315. "background image should be 3-dimensions, but now is {}-dimensions".
  316. format(len(back_im.shape)))
  317. else:
  318. try:
  319. back_im = cv2.imread(back_im, cv2.IMREAD_UNCHANGED)
  320. except:
  321. raise TypeError('Can\'t read The image file {}!'.format(
  322. back_im))
  323. back_annos = background['annos']
  324. im_h, im_w, im_c = back_im.shape
  325. for temp in templates:
  326. temp_im = temp['image']
  327. if isinstance(temp_im, np.ndarray):
  328. if len(temp_im.shape) != 3:
  329. raise Exception(
  330. "template image should be 3-dimensions, but now is {}-dimensions".
  331. format(len(temp_im.shape)))
  332. else:
  333. try:
  334. temp_im = cv2.imread(temp_im, cv2.IMREAD_UNCHANGED)
  335. except:
  336. raise TypeError('Can\'t read The image file {}!'.format(
  337. temp_im))
  338. temp_annos = temp['annos']
  339. for temp_anno in temp_annos:
  340. temp_mask = np.zeros(temp_im.shape, temp_im.dtype)
  341. temp_poly = np.array(temp_anno['polygon'], np.int32)
  342. temp_category = temp_anno['category']
  343. cv2.fillPoly(temp_mask, [temp_poly], (255, 255, 255))
  344. x_list = [temp_poly[i][0] for i in range(len(temp_poly))]
  345. y_list = [temp_poly[i][1] for i in range(len(temp_poly))]
  346. temp_poly_w = max(x_list) - min(x_list)
  347. temp_poly_h = max(y_list) - min(y_list)
  348. found = False
  349. while not found:
  350. center_x = random.randint(1, im_w - 1)
  351. center_y = random.randint(1, im_h - 1)
  352. if center_x < temp_poly_w / 2 or center_x > im_w - temp_poly_w / 2 - 1 or \
  353. center_y < temp_poly_h / 2 or center_y > im_h - temp_poly_h / 2 - 1:
  354. found = False
  355. continue
  356. if len(back_annos) == 0:
  357. found = True
  358. for back_anno in back_annos:
  359. x1, y1, x2, y2 = back_anno['bbox']
  360. category = back_anno['category']
  361. if center_x > x1 and center_x < x2 and center_y > y1 and center_y < y2:
  362. found = False
  363. continue
  364. found = True
  365. center = (center_x, center_y)
  366. back_im = cv2.seamlessClone(temp_im, back_im, temp_mask,
  367. center, cv2.MIXED_CLONE)
  368. i += 1
  369. x1 = center[0] - temp_poly_w / 2
  370. x2 = center[0] + temp_poly_w / 2
  371. y1 = center[1] - temp_poly_h / 2
  372. y2 = center[1] + temp_poly_h / 2
  373. gt_bbox[i] = [x1, y1, x2, y2]
  374. gt_class[i][0] = self.cname2cid[temp_category]
  375. self.ann_ct += 1
  376. self.coco_gt.dataset['annotations'].append({
  377. 'iscrowd': 0,
  378. 'image_id': max_img_id,
  379. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  380. 'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
  381. 'category_id': self.cname2cid[temp_category],
  382. 'id': self.ann_ct,
  383. 'difficult': 0,
  384. })
  385. im_info = {
  386. 'im_id': np.array([max_img_id]).astype('int32'),
  387. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  388. }
  389. label_info = {
  390. 'is_crowd': is_crowd,
  391. 'gt_class': gt_class,
  392. 'gt_bbox': gt_bbox,
  393. 'gt_score': gt_score,
  394. 'difficult': difficult,
  395. 'gt_poly': [],
  396. }
  397. self.coco_gt.dataset['images'].append({
  398. 'height': im_h,
  399. 'width': im_w,
  400. 'id': max_img_id,
  401. 'file_name': "clone_{:06d}.jpg".format(max_img_id)
  402. })
  403. coco_rec = (im_info, label_info)
  404. im_fname = osp.join(image_dir, "clone_{:06d}.jpg".format(max_img_id))
  405. cv2.imwrite(im_fname, back_im.astype('uint8'))
  406. self._write_xml(im_fname, im_h, im_w, im_c, label_info, anno_dir)
  407. self.file_list.append([im_fname, coco_rec])
  408. self.num_samples = len(self.file_list)
  409. self._write_json(self.coco_gt.dataset, save_dir)
  410. def iterator(self):
  411. self._epoch += 1
  412. self._pos = 0
  413. files = copy.deepcopy(self.file_list)
  414. if self.shuffle:
  415. random.shuffle(files)
  416. files = files[:self.num_samples]
  417. self.num_samples = len(files)
  418. for f in files:
  419. records = f[1]
  420. im_info = copy.deepcopy(records[0])
  421. label_info = copy.deepcopy(records[1])
  422. im_info['epoch'] = self._epoch
  423. if self.num_samples > 1:
  424. mix_idx = random.randint(1, self.num_samples - 1)
  425. mix_pos = (mix_idx + self._pos) % self.num_samples
  426. else:
  427. mix_pos = 0
  428. im_info['mixup'] = [
  429. files[mix_pos][0], copy.deepcopy(files[mix_pos][1][0]),
  430. copy.deepcopy(files[mix_pos][1][1])
  431. ]
  432. self._pos += 1
  433. sample = [f[0], im_info, label_info]
  434. yield sample
  435. def _write_xml(self, im_fname, im_h, im_w, im_c, label_info, anno_dir):
  436. is_crowd = label_info['is_crowd']
  437. gt_class = label_info['gt_class']
  438. gt_bbox = label_info['gt_bbox']
  439. gt_score = label_info['gt_score']
  440. gt_poly = label_info['gt_poly']
  441. difficult = label_info['difficult']
  442. import xml.dom.minidom as minidom
  443. xml_doc = minidom.Document()
  444. root = xml_doc.createElement("annotation")
  445. xml_doc.appendChild(root)
  446. node_filename = xml_doc.createElement("filename")
  447. node_filename.appendChild(xml_doc.createTextNode(im_fname))
  448. root.appendChild(node_filename)
  449. node_size = xml_doc.createElement("size")
  450. node_width = xml_doc.createElement("width")
  451. node_width.appendChild(xml_doc.createTextNode(str(im_w)))
  452. node_size.appendChild(node_width)
  453. node_height = xml_doc.createElement("height")
  454. node_height.appendChild(xml_doc.createTextNode(str(im_h)))
  455. node_size.appendChild(node_height)
  456. node_depth = xml_doc.createElement("depth")
  457. node_depth.appendChild(xml_doc.createTextNode(str(im_c)))
  458. node_size.appendChild(node_depth)
  459. root.appendChild(node_size)
  460. for i in range(label_info['gt_class'].shape[0]):
  461. node_obj = xml_doc.createElement("object")
  462. node_name = xml_doc.createElement("name")
  463. label = self.cid2cname[gt_class[i][0]]
  464. node_name.appendChild(xml_doc.createTextNode(label))
  465. node_obj.appendChild(node_name)
  466. node_diff = xml_doc.createElement("difficult")
  467. node_diff.appendChild(xml_doc.createTextNode(str(difficult[i][0])))
  468. node_obj.appendChild(node_diff)
  469. node_box = xml_doc.createElement("bndbox")
  470. node_xmin = xml_doc.createElement("xmin")
  471. node_xmin.appendChild(xml_doc.createTextNode(str(gt_bbox[i][0])))
  472. node_box.appendChild(node_xmin)
  473. node_ymin = xml_doc.createElement("ymin")
  474. node_ymin.appendChild(xml_doc.createTextNode(str(gt_bbox[i][1])))
  475. node_box.appendChild(node_ymin)
  476. node_xmax = xml_doc.createElement("xmax")
  477. node_xmax.appendChild(xml_doc.createTextNode(str(gt_bbox[i][2])))
  478. node_box.appendChild(node_xmax)
  479. node_ymax = xml_doc.createElement("ymax")
  480. node_ymax.appendChild(xml_doc.createTextNode(str(gt_bbox[i][3])))
  481. node_box.appendChild(node_ymax)
  482. node_obj.appendChild(node_box)
  483. root.appendChild(node_obj)
  484. img_name_part = osp.split(im_fname)[-1].split('.')[0]
  485. with open(osp.join(anno_dir, img_name_part + ".xml"), 'w') as fxml:
  486. xml_doc.writexml(
  487. fxml, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
  488. def _write_json(self, coco_gt, save_dir):
  489. from paddlex.tools.base import MyEncoder
  490. json_path = osp.join(save_dir, "annotations.json")
  491. f = open(json_path, "w")
  492. json.dump(coco_gt, f, indent=4, cls=MyEncoder)
  493. f.close()