test.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import os
  4. import os.path as osp
  5. import mmengine
  6. from mmengine.config import Config, DictAction
  7. from mmengine.hooks import Hook
  8. from mmengine.runner import Runner
  9. def parse_args():
  10. parser = argparse.ArgumentParser(
  11. description='MMPose test (and eval) model')
  12. parser.add_argument('config', help='test config file path')
  13. parser.add_argument('checkpoint', help='checkpoint file')
  14. parser.add_argument(
  15. '--work-dir', help='the directory to save evaluation results')
  16. parser.add_argument('--out', help='the file to save metric results.')
  17. parser.add_argument(
  18. '--dump',
  19. type=str,
  20. help='dump predictions to a pickle file for offline evaluation')
  21. parser.add_argument(
  22. '--cfg-options',
  23. nargs='+',
  24. action=DictAction,
  25. default={},
  26. help='override some settings in the used config, the key-value pair '
  27. 'in xxx=yyy format will be merged into config file. For example, '
  28. "'--cfg-options model.backbone.depth=18 model.backbone.with_cp=True'")
  29. parser.add_argument(
  30. '--show-dir',
  31. help='directory where the visualization images will be saved.')
  32. parser.add_argument(
  33. '--show',
  34. action='store_true',
  35. help='whether to display the prediction results in a window.')
  36. parser.add_argument(
  37. '--interval',
  38. type=int,
  39. default=1,
  40. help='visualize per interval samples.')
  41. parser.add_argument(
  42. '--wait-time',
  43. type=float,
  44. default=1,
  45. help='display time of every window. (second)')
  46. parser.add_argument(
  47. '--launcher',
  48. choices=['none', 'pytorch', 'slurm', 'mpi'],
  49. default='none',
  50. help='job launcher')
  51. parser.add_argument('--local_rank', type=int, default=0)
  52. args = parser.parse_args()
  53. if 'LOCAL_RANK' not in os.environ:
  54. os.environ['LOCAL_RANK'] = str(args.local_rank)
  55. return args
  56. def merge_args(cfg, args):
  57. """Merge CLI arguments to config."""
  58. # -------------------- visualization --------------------
  59. if args.show or (args.show_dir is not None):
  60. assert 'visualization' in cfg.default_hooks, \
  61. 'PoseVisualizationHook is not set in the ' \
  62. '`default_hooks` field of config. Please set ' \
  63. '`visualization=dict(type="PoseVisualizationHook")`'
  64. cfg.default_hooks.visualization.enable = True
  65. cfg.default_hooks.visualization.show = args.show
  66. if args.show:
  67. cfg.default_hooks.visualization.wait_time = args.wait_time
  68. cfg.default_hooks.visualization.out_dir = args.show_dir
  69. cfg.default_hooks.visualization.interval = args.interval
  70. # -------------------- Dump predictions --------------------
  71. if args.dump is not None:
  72. assert args.dump.endswith(('.pkl', '.pickle')), \
  73. 'The dump file must be a pkl file.'
  74. dump_metric = dict(type='DumpResults', out_file_path=args.dump)
  75. if isinstance(cfg.test_evaluator, (list, tuple)):
  76. cfg.test_evaluator = list(cfg.test_evaluator).append(dump_metric)
  77. else:
  78. cfg.test_evaluator = [cfg.test_evaluator, dump_metric]
  79. return cfg
  80. def main():
  81. args = parse_args()
  82. # load config
  83. cfg = Config.fromfile(args.config)
  84. cfg = merge_args(cfg, args)
  85. cfg.launcher = args.launcher
  86. if args.cfg_options is not None:
  87. cfg.merge_from_dict(args.cfg_options)
  88. # work_dir is determined in this priority: CLI > segment in file > filename
  89. if args.work_dir is not None:
  90. # update configs according to CLI args if args.work_dir is not None
  91. cfg.work_dir = args.work_dir
  92. elif cfg.get('work_dir', None) is None:
  93. # use config filename as default work_dir if cfg.work_dir is None
  94. cfg.work_dir = osp.join('./work_dirs',
  95. osp.splitext(osp.basename(args.config))[0])
  96. cfg.load_from = args.checkpoint
  97. # build the runner from config
  98. runner = Runner.from_cfg(cfg)
  99. if args.out:
  100. class SaveMetricHook(Hook):
  101. def after_test_epoch(self, _, metrics=None):
  102. if metrics is not None:
  103. mmengine.dump(metrics, args.out)
  104. runner.register_hook(SaveMetricHook(), 'LOWEST')
  105. # start testing
  106. runner.test()
  107. if __name__ == '__main__':
  108. main()