You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 line
5.5KB

  1. """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
  2. Usage:
  3. import torch
  4. model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
  5. """
  6. import torch
  7. def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  8. """Creates a specified YOLOv5 model
  9. Arguments:
  10. name (str): name of model, i.e. 'yolov5s'
  11. pretrained (bool): load pretrained weights into the model
  12. channels (int): number of input channels
  13. classes (int): number of model classes
  14. autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
  15. verbose (bool): print all information to screen
  16. device (str, torch.device, None): device to use for model parameters
  17. Returns:
  18. YOLOv5 pytorch model
  19. """
  20. from pathlib import Path
  21. from models.yolo import Model, attempt_load
  22. from utils.general import check_requirements, set_logging
  23. from utils.google_utils import attempt_download
  24. from utils.torch_utils import select_device
  25. file = Path(__file__).absolute()
  26. check_requirements(requirements=file.parent / 'requirements.txt', exclude=('tensorboard', 'thop', 'opencv-python'))
  27. set_logging(verbose=verbose)
  28. save_dir = Path('') if str(name).endswith('.pt') else file.parent
  29. path = (save_dir / name).with_suffix('.pt') # checkpoint path
  30. try:
  31. device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device)
  32. if pretrained and channels == 3 and classes == 80:
  33. model = attempt_load(path, map_location=device) # download/load FP32 model
  34. else:
  35. cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
  36. model = Model(cfg, channels, classes) # create model
  37. if pretrained:
  38. ckpt = torch.load(attempt_download(path), map_location=device) # load
  39. msd = model.state_dict() # model state_dict
  40. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  41. csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
  42. model.load_state_dict(csd, strict=False) # load
  43. if len(ckpt['model'].names) == classes:
  44. model.names = ckpt['model'].names # set class names attribute
  45. if autoshape:
  46. model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  47. return model.to(device)
  48. except Exception as e:
  49. help_url = 'https://github.com/ultralytics/yolov5/issues/36'
  50. s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url
  51. raise Exception(s) from e
  52. def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None):
  53. # YOLOv5 custom or local model
  54. return _create(path, autoshape=autoshape, verbose=verbose, device=device)
  55. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  56. # YOLOv5-small model https://github.com/ultralytics/yolov5
  57. return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device)
  58. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  59. # YOLOv5-medium model https://github.com/ultralytics/yolov5
  60. return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device)
  61. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  62. # YOLOv5-large model https://github.com/ultralytics/yolov5
  63. return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device)
  64. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  65. # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
  66. return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device)
  67. def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  68. # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
  69. return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device)
  70. def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  71. # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
  72. return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device)
  73. def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  74. # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
  75. return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device)
  76. def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  77. # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
  78. return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device)
  79. if __name__ == '__main__':
  80. model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
  81. # model = custom(path='path/to/model.pt') # custom
  82. # Verify inference
  83. import cv2
  84. import numpy as np
  85. from PIL import Image
  86. imgs = ['data/images/zidane.jpg', # filename
  87. 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI
  88. cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
  89. Image.open('data/images/bus.jpg'), # PIL
  90. np.zeros((320, 640, 3))] # numpy
  91. results = model(imgs) # batched inference
  92. results.print()
  93. results.save()