util.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. from __future__ import print_function
  2. import torch
  3. import numpy as np
  4. from PIL import Image
  5. import numpy as np
  6. import os
  7. # Converts a Tensor into a Numpy array
  8. # |imtype|: the desired type of the converted numpy array
  9. def tensor2im(image_tensor, imtype=np.uint8, normalize=True):
  10. if isinstance(image_tensor, list):
  11. image_numpy = []
  12. for i in range(len(image_tensor)):
  13. image_numpy.append(tensor2im(image_tensor[i], imtype, normalize))
  14. return image_numpy
  15. image_numpy = image_tensor.cpu().float().numpy()
  16. if normalize:
  17. image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
  18. else:
  19. image_numpy = np.transpose(image_numpy, (1, 2, 0)) * 255.0
  20. image_numpy = np.clip(image_numpy, 0, 255)
  21. if image_numpy.shape[2] == 1 or image_numpy.shape[2] > 3:
  22. image_numpy = image_numpy[:,:,0]
  23. return image_numpy.astype(imtype)
  24. # Converts a one-hot tensor into a colorful label map
  25. def tensor2label(label_tensor, n_label, imtype=np.uint8):
  26. if n_label == 0:
  27. return tensor2im(label_tensor, imtype)
  28. label_tensor = label_tensor.cpu().float()
  29. if label_tensor.size()[0] > 1:
  30. label_tensor = label_tensor.max(0, keepdim=True)[1]
  31. label_tensor = Colorize(n_label)(label_tensor)
  32. label_numpy = np.transpose(label_tensor.numpy(), (1, 2, 0))
  33. return label_numpy.astype(imtype)
  34. def save_image(image_numpy, image_path):
  35. image_pil = Image.fromarray(image_numpy)
  36. image_pil.save(image_path)
  37. def mkdirs(paths):
  38. if isinstance(paths, list) and not isinstance(paths, str):
  39. for path in paths:
  40. mkdir(path)
  41. else:
  42. mkdir(paths)
  43. def mkdir(path):
  44. if not os.path.exists(path):
  45. os.makedirs(path)
  46. ###############################################################################
  47. # Code from
  48. # https://github.com/ycszen/pytorch-seg/blob/master/transform.py
  49. # Modified so it complies with the Citscape label map colors
  50. ###############################################################################
  51. def uint82bin(n, count=8):
  52. """returns the binary of integer n, count refers to amount of bits"""
  53. return ''.join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
  54. def labelcolormap(N):
  55. if N == 35: # cityscape
  56. cmap = np.array([( 0, 0, 0), ( 0, 0, 0), ( 0, 0, 0), ( 0, 0, 0), ( 0, 0, 0), (111, 74, 0), ( 81, 0, 81),
  57. (128, 64,128), (244, 35,232), (250,170,160), (230,150,140), ( 70, 70, 70), (102,102,156), (190,153,153),
  58. (180,165,180), (150,100,100), (150,120, 90), (153,153,153), (153,153,153), (250,170, 30), (220,220, 0),
  59. (107,142, 35), (152,251,152), ( 70,130,180), (220, 20, 60), (255, 0, 0), ( 0, 0,142), ( 0, 0, 70),
  60. ( 0, 60,100), ( 0, 0, 90), ( 0, 0,110), ( 0, 80,100), ( 0, 0,230), (119, 11, 32), ( 0, 0,142)],
  61. dtype=np.uint8)
  62. else:
  63. cmap = np.zeros((N, 3), dtype=np.uint8)
  64. for i in range(N):
  65. r, g, b = 0, 0, 0
  66. id = i
  67. for j in range(7):
  68. str_id = uint82bin(id)
  69. r = r ^ (np.uint8(str_id[-1]) << (7-j))
  70. g = g ^ (np.uint8(str_id[-2]) << (7-j))
  71. b = b ^ (np.uint8(str_id[-3]) << (7-j))
  72. id = id >> 3
  73. cmap[i, 0] = r
  74. cmap[i, 1] = g
  75. cmap[i, 2] = b
  76. return cmap
  77. class Colorize(object):
  78. def __init__(self, n=35):
  79. self.cmap = labelcolormap(n)
  80. self.cmap = torch.from_numpy(self.cmap[:n])
  81. def __call__(self, gray_image):
  82. size = gray_image.size()
  83. color_image = torch.ByteTensor(3, size[1], size[2]).fill_(0)
  84. for label in range(0, len(self.cmap)):
  85. mask = (label == gray_image[0]).cpu()
  86. color_image[0][mask] = self.cmap[label][0]
  87. color_image[1][mask] = self.cmap[label][1]
  88. color_image[2][mask] = self.cmap[label][2]
  89. return color_image