Skip to content

Instantly share code, notes, and snippets.

@osin-vladimir
Created May 4, 2017 07:33
Show Gist options
  • Save osin-vladimir/e36c626b81ac4d75ae21ba7496be064a to your computer and use it in GitHub Desktop.
Save osin-vladimir/e36c626b81ac4d75ae21ba7496be064a to your computer and use it in GitHub Desktop.
Annotations convertion to PASCAL VOC XML format
import os
import json
from pprint import pprint
def save_image_set_txt(path, index):
f = open(path, 'w')
for ind in index:
f.write(ind+'\n')
f.close()
converted_annotations = '../notebooks/annotations/'
train_img_names = []
with open('../../Downloads/rectangles.json') as data_file:
data = json.load(data_file)
for i in range(len(data)):
# get INDEX name for annotations (image filename without extension)
INDEX = data[i]['filename'][17:-4]
train_img_names.append(INDEX)
# add basic annotations info
f = open(converted_annotations + INDEX + '.xml','w')
line = "<annotation>" + '\n'
f.write(line)
line = '\t\t<folder>' + "folder" + '</folder>' + '\n'
f.write(line)
line = '\t\t<filename>' + INDEX + '</filename>' + '\n'
f.write(line)
line = '\t\t<source>\n\t\t<database>Source</database>\n\t</source>\n'
f.write(line)
# TODO: add proper image sizes
# (width, height) = image.shape[0], image.shape[1]
(width, height) = 500, 500
line = '\t<size>\n\t\t<width>'+ str(width) + '</width>\n\t\t<height>' + str(height) + '</height>\n\t'
line += '\t<depth>3</depth>\n\t</size>'
f.write(line)
line = '\n\t<segmented>Unspecified</segmented>'
f.write(line)
for annotation in data[i]['annotations']:
x=int(annotation['x'])
y=int(annotation['y'])
w=int(annotation['width'])
h=int(annotation['height'])
line = '\n\t<object>'
line += '\n\t\t<name>'+annotation['class']+'</name>\n\t\t<pose>Unspecified</pose>'
line += '\n\t\t<truncated>Unspecified</truncated>\n\t\t<difficult>0</difficult>'
line += '\n\t\t<bndbox>\n\t\t\t<xmin>' + str(x) + '</xmin>'
line += '\n\t\t\t<ymin>' + str(y) + '</ymin>'
line += '\n\t\t\t<xmax>' + str(x+w) + '</xmax>'
line += '\n\t\t\t<ymax>' + str(y+h) + '</ymax>'
line += '\n\t\t</bndbox>'
line += '\n\t</object>\n'
f.write(line)
line = "</annotation>" + '\n'
f.write(line)
f.close()
save_image_set_txt('train.txt', train_img_names)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment