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.

154 lines
5.6KB

  1. """File for accessing YOLOv5 models via PyTorch Hub https://pytorch.org/hub/ultralytics_yolov5/
  2. Usage:
  3. import torch
  4. model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
  5. """
  6. from pathlib import Path
  7. import torch
  8. from models.yolo import Model
  9. from utils.general import check_requirements, set_logging
  10. from utils.google_utils import attempt_download
  11. from utils.torch_utils import select_device
  12. dependencies = ['torch', 'yaml']
  13. check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
  14. set_logging()
  15. def create(name, pretrained, channels, classes, autoshape):
  16. """Creates a specified YOLOv5 model
  17. Arguments:
  18. name (str): name of model, i.e. 'yolov5s'
  19. pretrained (bool): load pretrained weights into the model
  20. channels (int): number of input channels
  21. classes (int): number of model classes
  22. Returns:
  23. pytorch model
  24. """
  25. config = Path(__file__).parent / 'models' / f'{name}.yaml' # model.yaml path
  26. try:
  27. model = Model(config, channels, classes)
  28. if pretrained:
  29. fname = f'{name}.pt' # checkpoint filename
  30. attempt_download(fname) # download if not found locally
  31. ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
  32. msd = model.state_dict() # model state_dict
  33. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  34. csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
  35. model.load_state_dict(csd, strict=False) # load
  36. if len(ckpt['model'].names) == classes:
  37. model.names = ckpt['model'].names # set class names attribute
  38. if autoshape:
  39. model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  40. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  41. return model.to(device)
  42. except Exception as e:
  43. help_url = 'https://github.com/ultralytics/yolov5/issues/36'
  44. s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url
  45. raise Exception(s) from e
  46. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True):
  47. """YOLOv5-small model from https://github.com/ultralytics/yolov5
  48. Arguments:
  49. pretrained (bool): load pretrained weights into the model, default=False
  50. channels (int): number of input channels, default=3
  51. classes (int): number of model classes, default=80
  52. Returns:
  53. pytorch model
  54. """
  55. return create('yolov5s', pretrained, channels, classes, autoshape)
  56. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True):
  57. """YOLOv5-medium model from https://github.com/ultralytics/yolov5
  58. Arguments:
  59. pretrained (bool): load pretrained weights into the model, default=False
  60. channels (int): number of input channels, default=3
  61. classes (int): number of model classes, default=80
  62. Returns:
  63. pytorch model
  64. """
  65. return create('yolov5m', pretrained, channels, classes, autoshape)
  66. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True):
  67. """YOLOv5-large model from https://github.com/ultralytics/yolov5
  68. Arguments:
  69. pretrained (bool): load pretrained weights into the model, default=False
  70. channels (int): number of input channels, default=3
  71. classes (int): number of model classes, default=80
  72. Returns:
  73. pytorch model
  74. """
  75. return create('yolov5l', pretrained, channels, classes, autoshape)
  76. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True):
  77. """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5
  78. Arguments:
  79. pretrained (bool): load pretrained weights into the model, default=False
  80. channels (int): number of input channels, default=3
  81. classes (int): number of model classes, default=80
  82. Returns:
  83. pytorch model
  84. """
  85. return create('yolov5x', pretrained, channels, classes, autoshape)
  86. def custom(path_or_model='path/to/model.pt', autoshape=True):
  87. """YOLOv5-custom model from https://github.com/ultralytics/yolov5
  88. Arguments (3 options):
  89. path_or_model (str): 'path/to/model.pt'
  90. path_or_model (dict): torch.load('path/to/model.pt')
  91. path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
  92. Returns:
  93. pytorch model
  94. """
  95. model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
  96. if isinstance(model, dict):
  97. model = model['ema' if model.get('ema') else 'model'] # load model
  98. hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
  99. hub_model.load_state_dict(model.float().state_dict()) # load state_dict
  100. hub_model.names = model.names # class names
  101. if autoshape:
  102. hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  103. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  104. return hub_model.to(device)
  105. if __name__ == '__main__':
  106. model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
  107. # model = custom(path_or_model='path/to/model.pt') # custom example
  108. # Verify inference
  109. import numpy as np
  110. from PIL import Image
  111. imgs = [Image.open('data/images/bus.jpg'), # PIL
  112. 'data/images/zidane.jpg', # filename
  113. 'https://github.com/ultralytics/yolov5/raw/master/data/images/bus.jpg', # URI
  114. np.zeros((640, 480, 3))] # numpy
  115. results = model(imgs) # batched inference
  116. results.print()
  117. results.save()