visualization_hook.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import os.path as osp
  3. import warnings
  4. from typing import Optional, Sequence
  5. import mmcv
  6. from mmengine.fileio import get
  7. from mmengine.hooks import Hook
  8. from mmengine.runner import Runner
  9. from mmengine.utils import mkdir_or_exist
  10. from mmengine.visualization import Visualizer
  11. from mmdet.registry import HOOKS
  12. from mmdet.structures import DetDataSample
  13. @HOOKS.register_module()
  14. class DetVisualizationHook(Hook):
  15. """Detection Visualization Hook. Used to visualize validation and testing
  16. process prediction results.
  17. In the testing phase:
  18. 1. If ``show`` is True, it means that only the prediction results are
  19. visualized without storing data, so ``vis_backends`` needs to
  20. be excluded.
  21. 2. If ``test_out_dir`` is specified, it means that the prediction results
  22. need to be saved to ``test_out_dir``. In order to avoid vis_backends
  23. also storing data, so ``vis_backends`` needs to be excluded.
  24. 3. ``vis_backends`` takes effect if the user does not specify ``show``
  25. and `test_out_dir``. You can set ``vis_backends`` to WandbVisBackend or
  26. TensorboardVisBackend to store the prediction result in Wandb or
  27. Tensorboard.
  28. Args:
  29. draw (bool): whether to draw prediction results. If it is False,
  30. it means that no drawing will be done. Defaults to False.
  31. interval (int): The interval of visualization. Defaults to 50.
  32. score_thr (float): The threshold to visualize the bboxes
  33. and masks. Defaults to 0.3.
  34. show (bool): Whether to display the drawn image. Default to False.
  35. wait_time (float): The interval of show (s). Defaults to 0.
  36. test_out_dir (str, optional): directory where painted images
  37. will be saved in testing process.
  38. backend_args (dict, optional): Arguments to instantiate the
  39. corresponding backend. Defaults to None.
  40. """
  41. def __init__(self,
  42. draw: bool = False,
  43. interval: int = 50,
  44. score_thr: float = 0.3,
  45. show: bool = False,
  46. wait_time: float = 0.,
  47. test_out_dir: Optional[str] = None,
  48. backend_args: dict = None):
  49. self._visualizer: Visualizer = Visualizer.get_current_instance()
  50. self.interval = interval
  51. self.score_thr = score_thr
  52. self.show = show
  53. if self.show:
  54. # No need to think about vis backends.
  55. self._visualizer._vis_backends = {}
  56. warnings.warn('The show is True, it means that only '
  57. 'the prediction results are visualized '
  58. 'without storing data, so vis_backends '
  59. 'needs to be excluded.')
  60. self.wait_time = wait_time
  61. self.backend_args = backend_args
  62. self.draw = draw
  63. self.test_out_dir = test_out_dir
  64. self._test_index = 0
  65. def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  66. outputs: Sequence[DetDataSample]) -> None:
  67. """Run after every ``self.interval`` validation iterations.
  68. Args:
  69. runner (:obj:`Runner`): The runner of the validation process.
  70. batch_idx (int): The index of the current batch in the val loop.
  71. data_batch (dict): Data from dataloader.
  72. outputs (Sequence[:obj:`DetDataSample`]]): A batch of data samples
  73. that contain annotations and predictions.
  74. """
  75. if self.draw is False:
  76. return
  77. # There is no guarantee that the same batch of images
  78. # is visualized for each evaluation.
  79. total_curr_iter = runner.iter + batch_idx
  80. # Visualize only the first data
  81. img_path = outputs[0].img_path
  82. img_bytes = get(img_path, backend_args=self.backend_args)
  83. img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
  84. if total_curr_iter % self.interval == 0:
  85. self._visualizer.add_datasample(
  86. osp.basename(img_path) if self.show else 'val_img',
  87. img,
  88. data_sample=outputs[0],
  89. show=self.show,
  90. wait_time=self.wait_time,
  91. pred_score_thr=self.score_thr,
  92. step=total_curr_iter)
  93. def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  94. outputs: Sequence[DetDataSample]) -> None:
  95. """Run after every testing iterations.
  96. Args:
  97. runner (:obj:`Runner`): The runner of the testing process.
  98. batch_idx (int): The index of the current batch in the val loop.
  99. data_batch (dict): Data from dataloader.
  100. outputs (Sequence[:obj:`DetDataSample`]): A batch of data samples
  101. that contain annotations and predictions.
  102. """
  103. if self.draw is False:
  104. return
  105. if self.test_out_dir is not None:
  106. self.test_out_dir = osp.join(runner.work_dir, runner.timestamp,
  107. self.test_out_dir)
  108. mkdir_or_exist(self.test_out_dir)
  109. for data_sample in outputs:
  110. self._test_index += 1
  111. img_path = data_sample.img_path
  112. img_bytes = get(img_path, backend_args=self.backend_args)
  113. img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
  114. out_file = None
  115. if self.test_out_dir is not None:
  116. out_file = osp.basename(img_path)
  117. out_file = osp.join(self.test_out_dir, out_file)
  118. self._visualizer.add_datasample(
  119. osp.basename(img_path) if self.show else 'test_img',
  120. img,
  121. data_sample=data_sample,
  122. show=self.show,
  123. wait_time=self.wait_time,
  124. pred_score_thr=self.score_thr,
  125. out_file=out_file,
  126. step=self._test_index)