demo.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import os
  3. import urllib
  4. from argparse import ArgumentParser
  5. import mmcv
  6. import torch
  7. from mmengine.logging import print_log
  8. from mmengine.utils import ProgressBar, scandir
  9. from mmdet.apis import inference_detector, init_detector
  10. from mmdet.registry import VISUALIZERS
  11. from mmdet.utils import register_all_modules
  12. IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif',
  13. '.tiff', '.webp')
  14. def get_file_list(source_root: str) -> [list, dict]:
  15. """Get file list.
  16. Args:
  17. source_root (str): image or video source path
  18. Return:
  19. source_file_path_list (list): A list for all source file.
  20. source_type (dict): Source type: file or url or dir.
  21. """
  22. is_dir = os.path.isdir(source_root)
  23. is_url = source_root.startswith(('http:/', 'https:/'))
  24. is_file = os.path.splitext(source_root)[-1].lower() in IMG_EXTENSIONS
  25. source_file_path_list = []
  26. if is_dir:
  27. # when input source is dir
  28. for file in scandir(source_root, IMG_EXTENSIONS, recursive=True):
  29. source_file_path_list.append(os.path.join(source_root, file))
  30. elif is_url:
  31. # when input source is url
  32. filename = os.path.basename(
  33. urllib.parse.unquote(source_root).split('?')[0])
  34. file_save_path = os.path.join(os.getcwd(), filename)
  35. print(f'Downloading source file to {file_save_path}')
  36. torch.hub.download_url_to_file(source_root, file_save_path)
  37. source_file_path_list = [file_save_path]
  38. elif is_file:
  39. # when input source is single image
  40. source_file_path_list = [source_root]
  41. else:
  42. print('Cannot find image file.')
  43. source_type = dict(is_dir=is_dir, is_url=is_url, is_file=is_file)
  44. return source_file_path_list, source_type
  45. def parse_args():
  46. parser = ArgumentParser()
  47. parser.add_argument(
  48. 'img', help='Image path, include image file, dir and URL.')
  49. parser.add_argument('config', help='Config file')
  50. parser.add_argument('checkpoint', help='Checkpoint file')
  51. parser.add_argument(
  52. '--out-dir', default='./output', help='Path to output file')
  53. parser.add_argument(
  54. '--device', default='cuda:0', help='Device used for inference')
  55. parser.add_argument(
  56. '--show', action='store_true', help='Show the detection results')
  57. parser.add_argument(
  58. '--score-thr', type=float, default=0.3, help='Bbox score threshold')
  59. parser.add_argument(
  60. '--dataset', type=str, help='dataset name to load the text embedding')
  61. parser.add_argument(
  62. '--class-name', nargs='+', type=str, help='custom class names')
  63. args = parser.parse_args()
  64. return args
  65. def main():
  66. args = parse_args()
  67. # register all modules in mmdet into the registries
  68. register_all_modules()
  69. # build the model from a config file and a checkpoint file
  70. model = init_detector(args.config, args.checkpoint, device=args.device)
  71. if not os.path.exists(args.out_dir) and not args.show:
  72. os.mkdir(args.out_dir)
  73. # init visualizer
  74. visualizer = VISUALIZERS.build(model.cfg.visualizer)
  75. visualizer.dataset_meta = model.dataset_meta
  76. # get file list
  77. files, source_type = get_file_list(args.img)
  78. from detic.utils import (get_class_names, get_text_embeddings,
  79. reset_cls_layer_weight)
  80. # class name embeddings
  81. if args.class_name:
  82. dataset_classes = args.class_name
  83. elif args.dataset:
  84. dataset_classes = get_class_names(args.dataset)
  85. embedding = get_text_embeddings(
  86. dataset=args.dataset, custom_vocabulary=args.class_name)
  87. visualizer.dataset_meta['classes'] = dataset_classes
  88. reset_cls_layer_weight(model, embedding)
  89. # start detector inference
  90. progress_bar = ProgressBar(len(files))
  91. for file in files:
  92. result = inference_detector(model, file)
  93. img = mmcv.imread(file)
  94. img = mmcv.imconvert(img, 'bgr', 'rgb')
  95. if source_type['is_dir']:
  96. filename = os.path.relpath(file, args.img).replace('/', '_')
  97. else:
  98. filename = os.path.basename(file)
  99. out_file = None if args.show else os.path.join(args.out_dir, filename)
  100. progress_bar.update()
  101. visualizer.add_datasample(
  102. filename,
  103. img,
  104. data_sample=result,
  105. draw_gt=False,
  106. show=args.show,
  107. wait_time=0,
  108. out_file=out_file,
  109. pred_score_thr=args.score_thr)
  110. if not args.show:
  111. print_log(
  112. f'\nResults have been saved at {os.path.abspath(args.out_dir)}')
  113. if __name__ == '__main__':
  114. main()