export_json.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. parser = argparse.ArgumentParser()
  12. parser.add_argument("json_file")
  13. parser.add_argument("-o", "--out", default=None)
  14. args = parser.parse_args()
  15. json_file = args.json_file
  16. if args.out is None:
  17. out_dir = osp.basename(json_file).replace(".", "_")
  18. out_dir = osp.join(osp.dirname(json_file), out_dir)
  19. else:
  20. out_dir = args.out
  21. if not osp.exists(out_dir):
  22. os.mkdir(out_dir)
  23. data = json.load(open(json_file))
  24. imageData = data.get("imageData")
  25. if not imageData:
  26. imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"])
  27. with open(imagePath, "rb") as f:
  28. imageData = f.read()
  29. imageData = base64.b64encode(imageData).decode("utf-8")
  30. img = utils.img_b64_to_arr(imageData)
  31. label_name_to_value = {"_background_": 0}
  32. for shape in sorted(data["shapes"], key=lambda x: x["label"]):
  33. label_name = shape["label"]
  34. if label_name in label_name_to_value:
  35. label_value = label_name_to_value[label_name]
  36. else:
  37. label_value = len(label_name_to_value)
  38. label_name_to_value[label_name] = label_value
  39. lbl, _ = utils.shapes_to_label(
  40. img.shape, data["shapes"], label_name_to_value
  41. )
  42. label_names = [None] * (max(label_name_to_value.values()) + 1)
  43. for name, value in label_name_to_value.items():
  44. label_names[value] = name
  45. lbl_viz = imgviz.label2rgb(
  46. lbl, imgviz.asgray(img), label_names=label_names, loc="rb"
  47. )
  48. PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
  49. utils.lblsave(osp.join(out_dir, "label.png"), lbl)
  50. PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, "label_viz.png"))
  51. with open(osp.join(out_dir, "label_names.txt"), "w") as f:
  52. for lbl_name in label_names:
  53. f.write(lbl_name + "\n")
  54. logger.info("Saved to: {}".format(out_dir))
  55. if __name__ == "__main__":
  56. main()