voc_label.py 2.2 KB

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