visualize.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. ## @package visualize
  2. # Module caffe2.python.visualize
  3. """Functions that could be used to visualize Tensors.
  4. This is adapted from the old-time iceberk package that Yangqing wrote... Oh gold
  5. memories. Before decaf and caffe. Why iceberk? Because I was at Berkeley,
  6. bears are vegetarian, and iceberg lettuce has layers of leaves.
  7. (This joke is so lame.)
  8. """
  9. import numpy as np
  10. from matplotlib import cm, pyplot
  11. def ChannelFirst(arr):
  12. """Convert a HWC array to CHW."""
  13. ndim = arr.ndim
  14. return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
  15. def ChannelLast(arr):
  16. """Convert a CHW array to HWC."""
  17. ndim = arr.ndim
  18. return arr.swapaxes(ndim - 3, ndim - 2).swapaxes(ndim - 2, ndim - 1)
  19. class PatchVisualizer(object):
  20. """PatchVisualizer visualizes patches.
  21. """
  22. def __init__(self, gap=1):
  23. self.gap = gap
  24. def ShowSingle(self, patch, cmap=None):
  25. """Visualizes one single patch.
  26. The input patch could be a vector (in which case we try to infer the shape
  27. of the patch), a 2-D matrix, or a 3-D matrix whose 3rd dimension has 3
  28. channels.
  29. """
  30. if len(patch.shape) == 1:
  31. patch = patch.reshape(self.get_patch_shape(patch))
  32. elif len(patch.shape) > 2 and patch.shape[2] != 3:
  33. raise ValueError("The input patch shape isn't correct.")
  34. # determine color
  35. if len(patch.shape) == 2 and cmap is None:
  36. cmap = cm.gray
  37. pyplot.imshow(patch, cmap=cmap)
  38. return patch
  39. def ShowMultiple(self, patches, ncols=None, cmap=None, bg_func=np.mean):
  40. """Visualize multiple patches.
  41. In the passed in patches matrix, each row is a patch, in the shape of either
  42. n*n, n*n*1 or n*n*3, either in a flattened format (so patches would be a
  43. 2-D array), or a multi-dimensional tensor. We will try our best to figure
  44. out automatically the patch size.
  45. """
  46. num_patches = patches.shape[0]
  47. if ncols is None:
  48. ncols = int(np.ceil(np.sqrt(num_patches)))
  49. nrows = int(np.ceil(num_patches / float(ncols)))
  50. if len(patches.shape) == 2:
  51. patches = patches.reshape(
  52. (patches.shape[0], ) + self.get_patch_shape(patches[0])
  53. )
  54. patch_size_expand = np.array(patches.shape[1:3]) + self.gap
  55. image_size = patch_size_expand * np.array([nrows, ncols]) - self.gap
  56. if len(patches.shape) == 4:
  57. if patches.shape[3] == 1:
  58. # gray patches
  59. patches = patches.reshape(patches.shape[:-1])
  60. image_shape = tuple(image_size)
  61. if cmap is None:
  62. cmap = cm.gray
  63. elif patches.shape[3] == 3:
  64. # color patches
  65. image_shape = tuple(image_size) + (3, )
  66. else:
  67. raise ValueError("The input patch shape isn't expected.")
  68. else:
  69. image_shape = tuple(image_size)
  70. if cmap is None:
  71. cmap = cm.gray
  72. image = np.ones(image_shape) * bg_func(patches)
  73. for pid in range(num_patches):
  74. row = pid // ncols * patch_size_expand[0]
  75. col = pid % ncols * patch_size_expand[1]
  76. image[row:row+patches.shape[1], col:col+patches.shape[2]] = \
  77. patches[pid]
  78. pyplot.imshow(image, cmap=cmap, interpolation='nearest')
  79. pyplot.axis('off')
  80. return image
  81. def ShowImages(self, patches, *args, **kwargs):
  82. """Similar to ShowMultiple, but always normalize the values between 0 and 1
  83. for better visualization of image-type data.
  84. """
  85. patches = patches - np.min(patches)
  86. patches /= np.max(patches) + np.finfo(np.float64).eps
  87. return self.ShowMultiple(patches, *args, **kwargs)
  88. def ShowChannels(self, patch, cmap=None, bg_func=np.mean):
  89. """ This function shows the channels of a patch.
  90. The incoming patch should have shape [w, h, num_channels], and each channel
  91. will be visualized as a separate gray patch.
  92. """
  93. if len(patch.shape) != 3:
  94. raise ValueError("The input patch shape isn't correct.")
  95. patch_reordered = np.swapaxes(patch.T, 1, 2)
  96. return self.ShowMultiple(patch_reordered, cmap=cmap, bg_func=bg_func)
  97. def get_patch_shape(self, patch):
  98. """Gets the shape of a single patch.
  99. Basically it tries to interpret the patch as a square, and also check if it
  100. is in color (3 channels)
  101. """
  102. edgeLen = np.sqrt(patch.size)
  103. if edgeLen != np.floor(edgeLen):
  104. # we are given color patches
  105. edgeLen = np.sqrt(patch.size / 3.)
  106. if edgeLen != np.floor(edgeLen):
  107. raise ValueError("I can't figure out the patch shape.")
  108. return (edgeLen, edgeLen, 3)
  109. else:
  110. edgeLen = int(edgeLen)
  111. return (edgeLen, edgeLen)
  112. _default_visualizer = PatchVisualizer()
  113. """Utility functions that directly point to functions in the default visualizer.
  114. These functions don't return anything, so you won't see annoying printouts of
  115. the visualized images. If you want to save the images for example, you should
  116. explicitly instantiate a patch visualizer, and call those functions.
  117. """
  118. class NHWC(object):
  119. @staticmethod
  120. def ShowSingle(*args, **kwargs):
  121. _default_visualizer.ShowSingle(*args, **kwargs)
  122. @staticmethod
  123. def ShowMultiple(*args, **kwargs):
  124. _default_visualizer.ShowMultiple(*args, **kwargs)
  125. @staticmethod
  126. def ShowImages(*args, **kwargs):
  127. _default_visualizer.ShowImages(*args, **kwargs)
  128. @staticmethod
  129. def ShowChannels(*args, **kwargs):
  130. _default_visualizer.ShowChannels(*args, **kwargs)
  131. class NCHW(object):
  132. @staticmethod
  133. def ShowSingle(patch, *args, **kwargs):
  134. _default_visualizer.ShowSingle(ChannelLast(patch), *args, **kwargs)
  135. @staticmethod
  136. def ShowMultiple(patch, *args, **kwargs):
  137. _default_visualizer.ShowMultiple(ChannelLast(patch), *args, **kwargs)
  138. @staticmethod
  139. def ShowImages(patch, *args, **kwargs):
  140. _default_visualizer.ShowImages(ChannelLast(patch), *args, **kwargs)
  141. @staticmethod
  142. def ShowChannels(patch, *args, **kwargs):
  143. _default_visualizer.ShowChannels(ChannelLast(patch), *args, **kwargs)