test.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import os
  4. import os.path as osp
  5. import warnings
  6. from copy import deepcopy
  7. from mmengine import ConfigDict
  8. from mmengine.config import Config, DictAction
  9. from mmengine.runner import Runner
  10. from mmdet.engine.hooks.utils import trigger_visualization_hook
  11. from mmdet.evaluation import DumpDetResults
  12. from mmdet.registry import RUNNERS
  13. from mmdet.utils import setup_cache_size_limit_of_dynamo
  14. # TODO: support fuse_conv_bn and format_only
  15. def parse_args():
  16. parser = argparse.ArgumentParser(
  17. description='MMDet test (and eval) a model')
  18. parser.add_argument('config', help='test config file path')
  19. parser.add_argument('checkpoint', help='checkpoint file')
  20. parser.add_argument(
  21. '--work-dir',
  22. help='the directory to save the file containing evaluation metrics')
  23. parser.add_argument(
  24. '--out',
  25. type=str,
  26. help='dump predictions to a pickle file for offline evaluation')
  27. parser.add_argument(
  28. '--show', action='store_true', help='show prediction results')
  29. parser.add_argument(
  30. '--show-dir',
  31. help='directory where painted images will be saved. '
  32. 'If specified, it will be automatically saved '
  33. 'to the work_dir/timestamp/show_dir')
  34. parser.add_argument(
  35. '--wait-time', type=float, default=2, help='the interval of show (s)')
  36. parser.add_argument(
  37. '--cfg-options',
  38. nargs='+',
  39. action=DictAction,
  40. help='override some settings in the used config, the key-value pair '
  41. 'in xxx=yyy format will be merged into config file. If the value to '
  42. 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
  43. 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
  44. 'Note that the quotation marks are necessary and that no white space '
  45. 'is allowed.')
  46. parser.add_argument(
  47. '--launcher',
  48. choices=['none', 'pytorch', 'slurm', 'mpi'],
  49. default='none',
  50. help='job launcher')
  51. parser.add_argument('--tta', action='store_true')
  52. # When using PyTorch version >= 2.0.0, the `torch.distributed.launch`
  53. # will pass the `--local-rank` parameter to `tools/train.py` instead
  54. # of `--local_rank`.
  55. parser.add_argument('--local_rank', '--local-rank', type=int, default=0)
  56. args = parser.parse_args()
  57. if 'LOCAL_RANK' not in os.environ:
  58. os.environ['LOCAL_RANK'] = str(args.local_rank)
  59. return args
  60. def main():
  61. args = parse_args()
  62. # Reduce the number of repeated compilations and improve
  63. # testing speed.
  64. setup_cache_size_limit_of_dynamo()
  65. # load config
  66. cfg = Config.fromfile(args.config)
  67. cfg.launcher = args.launcher
  68. if args.cfg_options is not None:
  69. cfg.merge_from_dict(args.cfg_options)
  70. # work_dir is determined in this priority: CLI > segment in file > filename
  71. if args.work_dir is not None:
  72. # update configs according to CLI args if args.work_dir is not None
  73. cfg.work_dir = args.work_dir
  74. elif cfg.get('work_dir', None) is None:
  75. # use config filename as default work_dir if cfg.work_dir is None
  76. cfg.work_dir = osp.join('./work_dirs',
  77. osp.splitext(osp.basename(args.config))[0])
  78. cfg.load_from = args.checkpoint
  79. if args.show or args.show_dir:
  80. cfg = trigger_visualization_hook(cfg, args)
  81. if args.tta:
  82. if 'tta_model' not in cfg:
  83. warnings.warn('Cannot find ``tta_model`` in config, '
  84. 'we will set it as default.')
  85. cfg.tta_model = dict(
  86. type='DetTTAModel',
  87. tta_cfg=dict(
  88. nms=dict(type='nms', iou_threshold=0.5), max_per_img=100))
  89. if 'tta_pipeline' not in cfg:
  90. warnings.warn('Cannot find ``tta_pipeline`` in config, '
  91. 'we will set it as default.')
  92. test_data_cfg = cfg.test_dataloader.dataset
  93. while 'dataset' in test_data_cfg:
  94. test_data_cfg = test_data_cfg['dataset']
  95. cfg.tta_pipeline = deepcopy(test_data_cfg.pipeline)
  96. flip_tta = dict(
  97. type='TestTimeAug',
  98. transforms=[
  99. [
  100. dict(type='RandomFlip', prob=1.),
  101. dict(type='RandomFlip', prob=0.)
  102. ],
  103. [
  104. dict(
  105. type='PackDetInputs',
  106. meta_keys=('img_id', 'img_path', 'ori_shape',
  107. 'img_shape', 'scale_factor', 'flip',
  108. 'flip_direction'))
  109. ],
  110. ])
  111. cfg.tta_pipeline[-1] = flip_tta
  112. cfg.model = ConfigDict(**cfg.tta_model, module=cfg.model)
  113. cfg.test_dataloader.dataset.pipeline = cfg.tta_pipeline
  114. # build the runner from config
  115. if 'runner_type' not in cfg:
  116. # build the default runner
  117. runner = Runner.from_cfg(cfg)
  118. else:
  119. # build customized runner from the registry
  120. # if 'runner_type' is set in the cfg
  121. runner = RUNNERS.build(cfg)
  122. # add `DumpResults` dummy metric
  123. if args.out is not None:
  124. assert args.out.endswith(('.pkl', '.pickle')), \
  125. 'The dump file must be a pkl file.'
  126. runner.test_evaluator.metrics.append(
  127. DumpDetResults(out_file_path=args.out))
  128. # start testing
  129. runner.test()
  130. if __name__ == '__main__':
  131. main()