viz2d.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """
  2. 2D visualization primitives based on Matplotlib.
  3. 1) Plot images with `plot_images`.
  4. 2) Call `plot_keypoints` or `plot_matches` any number of times.
  5. 3) Optionally: save a .png or .pdf plot (nice in papers!) with `save_plot`.
  6. """
  7. import matplotlib
  8. import matplotlib.patheffects as path_effects
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. import torch
  12. def cm_RdGn(x):
  13. """Custom colormap: red (0) -> yellow (0.5) -> green (1)."""
  14. x = np.clip(x, 0, 1)[..., None] * 2
  15. c = x * np.array([[0, 1.0, 0]]) + (2 - x) * np.array([[1.0, 0, 0]])
  16. return np.clip(c, 0, 1)
  17. def cm_BlRdGn(x_):
  18. """Custom colormap: blue (-1) -> red (0.0) -> green (1)."""
  19. x = np.clip(x_, 0, 1)[..., None] * 2
  20. c = x * np.array([[0, 1.0, 0, 1.0]]) + (2 - x) * np.array([[1.0, 0, 0, 1.0]])
  21. xn = -np.clip(x_, -1, 0)[..., None] * 2
  22. cn = xn * np.array([[0, 0.1, 1, 1.0]]) + (2 - xn) * np.array([[1.0, 0, 0, 1.0]])
  23. out = np.clip(np.where(x_[..., None] < 0, cn, c), 0, 1)
  24. return out
  25. def cm_prune(x_):
  26. """Custom colormap to visualize pruning"""
  27. if isinstance(x_, torch.Tensor):
  28. x_ = x_.cpu().numpy()
  29. max_i = max(x_)
  30. norm_x = np.where(x_ == max_i, -1, (x_ - 1) / 9)
  31. return cm_BlRdGn(norm_x)
  32. def cm_grad2d(xy):
  33. """2D grad. colormap: yellow (0, 0) -> green (1, 0) -> red (0, 1) -> blue (1, 1)."""
  34. tl = np.array([1.0, 0, 0]) # red
  35. tr = np.array([0, 0.0, 1]) # blue
  36. ll = np.array([1.0, 1.0, 0]) # yellow
  37. lr = np.array([0, 1.0, 0]) # green
  38. xy = np.clip(xy, 0, 1)
  39. x = xy[..., :1]
  40. y = xy[..., -1:]
  41. rgb = (1 - x) * (1 - y) * ll + x * (1 - y) * lr + x * y * tr + (1 - x) * y * tl
  42. return rgb.clip(0, 1)
  43. def plot_images(imgs, titles=None, cmaps="gray", dpi=100, pad=0.5, adaptive=True):
  44. """Plot a set of images horizontally.
  45. Args:
  46. imgs: list of NumPy RGB (H, W, 3) or PyTorch RGB (3, H, W) or mono (H, W).
  47. titles: a list of strings, as titles for each image.
  48. cmaps: colormaps for monochrome images.
  49. adaptive: whether the figure size should fit the image aspect ratios.
  50. """
  51. # conversion to (H, W, 3) for torch.Tensor
  52. imgs = [
  53. (
  54. img.permute(1, 2, 0).cpu().numpy()
  55. if (isinstance(img, torch.Tensor) and img.dim() == 3)
  56. else img
  57. )
  58. for img in imgs
  59. ]
  60. n = len(imgs)
  61. if not isinstance(cmaps, (list, tuple)):
  62. cmaps = [cmaps] * n
  63. if adaptive:
  64. ratios = [i.shape[1] / i.shape[0] for i in imgs] # W / H
  65. else:
  66. ratios = [4 / 3] * n
  67. figsize = [sum(ratios) * 4.5, 4.5]
  68. fig, ax = plt.subplots(
  69. 1, n, figsize=figsize, dpi=dpi, gridspec_kw={"width_ratios": ratios}
  70. )
  71. if n == 1:
  72. ax = [ax]
  73. for i in range(n):
  74. ax[i].imshow(imgs[i], cmap=plt.get_cmap(cmaps[i]))
  75. ax[i].get_yaxis().set_ticks([])
  76. ax[i].get_xaxis().set_ticks([])
  77. ax[i].set_axis_off()
  78. for spine in ax[i].spines.values(): # remove frame
  79. spine.set_visible(False)
  80. if titles:
  81. ax[i].set_title(titles[i])
  82. fig.tight_layout(pad=pad)
  83. def plot_keypoints(kpts, colors="lime", ps=4, axes=None, a=1.0):
  84. """Plot keypoints for existing images.
  85. Args:
  86. kpts: list of ndarrays of size (N, 2).
  87. colors: string, or list of list of tuples (one for each keypoints).
  88. ps: size of the keypoints as float.
  89. """
  90. if not isinstance(colors, list):
  91. colors = [colors] * len(kpts)
  92. if not isinstance(a, list):
  93. a = [a] * len(kpts)
  94. if axes is None:
  95. axes = plt.gcf().axes
  96. for ax, k, c, alpha in zip(axes, kpts, colors, a):
  97. if isinstance(k, torch.Tensor):
  98. k = k.cpu().numpy()
  99. ax.scatter(k[:, 0], k[:, 1], c=c, s=ps, linewidths=0, alpha=alpha)
  100. def plot_matches(kpts0, kpts1, color=None, lw=1.5, ps=4, a=1.0, labels=None, axes=None):
  101. """Plot matches for a pair of existing images.
  102. Args:
  103. kpts0, kpts1: corresponding keypoints of size (N, 2).
  104. color: color of each match, string or RGB tuple. Random if not given.
  105. lw: width of the lines.
  106. ps: size of the end points (no endpoint if ps=0)
  107. indices: indices of the images to draw the matches on.
  108. a: alpha opacity of the match lines.
  109. """
  110. fig = plt.gcf()
  111. if axes is None:
  112. ax = fig.axes
  113. ax0, ax1 = ax[0], ax[1]
  114. else:
  115. ax0, ax1 = axes
  116. if isinstance(kpts0, torch.Tensor):
  117. kpts0 = kpts0.cpu().numpy()
  118. if isinstance(kpts1, torch.Tensor):
  119. kpts1 = kpts1.cpu().numpy()
  120. assert len(kpts0) == len(kpts1)
  121. if color is None:
  122. kpts_norm = (kpts0 - kpts0.min(axis=0, keepdims=True)) / np.ptp(
  123. kpts0, axis=0, keepdims=True
  124. )
  125. color = cm_grad2d(kpts_norm) # gradient color
  126. elif len(color) > 0 and not isinstance(color[0], (tuple, list)):
  127. color = [color] * len(kpts0)
  128. if lw > 0:
  129. for i in range(len(kpts0)):
  130. line = matplotlib.patches.ConnectionPatch(
  131. xyA=(kpts0[i, 0], kpts0[i, 1]),
  132. xyB=(kpts1[i, 0], kpts1[i, 1]),
  133. coordsA=ax0.transData,
  134. coordsB=ax1.transData,
  135. axesA=ax0,
  136. axesB=ax1,
  137. zorder=1,
  138. color=color[i],
  139. linewidth=lw,
  140. clip_on=True,
  141. alpha=a,
  142. label=None if labels is None else labels[i],
  143. picker=5.0,
  144. )
  145. line.set_annotation_clip(True)
  146. fig.add_artist(line)
  147. # freeze the axes to prevent the transform to change
  148. ax0.autoscale(enable=False)
  149. ax1.autoscale(enable=False)
  150. if ps > 0:
  151. ax0.scatter(kpts0[:, 0], kpts0[:, 1], c=color, s=ps)
  152. ax1.scatter(kpts1[:, 0], kpts1[:, 1], c=color, s=ps)
  153. def add_text(
  154. idx,
  155. text,
  156. pos=(0.01, 0.99),
  157. fs=15,
  158. color="w",
  159. lcolor="k",
  160. lwidth=2,
  161. ha="left",
  162. va="top",
  163. ):
  164. ax = plt.gcf().axes[idx]
  165. t = ax.text(
  166. *pos, text, fontsize=fs, ha=ha, va=va, color=color, transform=ax.transAxes
  167. )
  168. if lcolor is not None:
  169. t.set_path_effects(
  170. [
  171. path_effects.Stroke(linewidth=lwidth, foreground=lcolor),
  172. path_effects.Normal(),
  173. ]
  174. )
  175. def save_plot(path, **kw):
  176. """Save the current figure without any white margin."""
  177. plt.savefig(path, bbox_inches="tight", pad_inches=0, **kw)