hubconf.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # YOLOv5 🚀 by Ultralytics, AGPL-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') # official model
  7. model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s') # from branch
  8. model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt') # custom/local model
  9. model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local') # local repo
  10. """
  11. import torch
  12. def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
  13. """
  14. Creates or loads a YOLOv5 model.
  15. Arguments:
  16. name (str): model name 'yolov5s' or path 'path/to/best.pt'
  17. pretrained (bool): load pretrained weights into the model
  18. channels (int): number of input channels
  19. classes (int): number of model classes
  20. autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
  21. verbose (bool): print all information to screen
  22. device (str, torch.device, None): device to use for model parameters
  23. Returns:
  24. YOLOv5 model
  25. """
  26. from pathlib import Path
  27. from models.common import AutoShape, DetectMultiBackend
  28. from models.experimental import attempt_load
  29. from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
  30. from utils.downloads import attempt_download
  31. from utils.general import LOGGER, ROOT, check_requirements, intersect_dicts, logging
  32. from utils.torch_utils import select_device
  33. if not verbose:
  34. LOGGER.setLevel(logging.WARNING)
  35. check_requirements(ROOT / "requirements.txt", exclude=("opencv-python", "tensorboard", "thop"))
  36. name = Path(name)
  37. path = name.with_suffix(".pt") if name.suffix == "" and not name.is_dir() else name # checkpoint path
  38. try:
  39. device = select_device(device)
  40. if pretrained and channels == 3 and classes == 80:
  41. try:
  42. model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
  43. if autoshape:
  44. if model.pt and isinstance(model.model, ClassificationModel):
  45. LOGGER.warning(
  46. "WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. "
  47. "You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224)."
  48. )
  49. elif model.pt and isinstance(model.model, SegmentationModel):
  50. LOGGER.warning(
  51. "WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. "
  52. "You will not be able to run inference with this model."
  53. )
  54. else:
  55. model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
  56. except Exception:
  57. model = attempt_load(path, device=device, fuse=False) # arbitrary model
  58. else:
  59. cfg = list((Path(__file__).parent / "models").rglob(f"{path.stem}.yaml"))[0] # model.yaml path
  60. model = DetectionModel(cfg, channels, classes) # create model
  61. if pretrained:
  62. ckpt = torch.load(attempt_download(path), map_location=device) # load
  63. csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
  64. csd = intersect_dicts(csd, model.state_dict(), exclude=["anchors"]) # intersect
  65. model.load_state_dict(csd, strict=False) # load
  66. if len(ckpt["model"].names) == classes:
  67. model.names = ckpt["model"].names # set class names attribute
  68. if not verbose:
  69. LOGGER.setLevel(logging.INFO) # reset to default
  70. return model.to(device)
  71. except Exception as e:
  72. help_url = "https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading"
  73. s = f"{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help."
  74. raise Exception(s) from e
  75. def custom(path="path/to/model.pt", autoshape=True, _verbose=True, device=None):
  76. """Loads a custom or local YOLOv5 model from a given path with optional autoshaping and device specification."""
  77. return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
  78. def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  79. """Instantiates the YOLOv5-nano model with options for pretraining, input channels, class count, autoshaping,
  80. verbosity, and device.
  81. """
  82. return _create("yolov5n", pretrained, channels, classes, autoshape, _verbose, device)
  83. def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  84. """Creates YOLOv5-small model with options for pretraining, input channels, class count, autoshaping, verbosity, and
  85. device.
  86. """
  87. return _create("yolov5s", pretrained, channels, classes, autoshape, _verbose, device)
  88. def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  89. """Instantiates the YOLOv5-medium model with customizable pretraining, channel count, class count, autoshaping,
  90. verbosity, and device.
  91. """
  92. return _create("yolov5m", pretrained, channels, classes, autoshape, _verbose, device)
  93. def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  94. """Creates YOLOv5-large model with options for pretraining, channels, classes, autoshaping, verbosity, and device
  95. selection.
  96. """
  97. return _create("yolov5l", pretrained, channels, classes, autoshape, _verbose, device)
  98. def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  99. """Instantiates the YOLOv5-xlarge model with customizable pretraining, channel count, class count, autoshaping,
  100. verbosity, and device.
  101. """
  102. return _create("yolov5x", pretrained, channels, classes, autoshape, _verbose, device)
  103. def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  104. """Creates YOLOv5-nano-P6 model with options for pretraining, channels, classes, autoshaping, verbosity, and
  105. device.
  106. """
  107. return _create("yolov5n6", pretrained, channels, classes, autoshape, _verbose, device)
  108. def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  109. """Instantiate YOLOv5-small-P6 model with options for pretraining, input channels, number of classes, autoshaping,
  110. verbosity, and device selection.
  111. """
  112. return _create("yolov5s6", pretrained, channels, classes, autoshape, _verbose, device)
  113. def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  114. """Creates YOLOv5-medium-P6 model with options for pretraining, channel count, class count, autoshaping, verbosity,
  115. and device.
  116. """
  117. return _create("yolov5m6", pretrained, channels, classes, autoshape, _verbose, device)
  118. def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  119. """Instantiates the YOLOv5-large-P6 model with customizable pretraining, channel and class counts, autoshaping,
  120. verbosity, and device selection.
  121. """
  122. return _create("yolov5l6", pretrained, channels, classes, autoshape, _verbose, device)
  123. def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
  124. """Creates YOLOv5-xlarge-P6 model with options for pretraining, channels, classes, autoshaping, verbosity, and
  125. device.
  126. """
  127. return _create("yolov5x6", pretrained, channels, classes, autoshape, _verbose, device)
  128. if __name__ == "__main__":
  129. import argparse
  130. from pathlib import Path
  131. import numpy as np
  132. from PIL import Image
  133. from utils.general import cv2, print_args
  134. # Argparser
  135. parser = argparse.ArgumentParser()
  136. parser.add_argument("--model", type=str, default="yolov5s", help="model name")
  137. opt = parser.parse_args()
  138. print_args(vars(opt))
  139. # Model
  140. model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
  141. # model = custom(path='path/to/model.pt') # custom
  142. # Images
  143. imgs = [
  144. "data/images/zidane.jpg", # filename
  145. Path("data/images/zidane.jpg"), # Path
  146. "https://ultralytics.com/images/zidane.jpg", # URI
  147. cv2.imread("data/images/bus.jpg")[:, :, ::-1], # OpenCV
  148. Image.open("data/images/bus.jpg"), # PIL
  149. np.zeros((320, 640, 3)),
  150. ] # numpy
  151. # Inference
  152. results = model(imgs, size=320) # batched inference
  153. # Results
  154. results.print()
  155. results.save()