labelme2coco.py 6.4 KB

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