labelme2coco.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. if shape_type == "circle":
  114. (x1, y1), (x2, y2) = points
  115. r = np.linalg.norm([x2 - x1, y2 - y1])
  116. # r(1-cos(a/2))<x, a=2*pi/N => N>pi/arccos(1-x/r)
  117. # x: tolerance of the gap between the arc and the line segment
  118. n_points_circle = max(int(np.pi / np.arccos(1 - 1 / r)), 12)
  119. i = np.arange(n_points_circle)
  120. x = x1 + r * np.sin(2 * np.pi / n_points_circle * i)
  121. y = y1 + r * np.cos(2 * np.pi / n_points_circle * i)
  122. points = np.stack((x, y), axis=1).flatten().tolist()
  123. else:
  124. points = np.asarray(points).flatten().tolist()
  125. segmentations[instance].append(points)
  126. segmentations = dict(segmentations)
  127. for instance, mask in masks.items():
  128. cls_name, group_id = instance
  129. if cls_name not in class_name_to_id:
  130. continue
  131. cls_id = class_name_to_id[cls_name]
  132. mask = np.asfortranarray(mask.astype(np.uint8))
  133. mask = pycocotools.mask.encode(mask)
  134. area = float(pycocotools.mask.area(mask))
  135. bbox = pycocotools.mask.toBbox(mask).flatten().tolist()
  136. data["annotations"].append(
  137. dict(
  138. id=len(data["annotations"]),
  139. image_id=image_id,
  140. category_id=cls_id,
  141. segmentation=segmentations[instance],
  142. area=area,
  143. bbox=bbox,
  144. iscrowd=0,
  145. )
  146. )
  147. if not args.noviz:
  148. viz = img
  149. if masks:
  150. labels, captions, masks = zip(
  151. *[
  152. (class_name_to_id[cnm], cnm, msk)
  153. for (cnm, gid), msk in masks.items()
  154. if cnm in class_name_to_id
  155. ]
  156. )
  157. viz = imgviz.instances2rgb(
  158. image=img,
  159. labels=labels,
  160. masks=masks,
  161. captions=captions,
  162. font_size=15,
  163. line_width=2,
  164. )
  165. out_viz_file = osp.join(
  166. args.output_dir, "Visualization", base + ".jpg"
  167. )
  168. imgviz.io.imsave(out_viz_file, viz)
  169. with open(out_ann_file, "w") as f:
  170. json.dump(data, f)
  171. if __name__ == "__main__":
  172. main()