draw.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import io
  2. import numpy as np
  3. import PIL.Image
  4. import PIL.ImageDraw
  5. def label_colormap(N=256):
  6. def bitget(byteval, idx):
  7. return ((byteval & (1 << idx)) != 0)
  8. cmap = np.zeros((N, 3))
  9. for i in range(0, N):
  10. id = i
  11. r, g, b = 0, 0, 0
  12. for j in range(0, 8):
  13. r = np.bitwise_or(r, (bitget(id, 0) << 7 - j))
  14. g = np.bitwise_or(g, (bitget(id, 1) << 7 - j))
  15. b = np.bitwise_or(b, (bitget(id, 2) << 7 - j))
  16. id = (id >> 3)
  17. cmap[i, 0] = r
  18. cmap[i, 1] = g
  19. cmap[i, 2] = b
  20. cmap = cmap.astype(np.float32) / 255
  21. return cmap
  22. def _validate_colormap(colormap, n_labels):
  23. if colormap is None:
  24. colormap = label_colormap(n_labels)
  25. else:
  26. assert colormap.shape == (colormap.shape[0], 3), \
  27. 'colormap must be sequence of RGB values'
  28. assert 0 <= colormap.min() and colormap.max() <= 1, \
  29. 'colormap must ranges 0 to 1'
  30. return colormap
  31. # similar function as skimage.color.label2rgb
  32. def label2rgb(
  33. lbl, img=None, n_labels=None, alpha=0.5, thresh_suppress=0, colormap=None,
  34. ):
  35. if n_labels is None:
  36. n_labels = len(np.unique(lbl))
  37. colormap = _validate_colormap(colormap, n_labels)
  38. colormap = (colormap * 255).astype(np.uint8)
  39. lbl_viz = colormap[lbl]
  40. lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled
  41. if img is not None:
  42. img_gray = PIL.Image.fromarray(img).convert('LA')
  43. img_gray = np.asarray(img_gray.convert('RGB'))
  44. # img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  45. # img_gray = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
  46. lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray
  47. lbl_viz = lbl_viz.astype(np.uint8)
  48. return lbl_viz
  49. def draw_label(label, img=None, label_names=None, colormap=None, **kwargs):
  50. """Draw pixel-wise label with colorization and label names.
  51. label: ndarray, (H, W)
  52. Pixel-wise labels to colorize.
  53. img: ndarray, (H, W, 3), optional
  54. Image on which the colorized label will be drawn.
  55. label_names: iterable
  56. List of label names.
  57. """
  58. import matplotlib.pyplot as plt
  59. backend_org = plt.rcParams['backend']
  60. plt.switch_backend('agg')
  61. plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
  62. wspace=0, hspace=0)
  63. plt.margins(0, 0)
  64. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  65. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  66. if label_names is None:
  67. label_names = [str(l) for l in range(label.max() + 1)]
  68. colormap = _validate_colormap(colormap, len(label_names))
  69. label_viz = label2rgb(
  70. label, img, n_labels=len(label_names), colormap=colormap, **kwargs
  71. )
  72. plt.imshow(label_viz)
  73. plt.axis('off')
  74. plt_handlers = []
  75. plt_titles = []
  76. for label_value, label_name in enumerate(label_names):
  77. if label_value not in label:
  78. continue
  79. fc = colormap[label_value]
  80. p = plt.Rectangle((0, 0), 1, 1, fc=fc)
  81. plt_handlers.append(p)
  82. plt_titles.append('{value}: {name}'
  83. .format(value=label_value, name=label_name))
  84. plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
  85. f = io.BytesIO()
  86. plt.savefig(f, bbox_inches='tight', pad_inches=0)
  87. plt.cla()
  88. plt.close()
  89. plt.switch_backend(backend_org)
  90. out_size = (label_viz.shape[1], label_viz.shape[0])
  91. out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
  92. out = np.asarray(out)
  93. return out