YOLOv8 从零开始完整教程:环境搭建、模型下载、推理与训练
YOLOv8 从零开始完整教程:环境搭建、模型下载、推理与训练
前言
- YOLOv8 是一款基于 PyTorch 的目标检测模型,其速度、精度和参数量都有大幅提升。
- 本教程将从零开始,完整地介绍 YOLOv8 的使用方法,包括环境配置、模型下载、图片/视频推理、数据集准备、模型训练、评估与部署等所有关键环节。
YOLOv8 官方文档:https://github.com/ultralytics/yolov8/wiki/Train-Custom-Data
目录一、环境准备
1.1 系统要求
操作系统:Windows 10/11、Ubuntu 18.04+、macOS(CPU模式)
-
Python 版本:3.8 - 3.11
-
GPU(推荐):NVIDIA 显卡,CUDA 11.8+ 和 cuDNN 8.x
1.2 检查 GPU 环境(可选但推荐)
# 应输出 True
import torch
print(torch.cuda.is_available())
# 查看 CUDA 版本
print(torch.version.cuda)
1.3 安装 Ultralytics 包
# 使用 pip 一键安装(推荐)
pip install ultralytics
# 如需使用国内镜像加速
pip install ultralytics -i https://pypi.tuna.tsinghua.edu.cn/simple
1.4 验证安装
from ultralytics import YOLO
print("YOLOv8 安装成功!")
1.4 安装jupyterlab(可选但推荐)
pip install jupyterlab
二、模型下载
YOLOv8 提供多种预训练模型规格,模型会在首次使用时自动下载,也可手动下载。
2.1 自动下载(首次运行时自动触发)
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
# 自动下载到 ~/.cache/torch/hub/ 或当前目录
2.2 手动下载(推荐,避免网络超时)
下载后放入当前工作目录即可。
| 模型规格 | 下载链接 |
|---|---|
| YOLOv8n (Nano) | 下载 |
| YOLOv8s (Small) | 下载 |
| YOLOv8m (Medium) | 下载 |
| YOLOv8l (Large) | 下载 |
| YOLOv8x (Extra Large) | 下载 |
| YOLOv8n-seg (分割) | 下载 |
| YOLOv8n-pose (姿态估计) | 下载 |
2.3 各规格性能对比(COCO 数据集)
| 模型 | 输入尺寸 | mAP | 参数量(M) | 适用场景 |
|---|---|---|---|---|
| YOLOv8n | 640 | 37.3 | 3.2 | 移动端、实时性要求高 |
| YOLOv8s | 640 | 44.9 | 11.2 | 平衡速度与精度 |
| YOLOv8m | 640 | 50.2 | 25.9 | 精度优先 |
| YOLOv8l | 640 | 52.9 | 43.7 | 服务器端高精度 |
| YOLOv8x | 640 | 53.9 | 68.2 | 追求极致精度 |
三、图片推理
3.1 单张图片推理(Python API)
from ultralytics import YOLO
# 加载模型(自动下载或使用本地)
model = YOLO("yolov8n.pt")
# 对图片进行推理
results = model("https://ultralytics.com/images/bus.jpg")
# 显示结果
results[0].show()
# 保存结果(保存到 runs/detect/predict/)
results[0].save(filename="result.jpg")
# ---------- Jupyter 环境推荐用法 ----------
# import matplotlib.pyplot as plt
# # 获取带检测框的图像(BGR 格式)
# img_with_boxes = results[0].plot()
# # matplotlib 显示(BGR -> RGB)
# plt.figure(figsize=(10, 8))
# plt.imshow(img_with_boxes[:, :, ::-1])
# plt.axis("off")
# plt.title("Detection Result")
# plt.show()
# # 保存结果(支持中文路径)
# results[0].save(filename="result.jpg")
3.2 批量图片推理
# 对多张图片推理
results = model(["image1.jpg", "image2.jpg"])
for i, result in enumerate(results):
result.save(f"result_{i}.jpg")
# ---------- Jupyter 环境推荐用法 ----------
# # 多张图片推理
# image_paths = ["image1.jpg", "image2.jpg"]
# results = model(image_paths)
# # 在 Jupyter 中逐个显示结果
# for i, result in enumerate(results):
# img = result.plot()[:, :, ::-1] # BGR -> RGB
# plt.figure()
# plt.imshow(img)
# plt.axis("off")
# plt.title(f"Result {i+1}: {result.path}")
# plt.show()
# # 保存带框图像(可选)
# result.save(filename=f"result_{i}.jpg")
3.3 使用 CLI 命令行
# 图片推理
yolo predict model=yolov8n.pt source='bus.jpg'
# 指定输出目录
yolo predict model=yolov8n.pt source='bus.jpg' project=my_results name=exp
3.4 解析检测结果
python
results = model("image.jpg")
result = results[0] # 取第一张图的结果
# 获取检测框 [x1, y1, x2, y2, confidence, class]
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0].tolist() # 边界框坐标
conf = box.conf[0].item() # 置信度
cls = int(box.cls[0].item()) # 类别ID
print(f"检测到类别 {cls},置信度 {conf:.2f},位置 ({x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f})")
# # 使用 CLI 命令行(在 Jupyter 中执行)
# # 图片推理
# !yolo predict model=yolov8n.pt source='bus.jpg'
# # 指定输出目录
# !yolo predict model=yolov8n.pt source='bus.jpg' project=my_results name=exp
注意:CLI 的输出图像会保存在 runs/detect/predict/ 或自定义目录中,不会在单元格内直接显示。如需显示,可手动读取保存的图片。
3.4 解析检测结果
results = model("image.jpg")
result = results[0] # 取第一张图的结果
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0].tolist() # 边界框坐标
conf = box.conf[0].item() # 置信度
cls = int(box.cls[0].item()) # 类别ID
print(f"检测到类别 {cls},置信度 {conf:.2f},位置 ({x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f})")
3.5 支持的输入类型
| 输入类型 | 示例 |
|---|---|
| 本地图片 | ‘image.jpg’ |
| 网络图片 | ‘https://example.com/image.jpg’ |
| PIL 图像 | Image.open(‘image.jpg’) |
| OpenCV 数组 | cv2.imread(‘image.jpg’) |
| 目录 | ‘images/’ |
| Glob 模式 | ‘images/*.jpg’ |
四、视频推理与摄像头实时检测
4.1 视频文件推理
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
# 处理视频文件
results = model("video.mp4", save=True) # 保存结果视频
4.2 实时摄像头检测
import cv2
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
# 打开摄像头(0 表示默认摄像头)
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 对当前帧进行推理
results = model(frame)
# 在帧上绘制检测框
annotated_frame = results[0].plot()
# 显示
cv2.imshow("YOLOv8 Detection", annotated_frame)
# 按 'q' 退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
4.3 流式处理(避免内存溢出)
# 对于大视频,使用 stream=True 流式处理
results = model("large_video.mp4", stream=True)
for result in results:
# 逐帧处理,不会一次性加载所有帧
result.save() # 保存每一帧结果
4.4 保存视频中的关键帧检测结果
以下示例演示了如何每隔固定帧数保存检测结果(可自定义间隔):
import cv2
from ultralytics import YOLO
import os
model = YOLO("yolov8n.pt")
# 打开视频文件
cap = cv2.VideoCapture("video.mp4")
# 输出目录
os.makedirs("./output", exist_ok=True)
frame_count = 0
save_step = 30 # 每隔 30 帧保存一次
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame_count += 1
if frame_count % save_step == 0:
# 进行推理
results = model(frame)
# 保存原始帧
cv2.imwrite(f"./output/frame_{frame_count}_original.jpg", frame)
# 保存带检测框的结果图
result_img = results[0].plot() # 返回 BGR 格式
cv2.imwrite(f"./output/frame_{frame_count}_result.jpg", result_img)
cap.release()
cv2.destroyAllWindows()
4.5 支持的视频输入类型
| 输入类型 | 示例 |
|---|---|
| 本地视频文件 | ‘video.mp4’ |
| YouTube 链接 | ‘https://youtu.be/LNwODJXcvt4’ |
| RTSP 流 | ‘rtsp://example.com/live.stream’ |
| 摄像头: | 0(整数) |
五、数据集准备
5.1 公开数据集下载
| 数据集 | 描述 | 下载地址 |
|---|---|---|
| COCO | 80个类别,大规模通用检测 | 下载 |
| Open Images V7 | 600个类别 | 下载 |
| TinyPerson | 小目标人体检测 | GitHub |
| Pascal VOC | 20个类别 | 下载 |
| coco8(测试用) | 8张图片,轻量级测试数据集 | YOLOv8 内置,训练时指定 data=coco8.yaml 即可 |
温馨提示:
以上链接均为官方资源或推荐的可靠来源。下载前请确认有足够的存储空间(Open Images V7 完整版超过 500GB),并遵守各数据集的使用条款。
5.2 数据集目录结构
dataset/
├── images/
│ ├── train/ # 训练集图片
│ │ ├── image1.jpg
│ │ └── image2.jpg
│ └── val/ # 验证集图片
│ ├── image1.jpg
│ └── image2.jpg
└── labels/
├── train/ # 训练集标签
│ ├── image1.txt
│ └── image2.txt
└── val/ # 验证集标签
├── image1.txt
└── image2.txt
5.3 标注格式(YOLO 格式)
每张图片对应一个同名 .txt 文件,每行格式:
class_id x_center y_center width height
-
坐标均为归一化值(除以图片宽度/高度),范围 0-1
-
class_id 从 0 开始
示例:
0 0.5 0.5 0.2 0.3 # 类别0的人,中心(0.5,0.5),宽0.2,高0.3
1 0.3 0.4 0.1 0.2 # 类别1的车辆
5.4 JSON 转 YOLO 格式脚本(适用于 COCO 格式)
import json
import os
from PIL import Image
def convert_coco_to_yolo(json_path, image_dir, output_dir):
with open(json_path, 'r') as f:
data = json.load(f)
# 创建类别映射
categories = {cat['id']: idx for idx, cat in enumerate(data['categories'])}
# 按图片组织标注
images = {img['id']: img for img in data['images']}
annotations_by_image = {}
for ann in data['annotations']:
image_id = ann['image_id']
if image_id not in annotations_by_image:
annotations_by_image[image_id] = []
annotations_by_image[image_id].append(ann)
# 转换每个图片的标注
for image_id, anns in annotations_by_image.items():
img_info = images[image_id]
img_path = os.path.join(image_dir, img_info['file_name'])
# 获取图片尺寸
img = Image.open(img_path)
img_w, img_h = img.size
# 生成 YOLO 格式标注
yolo_lines = []
for ann in anns:
category_id = ann['category_id']
if category_id not in categories:
continue
class_id = categories[category_id]
x, y, w, h = ann['bbox']
# 转换为 YOLO 格式(中心坐标,归一化)
x_center = (x + w / 2) / img_w
y_center = (y + h / 2) / img_h
width = w / img_w
height = h / img_h
yolo_lines.append(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}")
# 保存标注文件
label_name = os.path.splitext(img_info['file_name'])[0] + '.txt'
label_path = os.path.join(output_dir, label_name)
with open(label_path, 'w') as f:
f.write('\n'.join(yolo_lines))
print(f"转换完成,输出目录: {output_dir}")
# 使用示例
convert_coco_to_yolo('annotations.json', 'images/', 'labels/')
六、自定义数据集训练
6.1 创建数据配置文件 data.yaml
# data.yaml
path: ./dataset # 数据集根目录
train: images/train # 训练集图片目录(相对 path)
val: images/val # 验证集图片目录
nc: 2 # 类别数量
names: ['person', 'car'] # 类别名称
6.2 训练命令(CLI 方式)
# 基础训练
yolo train data=data.yaml model=yolov8n.pt epochs=100 imgsz=640
# 带参数训练
yolo train data=data.yaml model=yolov8s.pt epochs=200 batch=16 lr0=0.01 device=0
6.3 训练命令(Python API 方式)
from ultralytics import YOLO
# 加载预训练模型
model = YOLO("yolov8n.pt")
# 开始训练
results = model.train(
data="data.yaml", # 数据集配置文件
epochs=100, # 训练轮数
imgsz=640, # 输入图像尺寸
batch=16, # 批次大小
lr0=0.01, # 初始学习率
device=0, # 使用 GPU 0(CPU 则用 'cpu')
workers=4, # 数据加载线程数
patience=50, # 早停轮数
save=True, # 保存模型
project="runs/train", # 保存目录
name="my_model" # 实验名称
)
参数说明对照表(方便查阅)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| data | str | 必填 | 数据集配置文件路径(.yaml) |
| epochs | int | 100 | 训练轮数 |
| batch | int | 16 | 批大小 |
| imgsz | int | 640 | 输入图像尺寸 |
| workers | int | 8 | 数据加载线程数(Windows 建议 0/2,Linux 可 8) |
| device | str/int | 0 | 设备:‘cpu’ 或 GPU 编号(0,1,…) |
| warmup_epochs | int | 3 | 预热轮数 |
| patience | int | 50 | 早停轮数(0 表示不早停) |
| save | bool | True | 是否保存模型 |
| project | str | ‘runs/train’ 结果保存根目录 |
其他参数参见官方地址:https://docs.ultralytics.com/usage/cfg/
6.4 训练参数优化建议
| 参数 | 推荐值 | 说明 |
|---|---|---|
| epochs | 100-300 | 数据集越大,轮数越多 |
| batch | 8-32 | 根据 GPU 显存调整 |
| imgsz | 640-1280 | 小目标检测可增大 |
| mosaic | 0.5-1.0 | 数据增强, |
| mixup | 0.1-0.3 | 小目标检测建议降低 |
| lr0 | 0.01 | 初始学习率 |
| device | 0,1,… | GPU 编号,多卡用 ‘0,1’ |
6.5 恢复训练
# 从断点恢复训练
model = YOLO("runs/train/my_model/weights/last.pt")
model.train(resume=True)
七、模型评估与推理
7.1 验证集评估
# CLI 方式
yolo val model=runs/train/my_model/weights/best.pt data=data.yaml
python
# Python API
model = YOLO("runs/train/my_model/weights/best.pt")
metrics = model.val()
print(f"mAP50-95: {metrics.box.map:.4f}")
print(f"mAP50: {metrics.box.map50:.4f}")
7.2 使用训练好的模型进行推理
from ultralytics import YOLO
# 加载训练好的模型
model = YOLO("runs/train/my_model/weights/best.pt")
# 图片推理
results = model("test_image.jpg")
results[0].show()
# 视频推理
results = model("test_video.mp4", save=True)
7.3 导出模型用于部署
model.export(format="onnx", imgsz=640) # ONNX
model.export(format="engine", device=0) # TensorRT
model.export(format="torchscript") # TorchScript
model.export(format="tflite") # TFLite(移动端)
八、完整流程
8.1 训练流程
# 完整示例:从训练到推理
from ultralytics import YOLO
# 1. 加载预训练模型
model = YOLO("yolov8n.pt")
# 2. 训练自定义模型
model.train(
data="data.yaml",
epochs=100,
imgsz=640,
batch=16,
device=0,
project="runs/train",
name="my_detector"
)
# 3. 验证模型
metrics = model.val()
print(f"训练完成,mAP: {metrics.box.map:.4f}")
# 4. 加载最佳模型
best_model = YOLO("runs/train/my_detector/weights/best.pt")
# 5. 推理测试
results = best_model("test_image.jpg")
results[0].show()
# 6. 导出模型
best_model.export(format="onnx")
九、常见问题与解决方案
问题 1:模型下载超时
解决:手动下载模型文件放到当前目录,或设置镜像:
export HF_ENDPOINT=https://hf-mirror.com # Linux/macOS
set HF_ENDPOINT=https://hf-mirror.com # Windows
问题 2:CUDA 不可用
解决:检查并安装对应 CUDA 版本的 PyTorch:
import torch
print(torch.cuda.is_available()) # 检查
# 重新安装对应 CUDA 版本的 PyTorch
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
问题 3:内存不足(OOM)
解决:
-
减小 batch 大小
-
减小 imgsz 尺寸
-
使用 device=‘cpu’ 先用 CPU 测试
问题 4:多线程共享模型冲突
# ❌ 错误:多线程共用模型
model = YOLO("model.pt")
Thread(target=lambda: model("image1.jpg")).start()
Thread(target=lambda: model("image2.jpg")).start()
# ✅ 正确:每个线程独立加载
def predict(img):
model = YOLO("model.pt")
return model(img)
问题 5:标注工具选择
-
labelImg:经典工具,支持 VOC/YOLO 格式,适合小规模标注。
-
Make Sense:在线工具,无需安装,适合快速标注。
-
Label Studio:全能型,支持多种标注类型,配置稍复杂。
问题 6:标注类别编号不一致
-
YOLO 格式要求类别编号从 0 开始连续,且与 data.yaml 中的 names 顺序严格对应
-
若使用 labelImg,可在 data/predefined_classes.txt 中预定义类别列表,确保顺序一致
十、资源汇总
| 资源 | 链接 |
|---|---|
| Ultralytics 官方文档 | https://docs.ultralytics.com |
| GitHub 仓库 | https://github.com/ultralytics/ultralytics |
| 预训练模型下载 | https://github.com/ultralytics/assets/releases |
| COCO 数据集 | https://cocodataset.org |
| Open Images 数据集 | https://storage.googleapis.com/openimages/web/index.html |
更多推荐
所有评论(0)