labelme2voc.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import argparse
  4. import glob
  5. import os
  6. import os.path as osp
  7. import sys
  8. import imgviz
  9. import numpy as np
  10. import labelme
  11. def main():
  12. parser = argparse.ArgumentParser(
  13. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  14. )
  15. parser.add_argument("input_dir", help="Input annotated directory")
  16. parser.add_argument("output_dir", help="Output dataset directory")
  17. parser.add_argument("--labels", help="Labels file", required=True)
  18. parser.add_argument(
  19. "--noobject", help="Flag not to generate object label", action="store_true"
  20. )
  21. parser.add_argument(
  22. "--nonpy", help="Flag not to generate .npy files", action="store_true"
  23. )
  24. parser.add_argument(
  25. "--noviz", help="Flag to disable visualization", action="store_true"
  26. )
  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. os.makedirs(osp.join(args.output_dir, "SegmentationClass"))
  34. if not args.nonpy:
  35. os.makedirs(osp.join(args.output_dir, "SegmentationClassNpy"))
  36. if not args.noviz:
  37. os.makedirs(osp.join(args.output_dir, "SegmentationClassVisualization"))
  38. if not args.noobject:
  39. os.makedirs(osp.join(args.output_dir, "SegmentationObject"))
  40. if not args.nonpy:
  41. os.makedirs(osp.join(args.output_dir, "SegmentationObjectNpy"))
  42. if not args.noviz:
  43. os.makedirs(osp.join(args.output_dir, "SegmentationObjectVisualization"))
  44. print("Creating dataset:", args.output_dir)
  45. class_names = []
  46. class_name_to_id = {}
  47. for i, line in enumerate(open(args.labels).readlines()):
  48. class_id = i - 1 # starts with -1
  49. class_name = line.strip()
  50. class_name_to_id[class_name] = class_id
  51. if class_id == -1:
  52. assert class_name == "__ignore__"
  53. continue
  54. elif class_id == 0:
  55. assert class_name == "_background_"
  56. class_names.append(class_name)
  57. class_names = tuple(class_names)
  58. print("class_names:", class_names)
  59. out_class_names_file = osp.join(args.output_dir, "class_names.txt")
  60. with open(out_class_names_file, "w") as f:
  61. f.writelines("\n".join(class_names))
  62. print("Saved class_names:", out_class_names_file)
  63. for filename in glob.glob(osp.join(args.input_dir, "*.json")):
  64. print("Generating dataset from:", filename)
  65. label_file = labelme.LabelFile(filename=filename)
  66. base = osp.splitext(osp.basename(filename))[0]
  67. out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
  68. out_clsp_file = osp.join(args.output_dir, "SegmentationClass", base + ".png")
  69. if not args.nonpy:
  70. out_cls_file = osp.join(
  71. args.output_dir, "SegmentationClassNpy", base + ".npy"
  72. )
  73. if not args.noviz:
  74. out_clsv_file = osp.join(
  75. args.output_dir,
  76. "SegmentationClassVisualization",
  77. base + ".jpg",
  78. )
  79. if not args.noobject:
  80. out_insp_file = osp.join(
  81. args.output_dir, "SegmentationObject", base + ".png"
  82. )
  83. if not args.nonpy:
  84. out_ins_file = osp.join(
  85. args.output_dir, "SegmentationObjectNpy", base + ".npy"
  86. )
  87. if not args.noviz:
  88. out_insv_file = osp.join(
  89. args.output_dir,
  90. "SegmentationObjectVisualization",
  91. base + ".jpg",
  92. )
  93. img = labelme.utils.img_data_to_arr(label_file.imageData)
  94. imgviz.io.imsave(out_img_file, img)
  95. cls, ins = labelme.utils.shapes_to_label(
  96. img_shape=img.shape,
  97. shapes=label_file.shapes,
  98. label_name_to_value=class_name_to_id,
  99. )
  100. ins[cls == -1] = 0 # ignore it.
  101. # class label
  102. labelme.utils.lblsave(out_clsp_file, cls)
  103. if not args.nonpy:
  104. np.save(out_cls_file, cls)
  105. if not args.noviz:
  106. clsv = imgviz.label2rgb(
  107. cls,
  108. imgviz.rgb2gray(img),
  109. label_names=class_names,
  110. font_size=15,
  111. loc="rb",
  112. )
  113. imgviz.io.imsave(out_clsv_file, clsv)
  114. if not args.noobject:
  115. # instance label
  116. labelme.utils.lblsave(out_insp_file, ins)
  117. if not args.nonpy:
  118. np.save(out_ins_file, ins)
  119. if not args.noviz:
  120. instance_ids = np.unique(ins)
  121. instance_names = [str(i) for i in range(max(instance_ids) + 1)]
  122. insv = imgviz.label2rgb(
  123. ins,
  124. imgviz.rgb2gray(img),
  125. label_names=instance_names,
  126. font_size=15,
  127. loc="rb",
  128. )
  129. imgviz.io.imsave(out_insv_file, insv)
  130. if __name__ == "__main__":
  131. main()