yolov5入门笔记

267 阅读2分钟
  1. 安装
git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

2. 推理

import torch

if __name__ == "__main__":
    # Model
    model = torch.hub.load("ultralytics/yolov5", "yolov5l")  # or yolov5n - yolov5x6, custom
    # Images
    img = "data/images/zidane.jpg"  # or file, Path, PIL, OpenCV, numpy, list
    # Inference
    results = model(img)
    # Results
    results.print()  # or .show(), .save(), .crop(), .pandas(), etc.
  1. rate limit exceeded 问题

在执行上诉代码时,在torch.hub.load("ultralytics/yolov5", "yolov5l")遇到下载报错 urllib.error.HTTPError: HTTP Error 403: rate limit exceeded此博客中找到解决方案如下:

  • 发生在 torch.hub.load 函数调用时,Torch Hub 尝试从github仓库加载模型,但由于 GitHub API 超过了速率限制导致无法下载. 因为你未配置 GitHub 访问令牌,或使用了未认证的公共 API 访问
  • 配置 GitHub 访问令牌以绕过速率限制
    • 登录 GitHub
    • 转到 Settings > Developer settings > Personal access tokens
    • 选择 Generate new token (classic),并勾选 repo 和 read:packages 权限
    • 复制生成的令牌
  • 在本机环境变量配置 GITHUB_TOKEN
    • nano ~/.bash_profile 添加以下内容
    • export GITHUB_TOKEN=<你的访问令牌>
    • source ~/.bash_profile
  1. 执行结果

在代码同路径下下载有 yolov5l.pt 模型文件

Using cache found in /Users/morningcat/.cache/torch/hub/ultralytics_yolov5_master
YOLOv5 🚀 2025-3-4 Python-3.8.20 torch-2.2.2 CPU

Downloading https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l.pt to yolov5l.pt...
100%|██████████| 89.3M/89.3M [00:08<00:00, 10.9MB/s]

Fusing layers... 
YOLOv5l summary: 367 layers, 46533693 parameters, 0 gradients, 109.0 GFLOPs
Adding AutoShape... 
image 1/1: 720x1280 2 persons, 1 tie
Speed: 24.5ms pre-process, 1042.3ms inference, 2.1ms NMS per image at shape (1, 3, 384, 640)

5. yolov5 模型对比

image.png https://github.com/ultralytics/yolov5/releases

  1. 环境设置完成后,您就可以开始训练、验证、执行推理并导出YOLOv5 模型
# Train a model on your data
python train.py

# Validate the trained model for Precision, Recall, and mAP
python val.py --weights yolov5s.pt

# Run inference using the trained model on your images or videos
python detect.py --weights yolov5s.pt --source path/to/images

# Export the trained model to other formats for deployment
python export.py --weights yolov5s.pt --include onnx coreml tflite