darknet  v3
voc_label.py
Go to the documentation of this file.
1 import xml.etree.ElementTree as ET
2 import pickle
3 import os
4 from os import listdir, getcwd
5 from os.path import join
6 
7 sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
8 
9 classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
10 
11 
12 def convert(size, box):
13  dw = 1./(size[0])
14  dh = 1./(size[1])
15  x = (box[0] + box[1])/2.0 - 1
16  y = (box[2] + box[3])/2.0 - 1
17  w = box[1] - box[0]
18  h = box[3] - box[2]
19  x = x*dw
20  w = w*dw
21  y = y*dh
22  h = h*dh
23  return (x,y,w,h)
24 
25 def convert_annotation(year, image_id):
26  in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
27  out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, image_id), 'w')
28  tree=ET.parse(in_file)
29  root = tree.getroot()
30  size = root.find('size')
31  w = int(size.find('width').text)
32  h = int(size.find('height').text)
33 
34  for obj in root.iter('object'):
35  difficult = obj.find('difficult').text
36  cls = obj.find('name').text
37  if cls not in classes or int(difficult)==1:
38  continue
39  cls_id = classes.index(cls)
40  xmlbox = obj.find('bndbox')
41  b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
42  bb = convert((w,h), b)
43  out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
44 
45 wd = getcwd()
46 
47 for year, image_set in sets:
48  if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
49  os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
50  image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
51  list_file = open('%s_%s.txt'%(year, image_set), 'w')
52  for image_id in image_ids:
53  list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
54  convert_annotation(year, image_id)
55  list_file.close()
56 
57 os.system("cat 2007_train.txt 2007_val.txt 2012_train.txt 2012_val.txt > train.txt")
58 os.system("cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt > train.all.txt")
59 
def convert(size, box)
Definition: voc_label.py:12
def convert_annotation(year, image_id)
Definition: voc_label.py:25
void strip(char *s)
Definition: utils.c:302