utils.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import base64
  2. try:
  3. import io
  4. except ImportError:
  5. import io as io
  6. import warnings
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9. import PIL.Image
  10. import PIL.ImageDraw
  11. import scipy.misc
  12. def label_colormap(N=256):
  13. def bitget(byteval, idx):
  14. return ((byteval & (1 << idx)) != 0)
  15. cmap = np.zeros((N, 3))
  16. for i in range(0, N):
  17. id = i
  18. r, g, b = 0, 0, 0
  19. for j in range(0, 8):
  20. r = np.bitwise_or(r, (bitget(id, 0) << 7-j))
  21. g = np.bitwise_or(g, (bitget(id, 1) << 7-j))
  22. b = np.bitwise_or(b, (bitget(id, 2) << 7-j))
  23. id = (id >> 3)
  24. cmap[i, 0] = r
  25. cmap[i, 1] = g
  26. cmap[i, 2] = b
  27. cmap = cmap.astype(np.float32) / 255
  28. return cmap
  29. def labelcolormap(N=256):
  30. warnings.warn('labelcolormap is deprecated. Please use label_colormap.')
  31. return label_colormap(N=N)
  32. # similar function as skimage.color.label2rgb
  33. def label2rgb(lbl, img=None, n_labels=None, alpha=0.3, thresh_suppress=0):
  34. if n_labels is None:
  35. n_labels = len(np.unique(lbl))
  36. cmap = label_colormap(n_labels)
  37. cmap = (cmap * 255).astype(np.uint8)
  38. lbl_viz = cmap[lbl]
  39. lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled
  40. if img is not None:
  41. img_gray = PIL.Image.fromarray(img).convert('LA')
  42. img_gray = np.asarray(img_gray.convert('RGB'))
  43. # img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  44. # img_gray = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
  45. lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray
  46. lbl_viz = lbl_viz.astype(np.uint8)
  47. return lbl_viz
  48. def img_b64_to_array(img_b64):
  49. f = io.BytesIO()
  50. f.write(base64.b64decode(img_b64))
  51. img_arr = np.array(PIL.Image.open(f))
  52. return img_arr
  53. def polygons_to_mask(img_shape, polygons):
  54. mask = np.zeros(img_shape[:2], dtype=np.uint8)
  55. mask = PIL.Image.fromarray(mask)
  56. xy = list(map(tuple, polygons))
  57. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  58. mask = np.array(mask, dtype=bool)
  59. return mask
  60. def draw_label(label, img, label_names, colormap=None):
  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 colormap is None:
  67. colormap = label_colormap(len(label_names))
  68. label_viz = label2rgb(label, img, n_labels=len(label_names))
  69. plt.imshow(label_viz)
  70. plt.axis('off')
  71. plt_handlers = []
  72. plt_titles = []
  73. for label_value, label_name in enumerate(label_names):
  74. fc = colormap[label_value]
  75. p = plt.Rectangle((0, 0), 1, 1, fc=fc)
  76. plt_handlers.append(p)
  77. plt_titles.append(label_name)
  78. plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
  79. f = io.BytesIO()
  80. plt.savefig(f, bbox_inches='tight', pad_inches=0)
  81. plt.cla()
  82. plt.close()
  83. out = np.array(PIL.Image.open(f))[:, :, :3]
  84. out = scipy.misc.imresize(out, img.shape[:2])
  85. return out
  86. def labelme_shapes_to_label(img_shape, shapes):
  87. label_name_to_val = {'background': 0}
  88. lbl = np.zeros(img_shape[:2], dtype=np.int32)
  89. for shape in sorted(shapes, key=lambda x: x['label']):
  90. polygons = shape['points']
  91. label_name = shape['label']
  92. if label_name in label_name_to_val:
  93. label_value = label_name_to_val[label_name]
  94. else:
  95. label_value = len(label_name_to_val)
  96. label_name_to_val[label_name] = label_value
  97. mask = polygons_to_mask(img_shape[:2], polygons)
  98. lbl[mask] = label_value
  99. lbl_names = [None] * (max(label_name_to_val.values()) + 1)
  100. for label_name, label_value in label_name_to_val.items():
  101. lbl_names[label_value] = label_name
  102. return lbl, lbl_names