labelme2voc.py 4.3 KB

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