inference.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import copy
  3. import warnings
  4. from pathlib import Path
  5. from typing import Optional, Sequence, Union
  6. import numpy as np
  7. import torch
  8. import torch.nn as nn
  9. from mmcv.ops import RoIPool
  10. from mmcv.transforms import Compose
  11. from mmengine.config import Config
  12. from mmengine.model.utils import revert_sync_batchnorm
  13. from mmengine.registry import init_default_scope
  14. from mmengine.runner import load_checkpoint
  15. from mmdet.registry import DATASETS
  16. from ..evaluation import get_classes
  17. from ..registry import MODELS
  18. from ..structures import DetDataSample, SampleList
  19. from ..utils import get_test_pipeline_cfg
  20. def init_detector(
  21. config: Union[str, Path, Config],
  22. checkpoint: Optional[str] = None,
  23. palette: str = 'none',
  24. device: str = 'cuda:0',
  25. cfg_options: Optional[dict] = None,
  26. ) -> nn.Module:
  27. """Initialize a detector from config file.
  28. Args:
  29. config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path,
  30. :obj:`Path`, or the config object.
  31. checkpoint (str, optional): Checkpoint path. If left as None, the model
  32. will not load any weights.
  33. palette (str): Color palette used for visualization. If palette
  34. is stored in checkpoint, use checkpoint's palette first, otherwise
  35. use externally passed palette. Currently, supports 'coco', 'voc',
  36. 'citys' and 'random'. Defaults to none.
  37. device (str): The device where the anchors will be put on.
  38. Defaults to cuda:0.
  39. cfg_options (dict, optional): Options to override some settings in
  40. the used config.
  41. Returns:
  42. nn.Module: The constructed detector.
  43. """
  44. if isinstance(config, (str, Path)):
  45. config = Config.fromfile(config)
  46. elif not isinstance(config, Config):
  47. raise TypeError('config must be a filename or Config object, '
  48. f'but got {type(config)}')
  49. if cfg_options is not None:
  50. config.merge_from_dict(cfg_options)
  51. elif 'init_cfg' in config.model.backbone:
  52. config.model.backbone.init_cfg = None
  53. init_default_scope(config.get('default_scope', 'mmdet'))
  54. model = MODELS.build(config.model)
  55. model = revert_sync_batchnorm(model)
  56. if checkpoint is None:
  57. warnings.simplefilter('once')
  58. warnings.warn('checkpoint is None, use COCO classes by default.')
  59. model.dataset_meta = {'classes': get_classes('coco')}
  60. else:
  61. checkpoint = load_checkpoint(model, checkpoint, map_location='cpu')
  62. # Weights converted from elsewhere may not have meta fields.
  63. checkpoint_meta = checkpoint.get('meta', {})
  64. # save the dataset_meta in the model for convenience
  65. if 'dataset_meta' in checkpoint_meta:
  66. # mmdet 3.x, all keys should be lowercase
  67. model.dataset_meta = {
  68. k.lower(): v
  69. for k, v in checkpoint_meta['dataset_meta'].items()
  70. }
  71. elif 'CLASSES' in checkpoint_meta:
  72. # < mmdet 3.x
  73. classes = checkpoint_meta['CLASSES']
  74. model.dataset_meta = {'classes': classes}
  75. else:
  76. warnings.simplefilter('once')
  77. warnings.warn(
  78. 'dataset_meta or class names are not saved in the '
  79. 'checkpoint\'s meta data, use COCO classes by default.')
  80. model.dataset_meta = {'classes': get_classes('coco')}
  81. # Priority: args.palette -> config -> checkpoint
  82. if palette != 'none':
  83. model.dataset_meta['palette'] = palette
  84. else:
  85. test_dataset_cfg = copy.deepcopy(config.test_dataloader.dataset)
  86. # lazy init. We only need the metainfo.
  87. test_dataset_cfg['lazy_init'] = True
  88. metainfo = DATASETS.build(test_dataset_cfg).metainfo
  89. cfg_palette = metainfo.get('palette', None)
  90. if cfg_palette is not None:
  91. model.dataset_meta['palette'] = cfg_palette
  92. else:
  93. if 'palette' not in model.dataset_meta:
  94. warnings.warn(
  95. 'palette does not exist, random is used by default. '
  96. 'You can also set the palette to customize.')
  97. model.dataset_meta['palette'] = 'random'
  98. model.cfg = config # save the config in the model for convenience
  99. model.to(device)
  100. model.eval()
  101. return model
  102. ImagesType = Union[str, np.ndarray, Sequence[str], Sequence[np.ndarray]]
  103. def inference_detector(
  104. model: nn.Module,
  105. imgs: ImagesType,
  106. test_pipeline: Optional[Compose] = None
  107. ) -> Union[DetDataSample, SampleList]:
  108. """Inference image(s) with the detector.
  109. Args:
  110. model (nn.Module): The loaded detector.
  111. imgs (str, ndarray, Sequence[str/ndarray]):
  112. Either image files or loaded images.
  113. test_pipeline (:obj:`Compose`): Test pipeline.
  114. Returns:
  115. :obj:`DetDataSample` or list[:obj:`DetDataSample`]:
  116. If imgs is a list or tuple, the same length list type results
  117. will be returned, otherwise return the detection results directly.
  118. """
  119. if isinstance(imgs, (list, tuple)):
  120. is_batch = True
  121. else:
  122. imgs = [imgs]
  123. is_batch = False
  124. cfg = model.cfg
  125. if test_pipeline is None:
  126. cfg = cfg.copy()
  127. test_pipeline = get_test_pipeline_cfg(cfg)
  128. if isinstance(imgs[0], np.ndarray):
  129. # Calling this method across libraries will result
  130. # in module unregistered error if not prefixed with mmdet.
  131. test_pipeline[0].type = 'mmdet.LoadImageFromNDArray'
  132. test_pipeline = Compose(test_pipeline)
  133. if model.data_preprocessor.device.type == 'cpu':
  134. for m in model.modules():
  135. assert not isinstance(
  136. m, RoIPool
  137. ), 'CPU inference with RoIPool is not supported currently.'
  138. result_list = []
  139. for img in imgs:
  140. # prepare data
  141. if isinstance(img, np.ndarray):
  142. # TODO: remove img_id.
  143. data_ = dict(img=img, img_id=0)
  144. else:
  145. # TODO: remove img_id.
  146. data_ = dict(img_path=img, img_id=0)
  147. # build the data pipeline
  148. data_ = test_pipeline(data_)
  149. data_['inputs'] = [data_['inputs']]
  150. data_['data_samples'] = [data_['data_samples']]
  151. # forward the model
  152. with torch.no_grad():
  153. results = model.test_step(data_)[0]
  154. result_list.append(results)
  155. if not is_batch:
  156. return result_list[0]
  157. else:
  158. return result_list
  159. # TODO: Awaiting refactoring
  160. async def async_inference_detector(model, imgs):
  161. """Async inference image(s) with the detector.
  162. Args:
  163. model (nn.Module): The loaded detector.
  164. img (str | ndarray): Either image files or loaded images.
  165. Returns:
  166. Awaitable detection results.
  167. """
  168. if not isinstance(imgs, (list, tuple)):
  169. imgs = [imgs]
  170. cfg = model.cfg
  171. if isinstance(imgs[0], np.ndarray):
  172. cfg = cfg.copy()
  173. # set loading pipeline type
  174. cfg.data.test.pipeline[0].type = 'LoadImageFromNDArray'
  175. # cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline)
  176. test_pipeline = Compose(cfg.data.test.pipeline)
  177. datas = []
  178. for img in imgs:
  179. # prepare data
  180. if isinstance(img, np.ndarray):
  181. # directly add img
  182. data = dict(img=img)
  183. else:
  184. # add information into dict
  185. data = dict(img_info=dict(filename=img), img_prefix=None)
  186. # build the data pipeline
  187. data = test_pipeline(data)
  188. datas.append(data)
  189. for m in model.modules():
  190. assert not isinstance(
  191. m,
  192. RoIPool), 'CPU inference with RoIPool is not supported currently.'
  193. # We don't restore `torch.is_grad_enabled()` value during concurrent
  194. # inference since execution can overlap
  195. torch.set_grad_enabled(False)
  196. results = await model.aforward_test(data, rescale=True)
  197. return results