test.py 5.5 KB

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