This repository has been archived by the owner on Dec 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
convert_yolo_to_voc.py
286 lines (241 loc) · 10.2 KB
/
convert_yolo_to_voc.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Convert Yolo to Pascal VOC.
License_info:
# ==============================================================================
# ISC License (ISC)
# Copyright 2020 Christian Doppler Laboratory for Embedded Machine Learning
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
# ==============================================================================
# The following script uses several method fragments the following guide
# Source: https://gist.github.com/goodhamgupta/7ca514458d24af980669b8b1c8bcdafd
"""
# Futures
from __future__ import print_function
# Built-in/Generic Imports
import os
import re
import time
import json
import re
import ntpath
import warnings
# Libs
import argparse
import numpy as np
import glob
import xml.etree.ElementTree as ET
from multiprocessing import Pool
import matplotlib
from six import BytesIO
import pandas as pd
import tkinter
import argparse
import collections
import xmltodict
from PIL import Image
import numpy as np
import dicttoxml
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
from tqdm import tqdm
import shutil
import os
from xml.dom import minidom
import xml.etree.cElementTree as ET
from PIL import Image
# Own modules
__author__ = 'Julian Westra'
__copyright__ = 'Copyright 2020, Christian Doppler Laboratory for ' \
'Embedded Machine Learning'
__credits__ = ['Alexander Wendt', 'https://gist.github.com/goodhamgupta']
__license__ = 'ISC'
__version__ = '0.2.0'
__maintainer__ = 'Alexander Wendt'
__email__ = '[email protected]'
__status__ = 'Experiental'
parser = argparse.ArgumentParser(description='Convert Yolo to Pascal VOC')
parser.add_argument("-ad", '--annotation_dir',
default=None,
help='Annotation directory with txt files of yolo annotations of the same name format as image files',
required=False)
parser.add_argument("-id", '--image_dir',
default="images",
help='Image file directory', required=False)
parser.add_argument("-at", '--target_annotation_dir',
default="./annotations/xmls",
help='Target directory for xml files', required=False)
parser.add_argument("-cl", '--class_file',
default="./annotations/labels.txt",
help='File with class labels', required=False)
parser.add_argument("--create_empty_images", action='store_true', default=False,
help="Generates xmls also for images without any found objects, i.e. empty annotations. It is useful to prevent overfitting.")
args = parser.parse_args()
print(args)
# Script to convert yolo annotations to voc format
# Sample format
# <annotation>
# <folder>_image_fashion</folder>
# <filename>brooke-cagle-39574.jpg</filename>
# <size>
# <width>1200</width>
# <height>800</height>
# <depth>3</depth>
# </size>
# <segmented>0</segmented>
# <object>
# <name>head</name>
# <pose>Unspecified</pose>
# <truncated>0</truncated>
# <difficult>0</difficult>
# <bndbox>
# <xmin>549</xmin>
# <ymin>251</ymin>
# <xmax>625</xmax>
# <ymax>335</ymax>
# </bndbox>
# </object>
# <annotation>
# ANNOTATIONS_DIR_PREFIX = "path to your yolo annotations"
# DESTINATION_DIR = "output path"
# CLASS_MAPPING = {
# '1': 'Char'
# }
def formatter(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def create_root(file_prefix, width, height):
root = ET.Element("annotation")
ET.SubElement(root, "filename").text = "{}.jpg".format(file_prefix)
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):
#if len(voc_labels) == 0:
# obj = ET.SubElement(root, "object")
for voc_label in voc_labels:
obj = ET.SubElement(root, "object")
ET.SubElement(obj, "name").text = voc_label[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, target_annotation_dir):
root = create_root(file_prefix, width, height)
root = create_object_annotation(root, voc_labels)
with open("{}/{}.xml".format(target_annotation_dir, file_prefix), "w") as f:
f.write(formatter(root))
f.close()
def read_image_file(image_file_path, annotation_dir, target_annotation_dir, classes_dict, image_dir,
create_empty_images=True):
image_file_name = os.path.basename(image_file_path)
file_prefix = os.path.basename(image_file_path).split('.jpg')[0]
annotation_file_name = "{}.txt".format(file_prefix)
annotation_file_path = os.path.join(annotation_dir, annotation_file_name)
# file_prefix = file_path.split(".txt")[0]
# image_file_name = "{}.jpg".format(file_prefix)
# img = Image.open("{}/{}".format("sites", image_file_name))
img = Image.open(image_file_path)
w, h = img.size
if os.path.exists(annotation_file_path):
print("Convert annotation {}".format(annotation_file_path))
# with open(os.path.join(annotation_dir, )"labels/" + file_path, 'r') as file:
with open(os.path.join(annotation_file_path), 'r') as file:
lines = file.readlines()
voc_labels = []
for line in lines:
voc = []
line = line.strip()
data = line.split()
# voc.append(CLASS_MAPPING.get(data[0]))
voc.append(classes_dict.get(data[0]))
bbox_width = float(data[3]) * w
bbox_height = float(data[4]) * h
center_x = float(data[1]) * w
center_y = float(data[2]) * h
voc.append(round(center_x - (bbox_width / 2)))
voc.append(round(center_y - (bbox_height / 2)))
voc.append(round(center_x + (bbox_width / 2)))
voc.append(round(center_y + (bbox_height / 2)))
voc_labels.append(voc)
create_file(file_prefix, w, h, voc_labels, target_annotation_dir)
elif create_empty_images:
print("Annotation does not exist {}. Create empty annotation".format(annotation_file_path))
voc_labels = []
create_file(file_prefix, w, h, voc_labels, target_annotation_dir)
else:
print("Annotation does not exist {}. Do nothing".format(annotation_file_path))
def read_file(file_path, annotation_dir, target_annotation_dir, classes_dict, image_dir):
file_prefix = file_path.split(".txt")[0]
image_file_name = "{}.jpg".format(file_prefix)
# img = Image.open("{}/{}".format("sites", image_file_name))
if os.path.exists(os.path.join(image_dir, image_file_name)):
img = Image.open(os.path.join(image_dir, image_file_name))
w, h = img.size
# with open(os.path.join(annotation_dir, )"labels/" + file_path, 'r') as file:
with open(os.path.join(annotation_dir, file_path), 'r') as file:
lines = file.readlines()
voc_labels = []
for line in lines:
voc = []
line = line.strip()
data = line.split()
# voc.append(CLASS_MAPPING.get(data[0]))
voc.append(classes_dict.get(data[0]))
bbox_width = float(data[3]) * w
bbox_height = float(data[4]) * h
center_x = float(data[1]) * w
center_y = float(data[2]) * h
voc.append(round(center_x - (bbox_width / 2)))
voc.append(round(center_y - (bbox_height / 2)))
voc.append(round(center_x + (bbox_width / 2)))
voc.append(round(center_y + (bbox_height / 2)))
voc_labels.append(voc)
create_file(file_prefix, w, h, voc_labels, target_annotation_dir)
else:
warnings.warn("Image does not exist {}".format(os.path.join(image_dir, image_file_name)))
def load_classes(class_file):
d = {}
i = 0
with open(class_file) as f:
for line in f:
d[str(i)] = line.strip()
i = i + 1
return d
def start(annotation_dir, target_annotation_dir, class_file, image_dir, create_empty_images=True):
os.makedirs(target_annotation_dir, exist_ok=True)
# Load class file to list
classes_dict = load_classes(class_file)
print("Loaded classes", classes_dict)
print("Processing jpg files in the image folder ", image_dir)
for image_path in glob.glob(image_dir + '/*.jpg'):
print("Process image", image_path)
read_image_file(image_path, annotation_dir, target_annotation_dir, classes_dict, image_dir, create_empty_images)
# for filename in os.listdir(annotation_dir):
# if filename.endswith('txt'):
# print(filename)
# read_file(filename, annotation_dir, target_annotation_dir, classes_dict, image_dir)
# else:
# print("Skipping file: {}".format(filename))
if __name__ == "__main__":
start(args.annotation_dir, args.target_annotation_dir, args.class_file, args.image_dir, args.create_empty_images)
print("=== Program end ===")