utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import base64
  2. import io
  3. import warnings
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. import PIL.Image
  7. import PIL.ImageDraw
  8. def label_colormap(N=256):
  9. def bitget(byteval, idx):
  10. return ((byteval & (1 << idx)) != 0)
  11. cmap = np.zeros((N, 3))
  12. for i in range(0, N):
  13. id = i
  14. r, g, b = 0, 0, 0
  15. for j in range(0, 8):
  16. r = np.bitwise_or(r, (bitget(id, 0) << 7 - j))
  17. g = np.bitwise_or(g, (bitget(id, 1) << 7 - j))
  18. b = np.bitwise_or(b, (bitget(id, 2) << 7 - j))
  19. id = (id >> 3)
  20. cmap[i, 0] = r
  21. cmap[i, 1] = g
  22. cmap[i, 2] = b
  23. cmap = cmap.astype(np.float32) / 255
  24. return cmap
  25. def labelcolormap(N=256):
  26. warnings.warn('labelcolormap is deprecated. Please use label_colormap.')
  27. return label_colormap(N=N)
  28. # similar function as skimage.color.label2rgb
  29. def label2rgb(lbl, img=None, n_labels=None, alpha=0.3, thresh_suppress=0):
  30. if n_labels is None:
  31. n_labels = len(np.unique(lbl))
  32. cmap = label_colormap(n_labels)
  33. cmap = (cmap * 255).astype(np.uint8)
  34. lbl_viz = cmap[lbl]
  35. lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled
  36. if img is not None:
  37. img_gray = PIL.Image.fromarray(img).convert('LA')
  38. img_gray = np.asarray(img_gray.convert('RGB'))
  39. # img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  40. # img_gray = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
  41. lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray
  42. lbl_viz = lbl_viz.astype(np.uint8)
  43. return lbl_viz
  44. def img_b64_to_array(img_b64):
  45. warnings.warn('img_ba64_to_array is deprecated. '
  46. 'Please use img_b64_to_arr.')
  47. return img_b64_to_arr(img_b64)
  48. def img_b64_to_arr(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 img_arr_to_b64(img_arr):
  54. img_pil = PIL.Image.fromarray(img_arr)
  55. f = io.BytesIO()
  56. img_pil.save(f, format='PNG')
  57. img_bin = f.getvalue()
  58. img_b64 = base64.encodestring(img_bin)
  59. return img_b64
  60. def polygons_to_mask(img_shape, polygons):
  61. mask = np.zeros(img_shape[:2], dtype=np.uint8)
  62. mask = PIL.Image.fromarray(mask)
  63. xy = list(map(tuple, polygons))
  64. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  65. mask = np.array(mask, dtype=bool)
  66. return mask
  67. def draw_label(label, img, label_names, colormap=None):
  68. backend_org = plt.rcParams['backend']
  69. plt.switch_backend('agg')
  70. plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
  71. wspace=0, hspace=0)
  72. plt.margins(0, 0)
  73. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  74. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  75. if colormap is None:
  76. colormap = label_colormap(len(label_names))
  77. label_viz = label2rgb(label, img, n_labels=len(label_names))
  78. plt.imshow(label_viz)
  79. plt.axis('off')
  80. plt_handlers = []
  81. plt_titles = []
  82. for label_value, label_name in enumerate(label_names):
  83. if label_value not in label:
  84. continue
  85. if label_name.startswith('_'):
  86. continue
  87. fc = colormap[label_value]
  88. p = plt.Rectangle((0, 0), 1, 1, fc=fc)
  89. plt_handlers.append(p)
  90. plt_titles.append(label_name)
  91. plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
  92. f = io.BytesIO()
  93. plt.savefig(f, bbox_inches='tight', pad_inches=0)
  94. plt.cla()
  95. plt.close()
  96. plt.switch_backend(backend_org)
  97. out_size = (img.shape[1], img.shape[0])
  98. out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
  99. out = np.asarray(out)
  100. return out
  101. def shapes_to_label(img_shape, shapes, label_name_to_value, type='class'):
  102. assert type in ['class', 'instance']
  103. cls = np.zeros(img_shape[:2], dtype=np.int32)
  104. if type == 'instance':
  105. ins = np.zeros(img_shape[:2], dtype=np.int32)
  106. instance_names = ['__background__']
  107. for shape in shapes:
  108. polygons = shape['points']
  109. label = shape['label']
  110. if type == 'class':
  111. cls_name = label
  112. elif type == 'instance':
  113. cls_name = label.split('-')[0]
  114. if label not in instance_names:
  115. instance_names.append(label)
  116. ins_id = len(instance_names) - 1
  117. cls_id = label_name_to_value[cls_name]
  118. mask = polygons_to_mask(img_shape[:2], polygons)
  119. cls[mask] = cls_id
  120. if type == 'instance':
  121. ins[mask] = ins_id
  122. if type == 'instance':
  123. return cls, ins
  124. return cls
  125. def labelme_shapes_to_label(img_shape, shapes):
  126. warnings.warn('labelme_shapes_to_label is deprecated, so please use '
  127. 'shapes_to_label.')
  128. label_name_to_value = {}
  129. for shape in shapes:
  130. label_name = shape['label']
  131. if label_name in label_name_to_value:
  132. label_value = label_name_to_value[label_name]
  133. else:
  134. label_value = len(label_name_to_value)
  135. label_name_to_value[label_name] = label_value
  136. lbl = shapes_to_label(img_shape, shapes, label_name_to_value)
  137. return lbl, label_name_to_value