xml2txt.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import xml.etree.ElementTree as ET
  2. import os, cv2
  3. import numpy as np
  4. from os import listdir
  5. from os.path import join
  6. classes = []
  7. def convert(size, box):
  8. dw = 1. / (size[0])
  9. dh = 1. / (size[1])
  10. x = (box[0] + box[1]) / 2.0 - 1
  11. y = (box[2] + box[3]) / 2.0 - 1
  12. w = box[1] - box[0]
  13. h = box[3] - box[2]
  14. x = x * dw
  15. w = w * dw
  16. y = y * dh
  17. h = h * dh
  18. return (x, y, w, h)
  19. def convert_annotation(xmlpath, xmlname):
  20. with open(xmlpath, "r", encoding='utf-8') as in_file:
  21. txtname = xmlname[:-4] + '.txt'
  22. txtfile = os.path.join(txtpath, txtname)
  23. tree = ET.parse(in_file)
  24. root = tree.getroot()
  25. filename = root.find('filename')
  26. img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
  27. h, w = img.shape[:2]
  28. res = []
  29. for obj in root.iter('object'):
  30. cls = obj.find('name').text
  31. if cls not in classes:
  32. classes.append(cls)
  33. cls_id = classes.index(cls)
  34. xmlbox = obj.find('bndbox')
  35. b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  36. float(xmlbox.find('ymax').text))
  37. bb = convert((w, h), b)
  38. res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
  39. if len(res) != 0:
  40. with open(txtfile, 'w+') as f:
  41. f.write('\n'.join(res))
  42. if __name__ == "__main__":
  43. postfix = 'jpg'
  44. imgpath = 'VOCdevkit/JPEGImages'
  45. xmlpath = 'VOCdevkit/Annotations'
  46. txtpath = 'VOCdevkit/txt'
  47. if not os.path.exists(txtpath):
  48. os.makedirs(txtpath, exist_ok=True)
  49. list = os.listdir(xmlpath)
  50. error_file_list = []
  51. for i in range(0, len(list)):
  52. try:
  53. path = os.path.join(xmlpath, list[i])
  54. if ('.xml' in path) or ('.XML' in path):
  55. convert_annotation(path, list[i])
  56. print(f'file {list[i]} convert success.')
  57. else:
  58. print(f'file {list[i]} is not xml format.')
  59. except Exception as e:
  60. print(f'file {list[i]} convert error.')
  61. print(f'error message:\n{e}')
  62. error_file_list.append(list[i])
  63. print(f'this file convert failure\n{error_file_list}')
  64. print(f'Dataset Classes:{classes}')