-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertToVOC.py
More file actions
79 lines (66 loc) · 2.67 KB
/
ConvertToVOC.py
File metadata and controls
79 lines (66 loc) · 2.67 KB
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
76
77
78
79
import os
import xml.etree.cElementTree as ET
from PIL import Image
import StaticMethods as sm
ANNOTATIONS_DIR_PREFIX = "converted_annotation_in_txt\\"
AUGMENTED_XML_DATA_PATH = "AugmentedXML"
sm.createFolder(AUGMENTED_XML_DATA_PATH)
def create_root(file_prefix, width, height):
root = ET.Element("annotations")
ET.SubElement(root, "filename").text = "{}.jpg".format(file_prefix)
ET.SubElement(root, "folder").text = "images"
size = ET.SubElement(root, "size")
ET.SubElement(size, "width").text = str(width)
ET.SubElement(size, "height").text = str(height)
ET.SubElement(size, "depth").text = "3"
return root
def create_object_annotation(root, voc_labels):
for voc_label in voc_labels:
obj = ET.SubElement(root, "object")
ET.SubElement(obj, "name").text = voc_label[0]
ET.SubElement(obj, "pose").text = "Unspecified"
ET.SubElement(obj, "truncated").text = str(0)
ET.SubElement(obj, "difficult").text = str(0)
bbox = ET.SubElement(obj, "bndbox")
ET.SubElement(bbox, "xmin").text = str(voc_label[1])
ET.SubElement(bbox, "ymin").text = str(voc_label[2])
ET.SubElement(bbox, "xmax").text = str(voc_label[3])
ET.SubElement(bbox, "ymax").text = str(voc_label[4])
return root
def create_file(file_prefix, width, height, voc_labels):
root = create_root(file_prefix, width, height)
root = create_object_annotation(root, voc_labels)
tree = ET.ElementTree(root)
tree.write("AugmentedXML\\{}.xml".format(file_prefix))
def read_file(file_path):
file_prefix = file_path.split(".jpg")[0]
file_path_data = "converted_annotation_in_txt\\" + file_path
print("the file path data", file_path_data)
image_file_name = "{}.jpg".format(file_prefix)
img = Image.open("{}/{}".format("AugmentedImages", image_file_name))
w, h = img.size
with open(file_path_data, 'r') as file:
lines = file.readlines()
voc_labels = []
for line in lines:
voc = []
line = line.strip()
data = line.split()
print(data[0], data[1], data[2], data[3], data[4])
voc.append(data[0])
voc.append(data[1])
voc.append(data[2])
voc.append(data[3])
voc.append(data[4])
voc_labels.append(voc)
print(voc_labels)
create_file(file_prefix, w, h, voc_labels)
print("Processing complete for file: {}".format(file_path))
def start():
for filename in os.listdir(ANNOTATIONS_DIR_PREFIX):
print(filename)
if filename.endswith('txt'):
read_file(filename)
else:
print("Skipping file: {}".format(filename))
start()