labelme2voc.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import argparse
  4. import glob
  5. import json
  6. import os
  7. import os.path as osp
  8. import sys
  9. try:
  10. import lxml.builder
  11. import lxml.etree
  12. except ImportError:
  13. print('Please install lxml:\n\n pip install lxml\n')
  14. sys.exit(1)
  15. import numpy as np
  16. import PIL.Image
  17. import labelme
  18. def main():
  19. parser = argparse.ArgumentParser(
  20. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  21. parser.add_argument('labels_file')
  22. parser.add_argument('in_dir', help='input dir with annotated files')
  23. parser.add_argument('out_dir', help='output dataset directory')
  24. args = parser.parse_args()
  25. if osp.exists(args.out_dir):
  26. print('Output directory already exists:', args.out_dir)
  27. quit(1)
  28. os.makedirs(args.out_dir)
  29. os.makedirs(osp.join(args.out_dir, 'JPEGImages'))
  30. os.makedirs(osp.join(args.out_dir, 'Annotations'))
  31. os.makedirs(osp.join(args.out_dir, 'AnnotationsVisualization'))
  32. print('Creating dataset:', args.out_dir)
  33. class_names = []
  34. class_name_to_id = {}
  35. for i, line in enumerate(open(args.labels_file).readlines()):
  36. class_id = i - 1 # starts with -1
  37. class_name = line.strip()
  38. class_name_to_id[class_name] = class_id
  39. if class_id == -1:
  40. assert class_name == '__ignore__'
  41. continue
  42. elif class_id == 0:
  43. assert class_name == '_background_'
  44. class_names.append(class_name)
  45. class_names = tuple(class_names)
  46. print('class_names:', class_names)
  47. out_class_names_file = osp.join(args.out_dir, 'class_names.txt')
  48. with open(out_class_names_file, 'w') as f:
  49. f.writelines('\n'.join(class_names))
  50. print('Saved class_names:', out_class_names_file)
  51. for label_file in glob.glob(osp.join(args.in_dir, '*.json')):
  52. print('Generating dataset from:', label_file)
  53. with open(label_file) as f:
  54. data = json.load(f)
  55. base = osp.splitext(osp.basename(label_file))[0]
  56. out_img_file = osp.join(
  57. args.out_dir, 'JPEGImages', base + '.jpg')
  58. out_xml_file = osp.join(
  59. args.out_dir, 'Annotations', base + '.xml')
  60. out_viz_file = osp.join(
  61. args.out_dir, 'AnnotationsVisualization', base + '.jpg')
  62. img_file = osp.join(osp.dirname(label_file), data['imagePath'])
  63. img = np.asarray(PIL.Image.open(img_file))
  64. PIL.Image.fromarray(img).save(out_img_file)
  65. maker = lxml.builder.ElementMaker()
  66. xml = maker.annotation(
  67. maker.folder(),
  68. maker.filename(base + '.jpg'),
  69. maker.database(), # e.g., The VOC2007 Database
  70. maker.annotation(), # e.g., Pascal VOC2007
  71. maker.image(), # e.g., flickr
  72. maker.size(
  73. maker.height(str(img.shape[0])),
  74. maker.width(str(img.shape[1])),
  75. maker.depth(str(img.shape[2])),
  76. ),
  77. maker.segmented(),
  78. )
  79. bboxes = []
  80. labels = []
  81. for shape in data['shapes']:
  82. if shape['shape_type'] != 'rectangle':
  83. print('Skipping shape: label={label}, shape_type={shape_type}'
  84. .format(**shape))
  85. continue
  86. class_name = shape['label']
  87. class_id = class_names.index(class_name)
  88. (xmin, ymin), (xmax, ymax) = shape['points']
  89. bboxes.append([xmin, ymin, xmax, ymax])
  90. labels.append(class_id)
  91. xml.append(
  92. maker.object(
  93. maker.name(shape['label']),
  94. maker.pose(),
  95. maker.truncated(),
  96. maker.difficult(),
  97. maker.bndbox(
  98. maker.xmin(str(xmin)),
  99. maker.ymin(str(ymin)),
  100. maker.xmax(str(xmax)),
  101. maker.ymax(str(ymax)),
  102. ),
  103. )
  104. )
  105. captions = [class_names[l] for l in labels]
  106. viz = labelme.utils.draw_instances(
  107. img, bboxes, labels, captions=captions
  108. )
  109. PIL.Image.fromarray(viz).save(out_viz_file)
  110. with open(out_xml_file, 'wb') as f:
  111. f.write(lxml.etree.tostring(xml, pretty_print=True))
  112. if __name__ == '__main__':
  113. main()