hubconf.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 custom(path_or_model='path/to/model.pt', autoshape=True):
  47. """YOLOv5-custom model https://github.com/ultralytics/yolov5
  48. Arguments (3 options):
  49. path_or_model (str): 'path/to/model.pt'
  50. path_or_model (dict): torch.load('path/to/model.pt')
  51. path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
  52. Returns:
  53. pytorch model
  54. """
  55. model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
  56. if isinstance(model, dict):
  57. model = model['ema' if model.get('ema') else 'model'] # load model
  58. hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
  59. hub_model.load_state_dict(model.float().state_dict()) # load state_dict
  60. hub_model.names = model.names # class names
  61. if autoshape:
  62. hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
  63. device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
  64. return hub_model.to(device)
  65. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True):
  66. # YOLOv5-small model https://github.com/ultralytics/yolov5
  67. return create('yolov5s', pretrained, channels, classes, autoshape)
  68. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True):
  69. # YOLOv5-medium model https://github.com/ultralytics/yolov5
  70. return create('yolov5m', pretrained, channels, classes, autoshape)
  71. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True):
  72. # YOLOv5-large model https://github.com/ultralytics/yolov5
  73. return create('yolov5l', pretrained, channels, classes, autoshape)
  74. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True):
  75. # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
  76. return create('yolov5x', pretrained, channels, classes, autoshape)
  77. def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True):
  78. # YOLOv5-small model https://github.com/ultralytics/yolov5
  79. return create('yolov5s6', pretrained, channels, classes, autoshape)
  80. def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True):
  81. # YOLOv5-medium model https://github.com/ultralytics/yolov5
  82. return create('yolov5m6', pretrained, channels, classes, autoshape)
  83. def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True):
  84. # YOLOv5-large model https://github.com/ultralytics/yolov5
  85. return create('yolov5l6', pretrained, channels, classes, autoshape)
  86. def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True):
  87. # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
  88. return create('yolov5x6', pretrained, channels, classes, autoshape)
  89. if __name__ == '__main__':
  90. model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
  91. # model = custom(path_or_model='path/to/model.pt') # custom example
  92. # Verify inference
  93. import numpy as np
  94. from PIL import Image
  95. imgs = [Image.open('data/images/bus.jpg'), # PIL
  96. 'data/images/zidane.jpg', # filename
  97. 'https://github.com/ultralytics/yolov5/raw/master/data/images/bus.jpg', # URI
  98. np.zeros((640, 480, 3))] # numpy
  99. results = model(imgs) # batched inference
  100. results.print()
  101. results.save()