json_to_dataset.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import argparse
  2. import base64
  3. import json
  4. import os
  5. import os.path as osp
  6. import imgviz
  7. import PIL.Image
  8. from labelme.logger import logger
  9. from labelme import utils
  10. def main():
  11. logger.warning(
  12. "This script is aimed to demonstrate how to convert the "
  13. "JSON file to a single image dataset."
  14. )
  15. logger.warning(
  16. "It won't handle multiple JSON files to generate a "
  17. "real-use dataset."
  18. )
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument("json_file")
  21. parser.add_argument("-o", "--out", default=None)
  22. args = parser.parse_args()
  23. json_file = args.json_file
  24. if args.out is None:
  25. out_dir = osp.basename(json_file).replace(".", "_")
  26. out_dir = osp.join(osp.dirname(json_file), out_dir)
  27. else:
  28. out_dir = args.out
  29. if not osp.exists(out_dir):
  30. os.mkdir(out_dir)
  31. data = json.load(open(json_file))
  32. imageData = data.get("imageData")
  33. if not imageData:
  34. imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"])
  35. with open(imagePath, "rb") as f:
  36. imageData = f.read()
  37. imageData = base64.b64encode(imageData).decode("utf-8")
  38. img = utils.img_b64_to_arr(imageData)
  39. label_name_to_value = {"_background_": 0}
  40. for shape in sorted(data["shapes"], key=lambda x: x["label"]):
  41. label_name = shape["label"]
  42. if label_name in label_name_to_value:
  43. label_value = label_name_to_value[label_name]
  44. else:
  45. label_value = len(label_name_to_value)
  46. label_name_to_value[label_name] = label_value
  47. lbl, _ = utils.shapes_to_label(
  48. img.shape, data["shapes"], label_name_to_value
  49. )
  50. label_names = [None] * (max(label_name_to_value.values()) + 1)
  51. for name, value in label_name_to_value.items():
  52. label_names[value] = name
  53. lbl_viz = imgviz.label2rgb(
  54. label=lbl, img=imgviz.asgray(img), label_names=label_names, loc="rb"
  55. )
  56. PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
  57. utils.lblsave(osp.join(out_dir, "label.png"), lbl)
  58. PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, "label_viz.png"))
  59. with open(osp.join(out_dir, "label_names.txt"), "w") as f:
  60. for lbl_name in label_names:
  61. f.write(lbl_name + "\n")
  62. logger.info("Saved to: {}".format(out_dir))
  63. if __name__ == "__main__":
  64. main()