labelme_draw_json 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python
  2. import argparse
  3. import json
  4. import base64
  5. from cStringIO import StringIO
  6. import PIL.Image
  7. import PIL.ImageDraw
  8. import matplotlib.pyplot as plt
  9. import numpy as np
  10. from skimage.color import label2rgb
  11. def labelcolormap(N=256):
  12. def bitget(byteval, idx):
  13. return ((byteval & (1 << idx)) != 0)
  14. cmap = np.zeros((N, 3))
  15. for i in xrange(0, N):
  16. id = i
  17. r, g, b = 0, 0, 0
  18. for j in xrange(0, 8):
  19. r = np.bitwise_or(r, (bitget(id, 0) << 7-j))
  20. g = np.bitwise_or(g, (bitget(id, 1) << 7-j))
  21. b = np.bitwise_or(b, (bitget(id, 2) << 7-j))
  22. id = (id >> 3)
  23. cmap[i, 0] = r
  24. cmap[i, 1] = g
  25. cmap[i, 2] = b
  26. cmap = cmap.astype(np.float32) / 255
  27. return cmap
  28. def main():
  29. parser = argparse.ArgumentParser()
  30. parser.add_argument('json_file')
  31. args = parser.parse_args()
  32. json_file = args.json_file
  33. data = json.load(open(json_file))
  34. # string -> numpy.ndarray
  35. f = StringIO()
  36. f.write(base64.b64decode(data['imageData']))
  37. img = np.array(PIL.Image.open(f))
  38. target_names = {'background': 0}
  39. label = np.zeros(img.shape[:2], dtype=np.int32)
  40. for shape in data['shapes']:
  41. # get label value
  42. label_value = target_names.get(shape['label'])
  43. if label_value is None:
  44. label_value = len(target_names)
  45. target_names[shape['label']] = label_value
  46. # polygon -> mask
  47. mask = np.zeros(img.shape[:2], dtype=np.uint8)
  48. mask = PIL.Image.fromarray(mask)
  49. xy = map(tuple, shape['points'])
  50. PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
  51. mask = np.array(mask)
  52. # fill label value
  53. label[mask == 1] = label_value
  54. cmap = labelcolormap(len(target_names))
  55. label_viz = label2rgb(label, img, colors=cmap)
  56. label_viz[label == target_names['background']] = 0
  57. plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
  58. wspace=0, hspace=0)
  59. plt.margins(0, 0)
  60. plt.gca().xaxis.set_major_locator(plt.NullLocator())
  61. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  62. plt.subplot(121)
  63. plt.axis('off')
  64. plt.imshow(img)
  65. plt.subplot(122)
  66. plt.axis('off')
  67. plt.imshow(label_viz)
  68. # plot target_names legend
  69. plt_handlers = []
  70. plt_titles = []
  71. for l_name, l_value in target_names.items():
  72. fc = cmap[l_value]
  73. p = plt.Rectangle((0, 0), 1, 1, fc=fc)
  74. plt_handlers.append(p)
  75. plt_titles.append(l_name)
  76. plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
  77. plt.show()
  78. if __name__ == '__main__':
  79. main()