Last active
February 12, 2018 00:24
-
-
Save saikatbsk/b3bbbee20d75a91b361c01901090127f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Convert to darknet annotation format from pascal voc | |
# [email protected] | |
from __future__ import print_function | |
import xml.etree.ElementTree as ET | |
import os | |
import glob | |
""" | |
Change classes and annotations_dir_voc to match your setup. | |
""" | |
classes = ["class1", "class2"] | |
annotations_dir_voc = "../annotations_xml" | |
def convert(size, box): | |
dw = 1./size[0] | |
dh = 1./size[1] | |
x = (box[0] + box[1])/2.0 | |
y = (box[2] + box[3])/2.0 | |
w = box[1] - box[0] | |
h = box[3] - box[2] | |
x = x*dw | |
w = w*dw | |
y = y*dh | |
h = h*dh | |
return (x,y,w,h) | |
annotations_dir_darknet = os.path.join(os.path.dirname(os.path.abspath(annotations_dir_voc)), "annotations_darknet") | |
if not os.path.exists(annotations_dir_darknet): | |
os.makedirs(annotations_dir_darknet) | |
in_files = glob.glob(os.path.join(annotations_dir_voc, "*.xml")) | |
for in_file in in_files: | |
tree=ET.parse(in_file) | |
root = tree.getroot() | |
size = root.find('size') | |
w = int(size.find('width').text) | |
h = int(size.find('height').text) | |
for obj in root.iter('object'): | |
difficult = obj.find('difficult').text | |
cls = obj.find('name').text | |
if cls not in classes or int(difficult) == 1: | |
continue | |
cls_id = classes.index(cls) | |
xmlbox = obj.find('bndbox') | |
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)) | |
bb = convert((w,h), b) | |
out_file = open(os.path.join(annotations_dir_darknet, str(os.path.splitext(os.path.basename(in_file))[0]+".txt")), "a+") | |
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment