選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

147 行
6.2KB

  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')
  7. model = torch.hub.load('ultralytics/yolov5:master', 'custom', 'path/to/yolov5s.onnx') # file from branch
  8. """
  9. import torch
  10. def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  11. """Creates or loads a YOLOv5 model
  12. Arguments:
  13. name (str): model name 'yolov5s' or path 'path/to/best.pt'
  14. pretrained (bool): load pretrained weights into the model
  15. channels (int): number of input channels
  16. classes (int): number of model classes
  17. autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
  18. verbose (bool): print all information to screen
  19. device (str, torch.device, None): device to use for model parameters
  20. Returns:
  21. YOLOv5 model
  22. """
  23. from pathlib import Path
  24. from models.common import AutoShape, DetectMultiBackend
  25. from models.yolo import Model
  26. from utils.downloads import attempt_download
  27. from utils.general import LOGGER, check_requirements, intersect_dicts, logging
  28. from utils.torch_utils import select_device
  29. if not verbose:
  30. LOGGER.setLevel(logging.WARNING)
  31. check_requirements(exclude=('tensorboard', 'thop', 'opencv-python'))
  32. name = Path(name)
  33. path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
  34. try:
  35. device = select_device(device)
  36. if pretrained and channels == 3 and classes == 80:
  37. model = DetectMultiBackend(path, device=device) # download/load FP32 model
  38. # model = models.experimental.attempt_load(path, map_location=device) # download/load FP32 model
  39. else:
  40. cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
  41. model = Model(cfg, channels, classes) # create model
  42. if pretrained:
  43. ckpt = torch.load(attempt_download(path), map_location=device) # load
  44. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  45. csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
  46. model.load_state_dict(csd, strict=False) # load
  47. if len(ckpt['model'].names) == classes:
  48. model.names = ckpt['model'].names # set class names attribute
  49. if autoshape:
  50. model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
  51. return model.to(device)
  52. except Exception as e:
  53. help_url = 'https://github.com/ultralytics/yolov5/issues/36'
  54. s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
  55. raise Exception(s) from e
  56. def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
  57. # YOLOv5 custom or local model
  58. return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
  59. def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  60. # YOLOv5-nano model https://github.com/ultralytics/yolov5
  61. return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
  62. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  63. # YOLOv5-small model https://github.com/ultralytics/yolov5
  64. return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
  65. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  66. # YOLOv5-medium model https://github.com/ultralytics/yolov5
  67. return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
  68. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  69. # YOLOv5-large model https://github.com/ultralytics/yolov5
  70. return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
  71. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  72. # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
  73. return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
  74. def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  75. # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
  76. return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
  77. def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  78. # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
  79. return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
  80. def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  81. # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
  82. return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
  83. def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  84. # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
  85. return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
  86. def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  87. # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
  88. return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
  89. if __name__ == '__main__':
  90. model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
  91. # model = custom(path='path/to/model.pt') # custom
  92. # Verify inference
  93. from pathlib import Path
  94. import numpy as np
  95. from PIL import Image
  96. from utils.general import cv2
  97. imgs = [
  98. 'data/images/zidane.jpg', # filename
  99. Path('data/images/zidane.jpg'), # Path
  100. 'https://ultralytics.com/images/zidane.jpg', # URI
  101. cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
  102. Image.open('data/images/bus.jpg'), # PIL
  103. np.zeros((320, 640, 3))] # numpy
  104. results = model(imgs, size=320) # batched inference
  105. results.print()
  106. results.save()