当前位置:   article > 正文

【YoLo】从 PyTorch Hub 加载 YOLOv5_yolov5自定义加载模型

yolov5自定义加载模型

使用 PyTorch Hub 加载 YOLOv5

此示例从 PyTorch Hub 加载预训练的 YOLOv5s 模型,model并传递图像进行推理。'yolov5s'是最轻最快的 YOLOv5 型号。

  1. import torch
  2. # Model
  3. model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
  4. # Image
  5. im = 'https://ultralytics.com/images/zidane.jpg'
  6. # Inference
  7. results = model(im)
  8. results.pandas().xyxy[0]
  9. # xmin ymin xmax ymax confidence class name
  10. # 0 749.50 43.50 1148.0 704.5 0.874023 0 person
  11. # 1 433.50 433.50 517.5 714.5 0.687988 27 tie
  12. # 2 114.75 195.75 1095.0 708.0 0.624512 0 person
  13. # 3 986.00 304.00 1028.0 420.0 0.286865 27 tie

详细示例

此示例显示了PILOpenCV图像源的批量推理。可以打印到控制台,保存到,在支持的环境中显示到屏幕上,并以张量pandas数据帧的形式返回。resultsruns/hub

  1. import cv2
  2. import torch
  3. from PIL import Image
  4. # Model
  5. model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
  6. # Images
  7. for f in 'zidane.jpg', 'bus.jpg':
  8. torch.hub.download_url_to_file('https://ultralytics.com/images/' + f, f) # download 2 images
  9. im1 = Image.open('zidane.jpg') # PIL image
  10. im2 = cv2.imread('bus.jpg')[..., ::-1] # OpenCV image (BGR to RGB)
  11. # Inference
  12. results = model([im1, im2], size=640) # batch of images
  13. # Results
  14. results.print()
  15. results.save() # or .show()
  16. results.xyxy[0] # im1 predictions (tensor)
  17. results.pandas().xyxy[0] # im1 predictions (pandas)
  18. # xmin ymin xmax ymax confidence class name
  19. # 0 749.50 43.50 1148.0 704.5 0.874023 0 person
  20. # 1 433.50 433.50 517.5 714.5 0.687988 27 tie
  21. # 2 114.75 195.75 1095.0 708.0 0.624512 0 person
  22. # 3 986.00 304.00 1028.0 420.0 0.286865 27 tie

 

推理设置

YOLOv5 模型包含各种推理属性,例如置信度阈值IoU 阈值等,可以通过以下方式设置:

  1. model.conf = 0.25 # NMS confidence threshold
  2. iou = 0.45 # NMS IoU threshold
  3. agnostic = False # NMS class-agnostic
  4. multi_label = False # NMS multiple labels per box
  5. classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
  6. max_det = 1000 # maximum number of detections per image
  7. amp = False # Automatic Mixed Precision (AMP) inference
  8. results = model(im, size=320) # custom inference size

设备

模型创建后可以转移到任何设备:

  1. model.cpu() # CPU
  2. model.cuda() # GPU
  3. model.to(device) # i.e. device=torch.device(0)

模型也可以直接在任何device

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', device='cpu')  # load on CPU

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/569580
推荐阅读
相关标签