hubconf.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5
  4. Usage:
  5. import torch
  6. model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # official model
  7. model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s') # from branch
  8. model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt') # custom/local model
  9. model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local') # local repo
  10. """
  11. import torch
  12. def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  13. """Creates or loads a YOLOv5 model
  14. Arguments:
  15. name (str): model name 'yolov5s' or path 'path/to/best.pt'
  16. pretrained (bool): load pretrained weights into the model
  17. channels (int): number of input channels
  18. classes (int): number of model classes
  19. autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
  20. verbose (bool): print all information to screen
  21. device (str, torch.device, None): device to use for model parameters
  22. Returns:
  23. YOLOv5 model
  24. """
  25. from pathlib import Path
  26. from models.common import AutoShape, DetectMultiBackend
  27. from models.experimental import attempt_load
  28. from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
  29. from utils.downloads import attempt_download
  30. from utils.general import LOGGER, check_requirements, intersect_dicts, logging
  31. from utils.torch_utils import select_device
  32. if not verbose:
  33. LOGGER.setLevel(logging.WARNING)
  34. check_requirements(exclude=('opencv-python', 'tensorboard', 'thop'))
  35. name = Path(name)
  36. path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
  37. try:
  38. device = select_device(device)
  39. if pretrained and channels == 3 and classes == 80:
  40. try:
  41. model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
  42. if autoshape:
  43. if model.pt and isinstance(model.model, ClassificationModel):
  44. LOGGER.warning('WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. '
  45. 'You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224).')
  46. elif model.pt and isinstance(model.model, SegmentationModel):
  47. LOGGER.warning('WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. '
  48. 'You will not be able to run inference with this model.')
  49. else:
  50. model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
  51. except Exception:
  52. model = attempt_load(path, device=device, fuse=False) # arbitrary model
  53. else:
  54. cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
  55. model = DetectionModel(cfg, channels, classes) # create model
  56. if pretrained:
  57. ckpt = torch.load(attempt_download(path), map_location=device) # load
  58. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  59. csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
  60. model.load_state_dict(csd, strict=False) # load
  61. if len(ckpt['model'].names) == classes:
  62. model.names = ckpt['model'].names # set class names attribute
  63. if not verbose:
  64. LOGGER.setLevel(logging.INFO) # reset to default
  65. return model.to(device)
  66. except Exception as e:
  67. help_url = 'https://github.com/ultralytics/yolov5/issues/36'
  68. s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
  69. raise Exception(s) from e
  70. def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
  71. # YOLOv5 custom or local model
  72. return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
  73. def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  74. # YOLOv5-nano model https://github.com/ultralytics/yolov5
  75. return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
  76. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  77. # YOLOv5-small model https://github.com/ultralytics/yolov5
  78. return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
  79. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  80. # YOLOv5-medium model https://github.com/ultralytics/yolov5
  81. return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
  82. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  83. # YOLOv5-large model https://github.com/ultralytics/yolov5
  84. return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
  85. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  86. # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
  87. return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
  88. def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  89. # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
  90. return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
  91. def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  92. # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
  93. return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
  94. def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  95. # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
  96. return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
  97. def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  98. # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
  99. return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
  100. def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  101. # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
  102. return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
  103. if __name__ == '__main__':
  104. import argparse
  105. from pathlib import Path
  106. import numpy as np
  107. from PIL import Image
  108. from utils.general import cv2, print_args
  109. # Argparser
  110. parser = argparse.ArgumentParser()
  111. parser.add_argument('--model', type=str, default='yolov5s', help='model name')
  112. opt = parser.parse_args()
  113. print_args(vars(opt))
  114. # Model
  115. model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
  116. # model = custom(path='path/to/model.pt') # custom
  117. # Images
  118. imgs = [
  119. 'data/images/zidane.jpg', # filename
  120. Path('data/images/zidane.jpg'), # Path
  121. 'https://ultralytics.com/images/zidane.jpg', # URI
  122. cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
  123. Image.open('data/images/bus.jpg'), # PIL
  124. np.zeros((320, 640, 3))] # numpy
  125. # Inference
  126. results = model(imgs, size=320) # batched inference
  127. # Results
  128. results.print()
  129. results.save()