-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathxml2yolo.py
75 lines (61 loc) · 2.46 KB
/
xml2yolo.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import xml.etree.ElementTree as ET
import glob
import os
import json
def xml_to_yolo_bbox(bbox, w, h):
# xmin, ymin, xmax, ymax
x_center = ((bbox[2] + bbox[0]) / 2) / w
y_center = ((bbox[3] + bbox[1]) / 2) / h
width = (bbox[2] - bbox[0]) / w
height = (bbox[3] - bbox[1]) / h
return [x_center, y_center, width, height]
def yolo_to_xml_bbox(bbox, w, h):
# x_center, y_center width heigth
w_half_len = (bbox[2] * w) / 2
h_half_len = (bbox[3] * h) / 2
xmin = int((bbox[0] * w) - w_half_len)
ymin = int((bbox[1] * h) - h_half_len)
xmax = int((bbox[0] * w) + w_half_len)
ymax = int((bbox[1] * h) + h_half_len)
return [xmin, ymin, xmax, ymax]
classes = []
input_dir = "/home/amin/persian_licenceplate_generator/output/00/anns/xmls"
output_dir = "/home/amin/persian_licenceplate_generator/output/00/yolo"
image_dir = "/home/amin/persian_licenceplate_generator/output/00/anns"
# create the labels folder (output directory)
os.rmdir(output_dir)
os.mkdir(output_dir)
# identify all the xml files in the annotations folder (input directory)
files = glob.glob(os.path.join(input_dir, '*.xml'))
# loop through each
for fil in files:
basename = os.path.basename(fil)
filename = os.path.splitext(basename)[0]
# check if the label contains the corresponding image file
if not os.path.exists(os.path.join(image_dir, f"{filename}.png")):
print(f"{filename} image does not exist!")
continue
result = []
# parse the content of the xml file
tree = ET.parse(fil)
root = tree.getroot()
width = int(root.find("size").find("width").text)
height = int(root.find("size").find("height").text)
for obj in root.findall('object'):
label = obj.find("name").text
# check for new classes and append to list
if label not in classes:
classes.append(label)
index = classes.index(label)
pil_bbox = [int(x.text) for x in obj.find("bndbox")]
yolo_bbox = xml_to_yolo_bbox(pil_bbox, width, height)
# convert data to string
bbox_string = " ".join([str(x) for x in yolo_bbox])
result.append(f"{index} {bbox_string}")
if result:
# generate a YOLO format text file for each xml file
with open(os.path.join(output_dir, f"{filename}.txt"), "w", encoding="utf-8") as f:
f.write("\n".join(result))
# generate the classes file as reference
with open('classes.txt', 'w', encoding='utf8') as f:
f.write(json.dumps(classes))