export_json.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 import utils
  9. from labelme.logger import logger
  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.splitext(osp.basename(json_file))[0]
  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(img.shape, data["shapes"], label_name_to_value)
  40. label_names = [None] * (max(label_name_to_value.values()) + 1)
  41. for name, value in label_name_to_value.items():
  42. label_names[value] = name
  43. lbl_viz = imgviz.label2rgb(
  44. lbl, imgviz.asgray(img), label_names=label_names, loc="rb"
  45. )
  46. PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
  47. utils.lblsave(osp.join(out_dir, "label.png"), lbl)
  48. PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, "label_viz.png"))
  49. with open(osp.join(out_dir, "label_names.txt"), "w") as f:
  50. for lbl_name in label_names:
  51. f.write(lbl_name + "\n")
  52. logger.info("Saved to: {}".format(out_dir))
  53. if __name__ == "__main__":
  54. main()