labelme2coco.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/env python
  2. import argparse
  3. import datetime
  4. import glob
  5. import json
  6. import os
  7. import os.path as osp
  8. import sys
  9. import numpy as np
  10. import PIL.Image
  11. import labelme
  12. try:
  13. import pycocotools.mask
  14. except ImportError:
  15. print('Please install pycocotools:\n\n pip install pycocotools\n')
  16. sys.exit(1)
  17. def main():
  18. parser = argparse.ArgumentParser(
  19. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  20. )
  21. parser.add_argument('input_dir', help='input annotated directory')
  22. parser.add_argument('output_dir', help='output dataset directory')
  23. parser.add_argument('--labels', help='labels file')
  24. args = parser.parse_args()
  25. if osp.exists(args.output_dir):
  26. print('Output directory already exists:', args.output_dir)
  27. sys.exit(1)
  28. os.makedirs(args.output_dir)
  29. os.makedirs(osp.join(args.output_dir, 'JPEGImages'))
  30. print('Creating dataset:', args.output_dir)
  31. now = datetime.datetime.now()
  32. data = dict(
  33. info=dict(
  34. description=None,
  35. url=None,
  36. version=None,
  37. year=now.year,
  38. contributor=None,
  39. date_created=now.strftime('%Y-%m-%d %H:%M:%S.%f'),
  40. ),
  41. licenses=[dict(
  42. url=None,
  43. id=0,
  44. name=None,
  45. )],
  46. images=[
  47. # license, url, file_name, height, width, date_captured, id
  48. ],
  49. type='instances',
  50. annotations=[
  51. # segmentation, area, iscrowd, image_id, bbox, category_id, id
  52. ],
  53. categories=[
  54. # supercategory, id, name
  55. ],
  56. )
  57. class_name_to_id = {}
  58. for i, line in enumerate(open(args.labels).readlines()):
  59. class_id = i - 1 # starts with -1
  60. class_name = line.strip()
  61. if class_id == -1:
  62. assert class_name == '__ignore__'
  63. continue
  64. elif class_id == 0:
  65. assert class_name == '_background_'
  66. class_name_to_id[class_name] = class_id
  67. data['categories'].append(dict(
  68. supercategory=None,
  69. id=class_id,
  70. name=class_name,
  71. ))
  72. out_ann_file = osp.join(args.output_dir, 'annotations.json')
  73. label_files = glob.glob(osp.join(args.input_dir, '*.json'))
  74. for image_id, label_file in enumerate(label_files):
  75. print('Generating dataset from:', label_file)
  76. with open(label_file) as f:
  77. label_data = json.load(f)
  78. base = osp.splitext(osp.basename(label_file))[0]
  79. out_img_file = osp.join(
  80. args.output_dir, 'JPEGImages', base + '.jpg'
  81. )
  82. img_file = osp.join(
  83. osp.dirname(label_file), label_data['imagePath']
  84. )
  85. img = np.asarray(PIL.Image.open(img_file))
  86. PIL.Image.fromarray(img).save(out_img_file)
  87. data['images'].append(dict(
  88. license=0,
  89. url=None,
  90. file_name=osp.relpath(out_img_file, osp.dirname(out_ann_file)),
  91. height=img.shape[0],
  92. width=img.shape[1],
  93. date_captured=None,
  94. id=image_id,
  95. ))
  96. masks = {}
  97. for shape in label_data['shapes']:
  98. points = shape['points']
  99. label = shape['label']
  100. shape_type = shape.get('shape_type', None)
  101. mask = labelme.utils.shape_to_mask(
  102. img.shape[:2], points, shape_type
  103. )
  104. mask = np.asfortranarray(mask.astype(np.uint8))
  105. if label in masks:
  106. masks[label] = masks[label] | mask
  107. else:
  108. masks[label] = mask
  109. for label, mask in masks.items():
  110. cls_name = label.split('-')[0]
  111. if cls_name not in class_name_to_id:
  112. continue
  113. cls_id = class_name_to_id[cls_name]
  114. segmentation = pycocotools.mask.encode(mask)
  115. segmentation['counts'] = segmentation['counts'].decode()
  116. area = float(pycocotools.mask.area(segmentation))
  117. data['annotations'].append(dict(
  118. segmentation=segmentation,
  119. area=area,
  120. iscrowd=None,
  121. image_id=image_id,
  122. category_id=cls_id,
  123. ))
  124. with open(out_ann_file, 'w') as f:
  125. json.dump(data, f)
  126. if __name__ == '__main__':
  127. main()