labelme2coco.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 imgviz
  12. import numpy as np
  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. parser.add_argument(
  27. "--noviz", help="no visualization", action="store_true"
  28. )
  29. args = parser.parse_args()
  30. if osp.exists(args.output_dir):
  31. print("Output directory already exists:", args.output_dir)
  32. sys.exit(1)
  33. os.makedirs(args.output_dir)
  34. os.makedirs(osp.join(args.output_dir, "JPEGImages"))
  35. if not args.noviz:
  36. os.makedirs(osp.join(args.output_dir, "Visualization"))
  37. print("Creating dataset:", args.output_dir)
  38. now = datetime.datetime.now()
  39. data = dict(
  40. info=dict(
  41. description=None,
  42. url=None,
  43. version=None,
  44. year=now.year,
  45. contributor=None,
  46. date_created=now.strftime("%Y-%m-%d %H:%M:%S.%f"),
  47. ),
  48. licenses=[dict(url=None, id=0, name=None,)],
  49. images=[
  50. # license, url, file_name, height, width, date_captured, id
  51. ],
  52. type="instances",
  53. annotations=[
  54. # segmentation, area, iscrowd, image_id, bbox, category_id, id
  55. ],
  56. categories=[
  57. # supercategory, id, name
  58. ],
  59. )
  60. class_name_to_id = {}
  61. for i, line in enumerate(open(args.labels).readlines()):
  62. class_id = i - 1 # starts with -1
  63. class_name = line.strip()
  64. if class_id == -1:
  65. assert class_name == "__ignore__"
  66. continue
  67. class_name_to_id[class_name] = class_id
  68. data["categories"].append(
  69. dict(supercategory=None, id=class_id, name=class_name,)
  70. )
  71. out_ann_file = osp.join(args.output_dir, "annotations.json")
  72. label_files = glob.glob(osp.join(args.input_dir, "*.json"))
  73. for image_id, filename in enumerate(label_files):
  74. print("Generating dataset from:", filename)
  75. label_file = labelme.LabelFile(filename=filename)
  76. base = osp.splitext(osp.basename(filename))[0]
  77. out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
  78. img = labelme.utils.img_data_to_arr(label_file.imageData)
  79. imgviz.io.imsave(out_img_file, img)
  80. data["images"].append(
  81. dict(
  82. license=0,
  83. url=None,
  84. file_name=osp.relpath(out_img_file, osp.dirname(out_ann_file)),
  85. height=img.shape[0],
  86. width=img.shape[1],
  87. date_captured=None,
  88. id=image_id,
  89. )
  90. )
  91. masks = {} # for area
  92. segmentations = collections.defaultdict(list) # for segmentation
  93. for shape in label_file.shapes:
  94. points = shape["points"]
  95. label = shape["label"]
  96. group_id = shape.get("group_id")
  97. shape_type = shape.get("shape_type", "polygon")
  98. mask = labelme.utils.shape_to_mask(
  99. img.shape[:2], points, shape_type
  100. )
  101. if group_id is None:
  102. group_id = uuid.uuid1()
  103. instance = (label, group_id)
  104. if instance in masks:
  105. masks[instance] = masks[instance] | mask
  106. else:
  107. masks[instance] = mask
  108. if shape_type == "rectangle":
  109. (x1, y1), (x2, y2) = points
  110. x1, x2 = sorted([x1, x2])
  111. y1, y2 = sorted([y1, y2])
  112. points = [x1, y1, x2, y1, x2, y2, x1, y2]
  113. else:
  114. points = np.asarray(points).flatten().tolist()
  115. segmentations[instance].append(points)
  116. segmentations = dict(segmentations)
  117. for instance, mask in masks.items():
  118. cls_name, group_id = instance
  119. if cls_name not in class_name_to_id:
  120. continue
  121. cls_id = class_name_to_id[cls_name]
  122. mask = np.asfortranarray(mask.astype(np.uint8))
  123. mask = pycocotools.mask.encode(mask)
  124. area = float(pycocotools.mask.area(mask))
  125. bbox = pycocotools.mask.toBbox(mask).flatten().tolist()
  126. data["annotations"].append(
  127. dict(
  128. id=len(data["annotations"]),
  129. image_id=image_id,
  130. category_id=cls_id,
  131. segmentation=segmentations[instance],
  132. area=area,
  133. bbox=bbox,
  134. iscrowd=0,
  135. )
  136. )
  137. if not args.noviz:
  138. viz = img
  139. if masks:
  140. labels, captions, masks = zip(
  141. *[
  142. (class_name_to_id[cnm], cnm, msk)
  143. for (cnm, gid), msk in masks.items()
  144. if cnm in class_name_to_id
  145. ]
  146. )
  147. viz = imgviz.instances2rgb(
  148. image=img,
  149. labels=labels,
  150. masks=masks,
  151. captions=captions,
  152. font_size=15,
  153. line_width=2,
  154. )
  155. out_viz_file = osp.join(
  156. args.output_dir, "Visualization", base + ".jpg"
  157. )
  158. imgviz.io.imsave(out_viz_file, viz)
  159. with open(out_ann_file, "w") as f:
  160. json.dump(data, f)
  161. if __name__ == "__main__":
  162. main()