visualization_hook.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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.datasets.samplers import TrackImgSampler
  12. from mmdet.registry import HOOKS
  13. from mmdet.structures import DetDataSample, TrackDataSample
  14. @HOOKS.register_module()
  15. class DetVisualizationHook(Hook):
  16. """Detection Visualization Hook. Used to visualize validation and testing
  17. process prediction results.
  18. In the testing phase:
  19. 1. If ``show`` is True, it means that only the prediction results are
  20. visualized without storing data, so ``vis_backends`` needs to
  21. be excluded.
  22. 2. If ``test_out_dir`` is specified, it means that the prediction results
  23. need to be saved to ``test_out_dir``. In order to avoid vis_backends
  24. also storing data, so ``vis_backends`` needs to be excluded.
  25. 3. ``vis_backends`` takes effect if the user does not specify ``show``
  26. and `test_out_dir``. You can set ``vis_backends`` to WandbVisBackend or
  27. TensorboardVisBackend to store the prediction result in Wandb or
  28. Tensorboard.
  29. Args:
  30. draw (bool): whether to draw prediction results. If it is False,
  31. it means that no drawing will be done. Defaults to False.
  32. interval (int): The interval of visualization. Defaults to 50.
  33. score_thr (float): The threshold to visualize the bboxes
  34. and masks. Defaults to 0.3.
  35. show (bool): Whether to display the drawn image. Default to False.
  36. wait_time (float): The interval of show (s). Defaults to 0.
  37. test_out_dir (str, optional): directory where painted images
  38. will be saved in testing process.
  39. backend_args (dict, optional): Arguments to instantiate the
  40. corresponding backend. Defaults to None.
  41. """
  42. def __init__(self,
  43. draw: bool = False,
  44. interval: int = 50,
  45. score_thr: float = 0.3,
  46. show: bool = False,
  47. wait_time: float = 0.,
  48. test_out_dir: Optional[str] = None,
  49. backend_args: dict = None):
  50. self._visualizer: Visualizer = Visualizer.get_current_instance()
  51. self.interval = interval
  52. self.score_thr = score_thr
  53. self.show = show
  54. if self.show:
  55. # No need to think about vis backends.
  56. self._visualizer._vis_backends = {}
  57. warnings.warn('The show is True, it means that only '
  58. 'the prediction results are visualized '
  59. 'without storing data, so vis_backends '
  60. 'needs to be excluded.')
  61. self.wait_time = wait_time
  62. self.backend_args = backend_args
  63. self.draw = draw
  64. self.test_out_dir = test_out_dir
  65. self._test_index = 0
  66. def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  67. outputs: Sequence[DetDataSample]) -> None:
  68. """Run after every ``self.interval`` validation iterations.
  69. Args:
  70. runner (:obj:`Runner`): The runner of the validation process.
  71. batch_idx (int): The index of the current batch in the val loop.
  72. data_batch (dict): Data from dataloader.
  73. outputs (Sequence[:obj:`DetDataSample`]]): A batch of data samples
  74. that contain annotations and predictions.
  75. """
  76. if self.draw is False:
  77. return
  78. # There is no guarantee that the same batch of images
  79. # is visualized for each evaluation.
  80. total_curr_iter = runner.iter + batch_idx
  81. # Visualize only the first data
  82. img_path = outputs[0].img_path
  83. img_bytes = get(img_path, backend_args=self.backend_args)
  84. img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
  85. if total_curr_iter % self.interval == 0:
  86. self._visualizer.add_datasample(
  87. osp.basename(img_path) if self.show else 'val_img',
  88. img,
  89. data_sample=outputs[0],
  90. show=self.show,
  91. wait_time=self.wait_time,
  92. pred_score_thr=self.score_thr,
  93. step=total_curr_iter)
  94. def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  95. outputs: Sequence[DetDataSample]) -> None:
  96. """Run after every testing iterations.
  97. Args:
  98. runner (:obj:`Runner`): The runner of the testing process.
  99. batch_idx (int): The index of the current batch in the val loop.
  100. data_batch (dict): Data from dataloader.
  101. outputs (Sequence[:obj:`DetDataSample`]): A batch of data samples
  102. that contain annotations and predictions.
  103. """
  104. if self.draw is False:
  105. return
  106. if self.test_out_dir is not None:
  107. self.test_out_dir = osp.join(runner.work_dir, runner.timestamp,
  108. self.test_out_dir)
  109. mkdir_or_exist(self.test_out_dir)
  110. for data_sample in outputs:
  111. self._test_index += 1
  112. img_path = data_sample.img_path
  113. img_bytes = get(img_path, backend_args=self.backend_args)
  114. img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
  115. out_file = None
  116. if self.test_out_dir is not None:
  117. out_file = osp.basename(img_path)
  118. out_file = osp.join(self.test_out_dir, out_file)
  119. self._visualizer.add_datasample(
  120. osp.basename(img_path) if self.show else 'test_img',
  121. img,
  122. data_sample=data_sample,
  123. show=self.show,
  124. wait_time=self.wait_time,
  125. pred_score_thr=self.score_thr,
  126. out_file=out_file,
  127. step=self._test_index)
  128. @HOOKS.register_module()
  129. class TrackVisualizationHook(Hook):
  130. """Tracking Visualization Hook. Used to visualize validation and testing
  131. process prediction results.
  132. In the testing phase:
  133. 1. If ``show`` is True, it means that only the prediction results are
  134. visualized without storing data, so ``vis_backends`` needs to
  135. be excluded.
  136. 2. If ``test_out_dir`` is specified, it means that the prediction results
  137. need to be saved to ``test_out_dir``. In order to avoid vis_backends
  138. also storing data, so ``vis_backends`` needs to be excluded.
  139. 3. ``vis_backends`` takes effect if the user does not specify ``show``
  140. and `test_out_dir``. You can set ``vis_backends`` to WandbVisBackend or
  141. TensorboardVisBackend to store the prediction result in Wandb or
  142. Tensorboard.
  143. Args:
  144. draw (bool): whether to draw prediction results. If it is False,
  145. it means that no drawing will be done. Defaults to False.
  146. frame_interval (int): The interval of visualization. Defaults to 30.
  147. score_thr (float): The threshold to visualize the bboxes
  148. and masks. Defaults to 0.3.
  149. show (bool): Whether to display the drawn image. Default to False.
  150. wait_time (float): The interval of show (s). Defaults to 0.
  151. test_out_dir (str, optional): directory where painted images
  152. will be saved in testing process.
  153. backend_args (dict): Arguments to instantiate a file client.
  154. Defaults to ``None``.
  155. """
  156. def __init__(self,
  157. draw: bool = False,
  158. frame_interval: int = 30,
  159. score_thr: float = 0.3,
  160. show: bool = False,
  161. wait_time: float = 0.,
  162. test_out_dir: Optional[str] = None,
  163. backend_args: dict = None) -> None:
  164. self._visualizer: Visualizer = Visualizer.get_current_instance()
  165. self.frame_interval = frame_interval
  166. self.score_thr = score_thr
  167. self.show = show
  168. if self.show:
  169. # No need to think about vis backends.
  170. self._visualizer._vis_backends = {}
  171. warnings.warn('The show is True, it means that only '
  172. 'the prediction results are visualized '
  173. 'without storing data, so vis_backends '
  174. 'needs to be excluded.')
  175. self.wait_time = wait_time
  176. self.backend_args = backend_args
  177. self.draw = draw
  178. self.test_out_dir = test_out_dir
  179. self.image_idx = 0
  180. def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  181. outputs: Sequence[TrackDataSample]) -> None:
  182. """Run after every ``self.interval`` validation iteration.
  183. Args:
  184. runner (:obj:`Runner`): The runner of the validation process.
  185. batch_idx (int): The index of the current batch in the val loop.
  186. data_batch (dict): Data from dataloader.
  187. outputs (Sequence[:obj:`TrackDataSample`]): Outputs from model.
  188. """
  189. if self.draw is False:
  190. return
  191. assert len(outputs) == 1,\
  192. 'only batch_size=1 is supported while validating.'
  193. sampler = runner.val_dataloader.sampler
  194. if isinstance(sampler, TrackImgSampler):
  195. if self.every_n_inner_iters(batch_idx, self.frame_interval):
  196. total_curr_iter = runner.iter + batch_idx
  197. track_data_sample = outputs[0]
  198. self.visualize_single_image(track_data_sample[0],
  199. total_curr_iter)
  200. else:
  201. # video visualization DefaultSampler
  202. if self.every_n_inner_iters(batch_idx, 1):
  203. track_data_sample = outputs[0]
  204. video_length = len(track_data_sample)
  205. for frame_id in range(video_length):
  206. if frame_id % self.frame_interval == 0:
  207. total_curr_iter = runner.iter + self.image_idx + \
  208. frame_id
  209. img_data_sample = track_data_sample[frame_id]
  210. self.visualize_single_image(img_data_sample,
  211. total_curr_iter)
  212. self.image_idx = self.image_idx + video_length
  213. def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
  214. outputs: Sequence[TrackDataSample]) -> None:
  215. """Run after every testing iteration.
  216. Args:
  217. runner (:obj:`Runner`): The runner of the testing process.
  218. batch_idx (int): The index of the current batch in the test loop.
  219. data_batch (dict): Data from dataloader.
  220. outputs (Sequence[:obj:`TrackDataSample`]): Outputs from model.
  221. """
  222. if self.draw is False:
  223. return
  224. assert len(outputs) == 1, \
  225. 'only batch_size=1 is supported while testing.'
  226. if self.test_out_dir is not None:
  227. self.test_out_dir = osp.join(runner.work_dir, runner.timestamp,
  228. self.test_out_dir)
  229. mkdir_or_exist(self.test_out_dir)
  230. sampler = runner.test_dataloader.sampler
  231. if isinstance(sampler, TrackImgSampler):
  232. if self.every_n_inner_iters(batch_idx, self.frame_interval):
  233. track_data_sample = outputs[0]
  234. self.visualize_single_image(track_data_sample[0], batch_idx)
  235. else:
  236. # video visualization DefaultSampler
  237. if self.every_n_inner_iters(batch_idx, 1):
  238. track_data_sample = outputs[0]
  239. video_length = len(track_data_sample)
  240. for frame_id in range(video_length):
  241. if frame_id % self.frame_interval == 0:
  242. img_data_sample = track_data_sample[frame_id]
  243. self.visualize_single_image(img_data_sample,
  244. self.image_idx + frame_id)
  245. self.image_idx = self.image_idx + video_length
  246. def visualize_single_image(self, img_data_sample: DetDataSample,
  247. step: int) -> None:
  248. """
  249. Args:
  250. img_data_sample (DetDataSample): single image output.
  251. step (int): The index of the current image.
  252. """
  253. img_path = img_data_sample.img_path
  254. img_bytes = get(img_path, backend_args=self.backend_args)
  255. img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
  256. out_file = None
  257. if self.test_out_dir is not None:
  258. video_name = img_path.split('/')[-3]
  259. mkdir_or_exist(osp.join(self.test_out_dir, video_name))
  260. out_file = osp.join(self.test_out_dir, video_name,
  261. osp.basename(img_path))
  262. self._visualizer.add_datasample(
  263. osp.basename(img_path) if self.show else 'test_img',
  264. img,
  265. data_sample=img_data_sample,
  266. show=self.show,
  267. wait_time=self.wait_time,
  268. pred_score_thr=self.score_thr,
  269. out_file=out_file,
  270. step=step)