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.

149 satır
5.3KB

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