Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

150 lines
5.4KB

  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. state_dict = ckpt['model'].float().state_dict() # to FP32
  33. state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].shape == v.shape} # filter
  34. model.load_state_dict(state_dict, strict=False) # load
  35. if len(ckpt['model'].names) == classes:
  36. model.names = ckpt['model'].names # set class names attribute
  37. if autoshape:
  38. model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  39. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  40. return model.to(device)
  41. except Exception as e:
  42. help_url = 'https://github.com/ultralytics/yolov5/issues/36'
  43. s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url
  44. raise Exception(s) from e
  45. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True):
  46. """YOLOv5-small model from https://github.com/ultralytics/yolov5
  47. Arguments:
  48. pretrained (bool): load pretrained weights into the model, default=False
  49. channels (int): number of input channels, default=3
  50. classes (int): number of model classes, default=80
  51. Returns:
  52. pytorch model
  53. """
  54. return create('yolov5s', pretrained, channels, classes, autoshape)
  55. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True):
  56. """YOLOv5-medium model from https://github.com/ultralytics/yolov5
  57. Arguments:
  58. pretrained (bool): load pretrained weights into the model, default=False
  59. channels (int): number of input channels, default=3
  60. classes (int): number of model classes, default=80
  61. Returns:
  62. pytorch model
  63. """
  64. return create('yolov5m', pretrained, channels, classes, autoshape)
  65. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True):
  66. """YOLOv5-large model from https://github.com/ultralytics/yolov5
  67. Arguments:
  68. pretrained (bool): load pretrained weights into the model, default=False
  69. channels (int): number of input channels, default=3
  70. classes (int): number of model classes, default=80
  71. Returns:
  72. pytorch model
  73. """
  74. return create('yolov5l', pretrained, channels, classes, autoshape)
  75. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True):
  76. """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5
  77. Arguments:
  78. pretrained (bool): load pretrained weights into the model, default=False
  79. channels (int): number of input channels, default=3
  80. classes (int): number of model classes, default=80
  81. Returns:
  82. pytorch model
  83. """
  84. return create('yolov5x', pretrained, channels, classes, autoshape)
  85. def custom(path_or_model='path/to/model.pt', autoshape=True):
  86. """YOLOv5-custom model from https://github.com/ultralytics/yolov5
  87. Arguments (3 options):
  88. path_or_model (str): 'path/to/model.pt'
  89. path_or_model (dict): torch.load('path/to/model.pt')
  90. path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
  91. Returns:
  92. pytorch model
  93. """
  94. model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
  95. if isinstance(model, dict):
  96. model = model['ema' if model.get('ema') else 'model'] # load model
  97. hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
  98. hub_model.load_state_dict(model.float().state_dict()) # load state_dict
  99. hub_model.names = model.names # class names
  100. return hub_model.autoshape() if autoshape else hub_model
  101. if __name__ == '__main__':
  102. model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
  103. # model = custom(path_or_model='path/to/model.pt') # custom example
  104. # Verify inference
  105. import numpy as np
  106. from PIL import Image
  107. imgs = [Image.open('data/images/bus.jpg'), # PIL
  108. 'data/images/zidane.jpg', # filename
  109. 'https://github.com/ultralytics/yolov5/raw/master/data/images/bus.jpg', # URI
  110. np.zeros((640, 480, 3))] # numpy
  111. results = model(imgs) # batched inference
  112. results.print()
  113. results.save()