想要用YOLOv5训练自己的目标检测模型,首先需要搭建好开发环境。我推荐使用Python 3.8或以上版本,这个版本在兼容性和稳定性方面表现都很不错。如果你是新手,建议直接安装Anaconda,它能帮你轻松管理Python环境和各种依赖包。
安装完Python环境后,我们需要准备几个关键工具:
安装这些工具非常简单,打开命令行(Windows用户用CMD或PowerShell,Mac/Linux用户用终端),依次执行以下命令:
bash复制pip install torch torchvision torchaudio
pip install opencv-python
pip install labelimg
这里有个小技巧:如果你有NVIDIA显卡,建议安装支持CUDA的PyTorch版本,可以大幅提升训练速度。安装命令稍微有些不同:
bash复制pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
安装完成后,可以通过以下命令验证是否安装成功:
python复制import torch
print(torch.cuda.is_available()) # 应该返回True
import cv2
print(cv2.__version__) # 应该显示版本号
制作自定义数据集的第一步是收集素材。我建议从拍摄视频开始,因为视频可以轻松提取出大量图像帧。比如你想做一个宠物检测器,可以拍一段你家猫狗活动的视频;如果想做特定物品检测,可以拍摄该物品在不同角度、光照条件下的视频。
用OpenCV提取视频帧的Python脚本如下:
python复制import cv2
video_path = 'your_video.mp4' # 替换为你的视频路径
output_dir = 'frames' # 保存帧图像的文件夹
os.makedirs(output_dir, exist_ok=True)
cap = cv2.VideoCapture(video_path)
frame_count = 0
save_interval = 10 # 每10帧保存一张
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if frame_count % save_interval == 0:
frame_path = os.path.join(output_dir, f"frame_{frame_count:04d}.jpg")
cv2.imwrite(frame_path, frame)
frame_count += 1
cap.release()
print(f"共提取了{frame_count//save_interval}张图像")
有了图像素材后,就该进行标注了。LabelImg是最常用的标注工具之一,使用起来非常简单:
labelimg回车标注时要注意几个关键点:
标注完成后,建议将数据集按8:2的比例分为训练集和验证集。可以手动分,也可以用Python脚本自动分:
python复制import os
import random
import shutil
dataset_dir = 'dataset'
images_dir = os.path.join(dataset_dir, 'images')
labels_dir = os.path.join(dataset_dir, 'labels')
# 创建子目录
for subset in ['train', 'val']:
os.makedirs(os.path.join(images_dir, subset), exist_ok=True)
os.makedirs(os.path.join(labels_dir, subset), exist_ok=True)
# 获取所有图像文件
image_files = [f for f in os.listdir(images_dir) if f.endswith('.jpg')]
random.shuffle(image_files)
# 按比例分割
split_idx = int(0.8 * len(image_files))
train_files = image_files[:split_idx]
val_files = image_files[split_idx:]
# 移动文件
for file in train_files:
shutil.move(os.path.join(images_dir, file), os.path.join(images_dir, 'train', file))
label_file = file.replace('.jpg', '.txt')
shutil.move(os.path.join(labels_dir, label_file), os.path.join(labels_dir, 'train', label_file))
for file in val_files:
shutil.move(os.path.join(images_dir, file), os.path.join(images_dir, 'val', file))
label_file = file.replace('.jpg', '.txt')
shutil.move(os.path.join(labels_dir, label_file), os.path.join(labels_dir, 'val', label_file))
首先从GitHub克隆YOLOv5的官方仓库:
bash复制git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
YOLOv5提供了多个预训练模型,从小型到大型依次是:
对于初学者,建议从yolov5s开始,它在准确率和速度之间取得了不错的平衡。
在yolov5/data目录下创建你的数据集配置文件,比如my_data.yaml:
yaml复制# 训练和验证图像路径
train: ../dataset/images/train
val: ../dataset/images/val
# 类别数量
nc: 1
# 类别名称
names: ['cat'] # 替换为你的类别名称
训练命令的基本格式如下:
bash复制python train.py --img 640 --batch 16 --epochs 100 --data data/my_data.yaml --weights yolov5s.pt --device 0
关键参数说明:
--img 640: 输入图像尺寸--batch 16: 批处理大小,根据GPU显存调整--epochs 100: 训练轮数--data: 数据集配置文件路径--weights: 预训练模型--device 0: 使用GPU 0,如果是CPU则设为'cpu'训练过程中会实时显示各项指标,包括损失函数值、精确度、召回率等。训练完成后,模型会保存在runs/train/exp/weights/目录下,其中best.pt是验证集上表现最好的模型。
训练完成后,YOLOv5会自动生成一系列评估图表,保存在runs/train/exp目录下。最重要的几个文件是:
可以通过这些图表直观地了解模型的表现。如果发现模型表现不佳,可以考虑:
使用训练好的模型进行预测非常简单:
bash复制python detect.py --weights runs/train/exp/weights/best.pt --source test_image.jpg --conf 0.25
参数说明:
--weights: 训练好的模型路径--source: 测试图像或视频路径--conf: 置信度阈值,高于此值的检测结果才会显示如果想测试视频或摄像头实时检测:
bash复制# 测试视频
python detect.py --weights best.pt --source test_video.mp4
# 使用摄像头
python detect.py --weights best.pt --source 0
为了在不同平台上使用训练好的模型,可以将其导出为其他格式。YOLOv5支持导出为ONNX、TorchScript等格式:
bash复制python export.py --weights runs/train/exp/weights/best.pt --include onnx
导出的ONNX模型可以被多种推理引擎使用,如OpenCV DNN、TensorRT等。
如果你想把模型部署到树莓派等嵌入式设备上,可以考虑以下优化:
一个简单的树莓派部署示例:
python复制import cv2
import numpy as np
# 加载模型
net = cv2.dnn.readNet('yolov5n.onnx')
# 图像预处理
image = cv2.imread('test.jpg')
blob = cv2.dnn.blobFromImage(image, 1/255.0, (640, 640), swapRB=True, crop=False)
# 推理
net.setInput(blob)
outputs = net.forward()
# 后处理
for detection in outputs[0,0,:,:]:
confidence = detection[4]
if confidence > 0.5:
x, y, w, h = detection[0:4] * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]])
cv2.rectangle(image, (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), (0,255,0), 2)
cv2.imshow('Result', image)
cv2.waitKey(0)
在实际项目中,我遇到过几个典型问题:
训练过程中如果遇到显存不足的问题,可以尝试减小批处理大小(--batch)或图像尺寸(--img)。我在GTX 1660显卡上,yolov5s模型使用batch=8和img=640的组合通常能稳定训练。