voc_label.py
Go to the documentation of this file.
00001 import xml.etree.ElementTree as ET
00002 import pickle
00003 import os
00004 from os import listdir, getcwd
00005 from os.path import join
00006 
00007 sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
00008 
00009 classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
00010 
00011 
00012 def convert(size, box):
00013     dw = 1./size[0]
00014     dh = 1./size[1]
00015     x = (box[0] + box[1])/2.0
00016     y = (box[2] + box[3])/2.0
00017     w = box[1] - box[0]
00018     h = box[3] - box[2]
00019     x = x*dw
00020     w = w*dw
00021     y = y*dh
00022     h = h*dh
00023     return (x,y,w,h)
00024 
00025 def convert_annotation(year, image_id):
00026     in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
00027     out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, image_id), 'w')
00028     tree=ET.parse(in_file)
00029     root = tree.getroot()
00030     size = root.find('size')
00031     w = int(size.find('width').text)
00032     h = int(size.find('height').text)
00033 
00034     for obj in root.iter('object'):
00035         difficult = obj.find('difficult').text
00036         cls = obj.find('name').text
00037         if cls not in classes or int(difficult) == 1:
00038             continue
00039         cls_id = classes.index(cls)
00040         xmlbox = obj.find('bndbox')
00041         b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
00042         bb = convert((w,h), b)
00043         out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
00044 
00045 wd = getcwd()
00046 
00047 for year, image_set in sets:
00048     if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
00049         os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
00050     image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
00051     list_file = open('%s_%s.txt'%(year, image_set), 'w')
00052     for image_id in image_ids:
00053         list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
00054         convert_annotation(year, image_id)
00055     list_file.close()
00056 


rail_object_detector
Author(s):
autogenerated on Sat Jun 8 2019 20:26:31