oliverlibaw commited on
Commit
5fc0b25
1 Parent(s): 79efff5

Create xml_to_txt.py

Browse files
Files changed (1) hide show
  1. xml_to_txt.py +42 -0
xml_to_txt.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import xml.etree.ElementTree as ET
2
+ import os
3
+ from glob import glob
4
+
5
+ XML_PATH = './dataset/xml'
6
+ CLASSES_PATH = './class_names/classes.txt'
7
+ TXT_PATH = './dataset/txt/anno.txt'
8
+
9
+
10
+ '''loads the classes'''
11
+ def get_classes(classes_path):
12
+ with open(classes_path) as f:
13
+ class_names = f.readlines()
14
+ class_names = [c.strip() for c in class_names]
15
+ return class_names
16
+
17
+
18
+ classes = get_classes(CLASSES_PATH)
19
+ assert len(classes) > 0, 'no class names detected!'
20
+ print(f'num classes: {len(classes)}')
21
+
22
+ # output file
23
+ list_file = open(TXT_PATH, 'w')
24
+
25
+ for path in glob(os.path.join(XML_PATH, '*.xml')):
26
+ in_file = open(path)
27
+
28
+ # Parse .xml file
29
+ tree = ET.parse(in_file)
30
+ root = tree.getroot()
31
+ # Write object information to .txt file
32
+ file_name = root.find('filename').text
33
+ print(file_name)
34
+ list_file.write(file_name)
35
+ for obj in root.iter('object'):
36
+ cls = obj.find('name').text
37
+ cls_id = classes.index(cls)
38
+ xmlbox = obj.find('bndbox')
39
+ b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
40
+ list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
41
+ list_file.write('\n')
42
+ list_file.close()