-
Notifications
You must be signed in to change notification settings - Fork 2
/
XML_to_YOLOv3.py
56 lines (48 loc) · 1.99 KB
/
XML_to_YOLOv3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import xml.etree.ElementTree as ET
import os
import glob
foldername = os.path.basename(os.getcwd())
if foldername == "tools": os.chdir("..")
data_dir = '/custom_dataset/'
Dataset_names_path = "model_data/license_plate_names.txt"
Dataset_train = "model_data/license_plate_train.txt"
Dataset_test = "model_data/license_plate_test.txt"
is_subfolder = False
Dataset_names = []
def ParseXML(img_folder, file):
for xml_file in glob.glob(img_folder+'/*.xml'):
tree=ET.parse(open(xml_file))
root = tree.getroot()
image_name = root.find('filename').text
img_path = img_folder+'/'+image_name
for i, obj in enumerate(root.iter('object')):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in Dataset_names:
Dataset_names.append(cls)
cls_id = Dataset_names.index(cls)
xmlbox = obj.find('bndbox')
OBJECT = (str(int(float(xmlbox.find('xmin').text)))+','
+str(int(float(xmlbox.find('ymin').text)))+','
+str(int(float(xmlbox.find('xmax').text)))+','
+str(int(float(xmlbox.find('ymax').text)))+','
+str(cls_id))
img_path += ' '+OBJECT
print(img_path)
file.write(img_path+'\n')
def run_XML_to_YOLOv3():
for i, folder in enumerate(['train','test']):
with open([Dataset_train,Dataset_test][i], "w") as file:
print(os.getcwd()+data_dir+folder)
img_path = os.path.join(os.getcwd()+data_dir+folder)
if is_subfolder:
for directory in os.listdir(img_path):
xml_path = os.path.join(img_path, directory)
ParseXML(xml_path, file)
else:
ParseXML(img_path, file)
print("Dataset_names:", Dataset_names)
with open(Dataset_names_path, "w") as file:
for name in Dataset_names:
file.write(str(name)+'\n')
run_XML_to_YOLOv3()