labelme2coco.py 4.6 KB

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