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.

base.py 14 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from abc import ABCMeta, abstractmethod
  3. from collections import OrderedDict
  4. import mmcv
  5. import numpy as np
  6. import torch
  7. import torch.distributed as dist
  8. from mmcv.runner import BaseModule, auto_fp16
  9. from mmdet.core.visualization import imshow_det_bboxes
  10. class BaseDetector(BaseModule, metaclass=ABCMeta):
  11. """Base class for detectors."""
  12. def __init__(self, init_cfg=None):
  13. super(BaseDetector, self).__init__(init_cfg)
  14. self.fp16_enabled = False
  15. @property
  16. def with_neck(self):
  17. """bool: whether the detector has a neck"""
  18. return hasattr(self, 'neck') and self.neck is not None
  19. # TODO: these properties need to be carefully handled
  20. # for both single stage & two stage detectors
  21. @property
  22. def with_shared_head(self):
  23. """bool: whether the detector has a shared head in the RoI Head"""
  24. return hasattr(self, 'roi_head') and self.roi_head.with_shared_head
  25. @property
  26. def with_bbox(self):
  27. """bool: whether the detector has a bbox head"""
  28. return ((hasattr(self, 'roi_head') and self.roi_head.with_bbox)
  29. or (hasattr(self, 'bbox_head') and self.bbox_head is not None))
  30. @property
  31. def with_mask(self):
  32. """bool: whether the detector has a mask head"""
  33. return ((hasattr(self, 'roi_head') and self.roi_head.with_mask)
  34. or (hasattr(self, 'mask_head') and self.mask_head is not None))
  35. @abstractmethod
  36. def extract_feat(self, imgs):
  37. """Extract features from images."""
  38. pass
  39. def extract_feats(self, imgs):
  40. """Extract features from multiple images.
  41. Args:
  42. imgs (list[torch.Tensor]): A list of images. The images are
  43. augmented from the same image but in different ways.
  44. Returns:
  45. list[torch.Tensor]: Features of different images
  46. """
  47. assert isinstance(imgs, list)
  48. return [self.extract_feat(img) for img in imgs]
  49. def forward_train(self, imgs, img_metas, **kwargs):
  50. """
  51. Args:
  52. img (list[Tensor]): List of tensors of shape (1, C, H, W).
  53. Typically these should be mean centered and std scaled.
  54. img_metas (list[dict]): List of image info dict where each dict
  55. has: 'img_shape', 'scale_factor', 'flip', and may also contain
  56. 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
  57. For details on the values of these keys, see
  58. :class:`mmdet.datasets.pipelines.Collect`.
  59. kwargs (keyword arguments): Specific to concrete implementation.
  60. """
  61. # NOTE the batched image size information may be useful, e.g.
  62. # in DETR, this is needed for the construction of masks, which is
  63. # then used for the transformer_head.
  64. batch_input_shape = tuple(imgs[0].size()[-2:])
  65. for img_meta in img_metas:
  66. img_meta['batch_input_shape'] = batch_input_shape
  67. async def async_simple_test(self, img, img_metas, **kwargs):
  68. raise NotImplementedError
  69. @abstractmethod
  70. def simple_test(self, img, img_metas, **kwargs):
  71. pass
  72. @abstractmethod
  73. def aug_test(self, imgs, img_metas, **kwargs):
  74. """Test function with test time augmentation."""
  75. pass
  76. async def aforward_test(self, *, img, img_metas, **kwargs):
  77. for var, name in [(img, 'img'), (img_metas, 'img_metas')]:
  78. if not isinstance(var, list):
  79. raise TypeError(f'{name} must be a list, but got {type(var)}')
  80. num_augs = len(img)
  81. if num_augs != len(img_metas):
  82. raise ValueError(f'num of augmentations ({len(img)}) '
  83. f'!= num of image metas ({len(img_metas)})')
  84. # TODO: remove the restriction of samples_per_gpu == 1 when prepared
  85. samples_per_gpu = img[0].size(0)
  86. assert samples_per_gpu == 1
  87. if num_augs == 1:
  88. return await self.async_simple_test(img[0], img_metas[0], **kwargs)
  89. else:
  90. raise NotImplementedError
  91. def forward_test(self, imgs, img_metas, **kwargs):
  92. """
  93. Args:
  94. imgs (List[Tensor]): the outer list indicates test-time
  95. augmentations and inner Tensor should have a shape NxCxHxW,
  96. which contains all images in the batch.
  97. img_metas (List[List[dict]]): the outer list indicates test-time
  98. augs (multiscale, flip, etc.) and the inner list indicates
  99. images in a batch.
  100. """
  101. for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]:
  102. if not isinstance(var, list):
  103. raise TypeError(f'{name} must be a list, but got {type(var)}')
  104. num_augs = len(imgs)
  105. if num_augs != len(img_metas):
  106. raise ValueError(f'num of augmentations ({len(imgs)}) '
  107. f'!= num of image meta ({len(img_metas)})')
  108. # NOTE the batched image size information may be useful, e.g.
  109. # in DETR, this is needed for the construction of masks, which is
  110. # then used for the transformer_head.
  111. for img, img_meta in zip(imgs, img_metas):
  112. batch_size = len(img_meta)
  113. for img_id in range(batch_size):
  114. img_meta[img_id]['batch_input_shape'] = tuple(img.size()[-2:])
  115. if num_augs == 1:
  116. # proposals (List[List[Tensor]]): the outer list indicates
  117. # test-time augs (multiscale, flip, etc.) and the inner list
  118. # indicates images in a batch.
  119. # The Tensor should have a shape Px4, where P is the number of
  120. # proposals.
  121. if 'proposals' in kwargs:
  122. kwargs['proposals'] = kwargs['proposals'][0]
  123. return self.simple_test(imgs[0], img_metas[0], **kwargs)
  124. else:
  125. assert imgs[0].size(0) == 1, 'aug test does not support ' \
  126. 'inference with batch size ' \
  127. f'{imgs[0].size(0)}'
  128. # TODO: support test augmentation for predefined proposals
  129. assert 'proposals' not in kwargs
  130. return self.aug_test(imgs, img_metas, **kwargs)
  131. @auto_fp16(apply_to=('img', ))
  132. def forward(self, img, img_metas, return_loss=True, **kwargs):
  133. """Calls either :func:`forward_train` or :func:`forward_test` depending
  134. on whether ``return_loss`` is ``True``.
  135. Note this setting will change the expected inputs. When
  136. ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor
  137. and List[dict]), and when ``resturn_loss=False``, img and img_meta
  138. should be double nested (i.e. List[Tensor], List[List[dict]]), with
  139. the outer list indicating test time augmentations.
  140. """
  141. if torch.onnx.is_in_onnx_export():
  142. assert len(img_metas) == 1
  143. return self.onnx_export(img[0], img_metas[0])
  144. if return_loss:
  145. return self.forward_train(img, img_metas, **kwargs)
  146. else:
  147. return self.forward_test(img, img_metas, **kwargs)
  148. def _parse_losses(self, losses):
  149. """Parse the raw outputs (losses) of the network.
  150. Args:
  151. losses (dict): Raw output of the network, which usually contain
  152. losses and other necessary information.
  153. Returns:
  154. tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \
  155. which may be a weighted sum of all losses, log_vars contains \
  156. all the variables to be sent to the logger.
  157. """
  158. log_vars = OrderedDict()
  159. for loss_name, loss_value in losses.items():
  160. if isinstance(loss_value, torch.Tensor):
  161. log_vars[loss_name] = loss_value.mean()
  162. elif isinstance(loss_value, list):
  163. log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)
  164. else:
  165. raise TypeError(
  166. f'{loss_name} is not a tensor or list of tensors')
  167. loss = sum(_value for _key, _value in log_vars.items()
  168. if 'loss' in _key)
  169. log_vars['loss'] = loss
  170. for loss_name, loss_value in log_vars.items():
  171. # reduce loss when distributed training
  172. if dist.is_available() and dist.is_initialized():
  173. loss_value = loss_value.data.clone()
  174. dist.all_reduce(loss_value.div_(dist.get_world_size()))
  175. log_vars[loss_name] = loss_value.item()
  176. return loss, log_vars
  177. def train_step(self, data, optimizer):
  178. """The iteration step during training.
  179. This method defines an iteration step during training, except for the
  180. back propagation and optimizer updating, which are done in an optimizer
  181. hook. Note that in some complicated cases or models, the whole process
  182. including back propagation and optimizer updating is also defined in
  183. this method, such as GAN.
  184. Args:
  185. data (dict): The output of dataloader.
  186. optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of
  187. runner is passed to ``train_step()``. This argument is unused
  188. and reserved.
  189. Returns:
  190. dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \
  191. ``num_samples``.
  192. - ``loss`` is a tensor for back propagation, which can be a
  193. weighted sum of multiple losses.
  194. - ``log_vars`` contains all the variables to be sent to the
  195. logger.
  196. - ``num_samples`` indicates the batch size (when the model is
  197. DDP, it means the batch size on each GPU), which is used for
  198. averaging the logs.
  199. """
  200. losses = self(**data)
  201. loss, log_vars = self._parse_losses(losses)
  202. outputs = dict(
  203. loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))
  204. return outputs
  205. def val_step(self, data, optimizer=None):
  206. """The iteration step during validation.
  207. This method shares the same signature as :func:`train_step`, but used
  208. during val epochs. Note that the evaluation after training epochs is
  209. not implemented with this method, but an evaluation hook.
  210. """
  211. losses = self(**data)
  212. loss, log_vars = self._parse_losses(losses)
  213. outputs = dict(
  214. loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))
  215. return outputs
  216. def show_result(self,
  217. img,
  218. result,
  219. score_thr=0.3,
  220. bbox_color=(72, 101, 241),
  221. text_color=(72, 101, 241),
  222. mask_color=None,
  223. thickness=2,
  224. font_size=13,
  225. win_name='',
  226. show=False,
  227. wait_time=0,
  228. out_file=None):
  229. """Draw `result` over `img`.
  230. Args:
  231. img (str or Tensor): The image to be displayed.
  232. result (Tensor or tuple): The results to draw over `img`
  233. bbox_result or (bbox_result, segm_result).
  234. score_thr (float, optional): Minimum score of bboxes to be shown.
  235. Default: 0.3.
  236. bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.
  237. The tuple of color should be in BGR order. Default: 'green'
  238. text_color (str or tuple(int) or :obj:`Color`):Color of texts.
  239. The tuple of color should be in BGR order. Default: 'green'
  240. mask_color (None or str or tuple(int) or :obj:`Color`):
  241. Color of masks. The tuple of color should be in BGR order.
  242. Default: None
  243. thickness (int): Thickness of lines. Default: 2
  244. font_size (int): Font size of texts. Default: 13
  245. win_name (str): The window name. Default: ''
  246. wait_time (float): Value of waitKey param.
  247. Default: 0.
  248. show (bool): Whether to show the image.
  249. Default: False.
  250. out_file (str or None): The filename to write the image.
  251. Default: None.
  252. Returns:
  253. img (Tensor): Only if not `show` or `out_file`
  254. """
  255. img = mmcv.imread(img)
  256. img = img.copy()
  257. if isinstance(result, tuple):
  258. bbox_result, segm_result = result
  259. if isinstance(segm_result, tuple):
  260. segm_result = segm_result[0] # ms rcnn
  261. else:
  262. bbox_result, segm_result = result, None
  263. bboxes = np.vstack(bbox_result)
  264. labels = [
  265. np.full(bbox.shape[0], i, dtype=np.int32)
  266. for i, bbox in enumerate(bbox_result)
  267. ]
  268. labels = np.concatenate(labels)
  269. # draw segmentation masks
  270. segms = None
  271. if segm_result is not None and len(labels) > 0: # non empty
  272. segms = mmcv.concat_list(segm_result)
  273. if isinstance(segms[0], torch.Tensor):
  274. segms = torch.stack(segms, dim=0).detach().cpu().numpy()
  275. else:
  276. segms = np.stack(segms, axis=0)
  277. # if out_file specified, do not show image in window
  278. if out_file is not None:
  279. show = False
  280. # draw bounding boxes
  281. img = imshow_det_bboxes(
  282. img,
  283. bboxes,
  284. labels,
  285. segms,
  286. class_names=self.CLASSES,
  287. score_thr=score_thr,
  288. bbox_color=bbox_color,
  289. text_color=text_color,
  290. mask_color=mask_color,
  291. thickness=thickness,
  292. font_size=font_size,
  293. win_name=win_name,
  294. show=show,
  295. wait_time=wait_time,
  296. out_file=out_file)
  297. if not (show or out_file):
  298. return img
  299. def onnx_export(self, img, img_metas):
  300. raise NotImplementedError(f'{self.__class__.__name__} does '
  301. f'not support ONNX EXPORT')

No Description

Contributors (3)