You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

create_result_gif.py 4.9 kB

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

No Description

Contributors (3)