draw_label_png.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import argparse
  2. import os
  3. import imgviz
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. from labelme.logger import logger
  7. def main():
  8. parser = argparse.ArgumentParser(
  9. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  10. )
  11. parser.add_argument("label_png", help="label PNG file")
  12. parser.add_argument(
  13. "--labels",
  14. help="labels list (comma separated text or file)",
  15. default=None,
  16. )
  17. parser.add_argument("--image", help="image file", default=None)
  18. args = parser.parse_args()
  19. if args.labels is not None:
  20. if os.path.exists(args.labels):
  21. with open(args.labels) as f:
  22. label_names = [label.strip() for label in f]
  23. else:
  24. label_names = args.labels.split(",")
  25. else:
  26. label_names = None
  27. if args.image is not None:
  28. image = imgviz.io.imread(args.image)
  29. else:
  30. image = None
  31. label = imgviz.io.imread(args.label_png)
  32. label = label.astype(np.int32)
  33. label[label == 255] = -1
  34. unique_label_values = np.unique(label)
  35. logger.info("Label image shape: {}".format(label.shape))
  36. logger.info("Label values: {}".format(unique_label_values.tolist()))
  37. if label_names is not None:
  38. logger.info(
  39. "Label names: {}".format(
  40. [
  41. "{}:{}".format(label_value, label_names[label_value])
  42. for label_value in unique_label_values
  43. ]
  44. )
  45. )
  46. if args.image:
  47. num_cols = 2
  48. else:
  49. num_cols = 1
  50. plt.figure(figsize=(num_cols * 6, 5))
  51. plt.subplot(1, num_cols, 1)
  52. plt.title(args.label_png)
  53. label_viz = imgviz.label2rgb(
  54. label=label, label_names=label_names, font_size=label.shape[1] // 30
  55. )
  56. plt.imshow(label_viz)
  57. if image is not None:
  58. plt.subplot(1, num_cols, 2)
  59. label_viz_with_overlay = imgviz.label2rgb(
  60. label=label,
  61. image=image,
  62. label_names=label_names,
  63. font_size=label.shape[1] // 30,
  64. )
  65. plt.title("{}\n{}".format(args.label_png, args.image))
  66. plt.imshow(label_viz_with_overlay)
  67. plt.tight_layout()
  68. plt.show()
  69. if __name__ == "__main__":
  70. main()