create_result_gif.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import os
  4. import os.path as osp
  5. import matplotlib.patches as mpatches
  6. import matplotlib.pyplot as plt
  7. import mmcv
  8. import numpy as np
  9. from mmengine.utils import scandir
  10. try:
  11. import imageio
  12. except ImportError:
  13. imageio = None
  14. # TODO verify after refactoring analyze_results.py
  15. def parse_args():
  16. parser = argparse.ArgumentParser(description='Create GIF for demo')
  17. parser.add_argument(
  18. 'image_dir',
  19. help='directory where result '
  20. 'images save path generated by ‘analyze_results.py’')
  21. parser.add_argument(
  22. '--out',
  23. type=str,
  24. default='result.gif',
  25. help='gif path where will be saved')
  26. args = parser.parse_args()
  27. return args
  28. def _generate_batch_data(sampler, batch_size):
  29. batch = []
  30. for idx in sampler:
  31. batch.append(idx)
  32. if len(batch) == batch_size:
  33. yield batch
  34. batch = []
  35. if len(batch) > 0:
  36. yield batch
  37. def create_gif(frames, gif_name, duration=2):
  38. """Create gif through imageio.
  39. Args:
  40. frames (list[ndarray]): Image frames
  41. gif_name (str): Saved gif name
  42. duration (int): Display interval (s),
  43. Default: 2
  44. """
  45. if imageio is None:
  46. raise RuntimeError('imageio is not installed,'
  47. 'Please use “pip install imageio” to install')
  48. imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
  49. def create_frame_by_matplotlib(image_dir,
  50. nrows=1,
  51. fig_size=(300, 300),
  52. font_size=15):
  53. """Create gif frame image through matplotlib.
  54. Args:
  55. image_dir (str): Root directory of result images
  56. nrows (int): Number of rows displayed, Default: 1
  57. fig_size (tuple): Figure size of the pyplot figure.
  58. Default: (300, 300)
  59. font_size (int): Font size of texts. Default: 15
  60. Returns:
  61. list[ndarray]: image frames
  62. """
  63. result_dir_names = os.listdir(image_dir)
  64. assert len(result_dir_names) == 2
  65. # Longer length has higher priority
  66. result_dir_names.reverse()
  67. images_list = []
  68. for dir_names in result_dir_names:
  69. images_list.append(scandir(osp.join(image_dir, dir_names)))
  70. frames = []
  71. for paths in _generate_batch_data(zip(*images_list), nrows):
  72. fig, axes = plt.subplots(nrows=nrows, ncols=2)
  73. fig.suptitle('Good/bad case selected according '
  74. 'to the COCO mAP of the single image')
  75. det_patch = mpatches.Patch(color='salmon', label='prediction')
  76. gt_patch = mpatches.Patch(color='royalblue', label='ground truth')
  77. # bbox_to_anchor may need to be finetuned
  78. plt.legend(
  79. handles=[det_patch, gt_patch],
  80. bbox_to_anchor=(1, -0.18),
  81. loc='lower right',
  82. borderaxespad=0.)
  83. if nrows == 1:
  84. axes = [axes]
  85. dpi = fig.get_dpi()
  86. # set fig size and margin
  87. fig.set_size_inches(
  88. (fig_size[0] * 2 + fig_size[0] // 20) / dpi,
  89. (fig_size[1] * nrows + fig_size[1] // 3) / dpi,
  90. )
  91. fig.tight_layout()
  92. # set subplot margin
  93. plt.subplots_adjust(
  94. hspace=.05,
  95. wspace=0.05,
  96. left=0.02,
  97. right=0.98,
  98. bottom=0.02,
  99. top=0.98)
  100. for i, (path_tuple, ax_tuple) in enumerate(zip(paths, axes)):
  101. image_path_left = osp.join(
  102. osp.join(image_dir, result_dir_names[0], path_tuple[0]))
  103. image_path_right = osp.join(
  104. osp.join(image_dir, result_dir_names[1], path_tuple[1]))
  105. image_left = mmcv.imread(image_path_left)
  106. image_left = mmcv.rgb2bgr(image_left)
  107. image_right = mmcv.imread(image_path_right)
  108. image_right = mmcv.rgb2bgr(image_right)
  109. if i == 0:
  110. ax_tuple[0].set_title(
  111. result_dir_names[0], fontdict={'size': font_size})
  112. ax_tuple[1].set_title(
  113. result_dir_names[1], fontdict={'size': font_size})
  114. ax_tuple[0].imshow(
  115. image_left, extent=(0, *fig_size, 0), interpolation='bilinear')
  116. ax_tuple[0].axis('off')
  117. ax_tuple[1].imshow(
  118. image_right,
  119. extent=(0, *fig_size, 0),
  120. interpolation='bilinear')
  121. ax_tuple[1].axis('off')
  122. canvas = fig.canvas
  123. s, (width, height) = canvas.print_to_buffer()
  124. buffer = np.frombuffer(s, dtype='uint8')
  125. img_rgba = buffer.reshape(height, width, 4)
  126. rgb, alpha = np.split(img_rgba, [3], axis=2)
  127. img = rgb.astype('uint8')
  128. frames.append(img)
  129. return frames
  130. def main():
  131. args = parse_args()
  132. frames = create_frame_by_matplotlib(args.image_dir)
  133. create_gif(frames, args.out)
  134. if __name__ == '__main__':
  135. main()