前言
YOLOv11 由 Ultralytics 团队在 2024 年 9 月 30 日发布,最新的 YOLOv11 模型在之前的 YOLO 版本引入了新功能和改进,以进一步提高性能和灵活性。YOLOv11 快速、准确且易于使用,使其成为各种目标检测和跟踪、实例分割、图像分类和姿态估计任务的绝佳选择。
YOLOv11 由 Ultralytics 团队发布,支持目标检测、实例分割等任务。教程涵盖数据集标注与格式转换、环境配置、训练及推理流程。包含 VOC 转 YOLO 格式脚本、数据集划分代码、train.py 与 detect.py 实现细节,以及断点续训解决方案,助力快速上手 YOLOv11 模型应用。

YOLOv11 由 Ultralytics 团队在 2024 年 9 月 30 日发布,最新的 YOLOv11 模型在之前的 YOLO 版本引入了新功能和改进,以进一步提高性能和灵活性。YOLOv11 快速、准确且易于使用,使其成为各种目标检测和跟踪、实例分割、图像分类和姿态估计任务的绝佳选择。

官网源码下载地址:Ultralytics GitHub
根据 yolov11.yaml 画出 yolo 整体结构图,如下图所示

推荐使用 labelimg 或 labelme 进行标注。安装命令如下:
pip install labelimg
启动标注软件后,设置自动保存标注生成的文件。
如果标注格式为 VOC,需要转换为 YOLO 格式。转换代码如下:
import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join
classes = []
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(xmlpath, xmlname):
with open(xmlpath, "r", encoding='utf-8') as in_file:
txtname = xmlname[:-4] + '.txt'
txtfile = os.path.join(txtpath, txtname)
tree = ET.parse(in_file)
root = tree.getroot()
filename = root.find('filename')
img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
h, w = img.shape[:2]
res = []
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
classes.append(cls)
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
bb = convert((w, h), b)
res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
if len(res) != 0:
with open(txtfile, 'w+') as f:
f.write('\n'.join(res))
if __name__ == "__main__":
postfix = 'png'
imgpath = r'./images'
xmlpath = r'./annotations'
txtpath = r'./labels'
if not os.path.exists(txtpath):
os.makedirs(txtpath, exist_ok=True)
list_dir = os.listdir(xmlpath)
error_file_list = []
for i in range(0, len(list_dir)):
try:
path = os.path.join(xmlpath, list_dir[i])
if ('.xml' in path) or ('.XML' in path):
convert_annotation(path, list_dir[i])
print(f'file {list_dir[i]} convert success.')
else:
print(f'file {list_dir[i]} is not xml format.')
except Exception as e:
print(f'file {list_dir[i]} convert error.')
print(f'error message:\n{e}')
error_file_list.append(list_dir[i])
print(f'this file convert failure\n{error_file_list}')
print(f'Dataset Classes:{classes}')
修改说明:
postfix 参数填图片后缀(如 png, jpg)。imgpath 参数填图片所在路径。xmlpath 参数填标注文件路径。txtpath 参数填生成的 YOLO 格式文件路径。划分训练集和验证集代码如下:
import os, shutil
from sklearn.model_selection import train_test_split
val_size = 0.2
postfix = 'jpg'
imgpath = r'./images'
txtpath = r'./labels'
output_train_img_folder = r'./dataset/images/train'
output_val_img_folder = r'./dataset/images/val'
output_train_txt_folder = r'./dataset/labels/train'
output_val_txt_folder = r'./dataset/labels/val'
os.makedirs(output_train_img_folder, exist_ok=True)
os.makedirs(output_val_img_folder, exist_ok=True)
os.makedirs(output_train_txt_folder, exist_ok=True)
os.makedirs(output_val_txt_folder, exist_ok=True)
list_dir = [i for i in os.listdir(txtpath) if 'txt' in i]
train, val = train_test_split(list_dir, test_size=val_size, shuffle=True, random_state=0)
for i in train:
img_source_path = os.path.join(imgpath, '{}.{}'.format(i[:-4], postfix))
txt_source_path = os.path.join(txtpath, i)
img_destination_path = os.path.join(output_train_img_folder, '{}.{}'.format(i[:-4], postfix))
txt_destination_path = os.path.join(output_train_txt_folder, i)
shutil.copy(img_source_path, img_destination_path)
shutil.copy(txt_source_path, txt_destination_path)
for i in val:
img_source_path = os.path.join(imgpath, '{}.{}'.format(i[:-4], postfix))
txt_source_path = os.path.join(txtpath, i)
img_destination_path = os.path.join(output_val_img_folder, '{}.{}'.format(i[:-4], postfix))
txt_destination_path = os.path.join(output_val_txt_folder, i)
shutil.copy(img_source_path, img_destination_path)
shutil.copy(txt_source_path, txt_destination_path)
数据集放置方式有两种,确保训练集和验证集目录结构正确即可。
在项目下创建 data.yaml 文件,配置训练集、验证集路径及类别名称。
train: ./images/train # train images (relative to 'path')
val: ./images/val # val images (relative to 'path')
nc: 2 # class names
names: ['dog', 'cat']
YOLOv11/YOLOv10/YOLOv9/YOLOv8/YOLOv7/YOLOv5 环境通用,只需安装一次。
参考官方文档安装 PyTorch。
安装 requirements.txt 中的环境,建议注释掉已安装的 PyTorch 相关行,避免覆盖版本。
# Ultralytics requirements
# Example: pip install -r requirements.txt
# Base ----------------------------------------
matplotlib>=3.3.0
numpy==1.24.4
opencv-python>=4.6.0
pillow>=7.1.2
pyyaml>=5.3.1
requests>=2.23.0
scipy>=1.4.1
tqdm>=4.64.0
train.py。# -*- coding: utf-8 -*-
import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO
if __name__ == '__main__':
model = YOLO(model=r'./cfg/models/11/yolo11.yaml')
# model.load('yolo11n.pt') # 加载预训练权重
model.train(data=r'data.yaml', imgsz=640, epochs=50, batch=4, workers=0, device='', optimizer='SGD', close_mosaic=10, resume=False, project='runs/train', name='exp', single_cls=False, cache=False,)
注意: 需将模型配置路径和数据集配置文件路径修改为实际路径。
参数解释:
model: 模型配置文件路径。data: 训练数据集配置文件路径。imgsz: 输入图像尺寸,默认 640x640。epochs: 训练轮数。batch: 批处理大小,根据显存调整。workers: 数据加载线程数,显存不足可设为 0。device: 设备选择,留空自动选择 GPU 或 CPU。optimizer: 优化器类型。close_mosaic: 关闭 mosaic 数据增强的 epoch 数。resume: 是否从上次中断继续训练。project: 结果保存文件夹。name: 结果文件夹命名。single_cls: 是否将所有类别视为一个类别。cache: 是否缓存数据。detect.py。# -*- coding: utf-8 -*-
from ultralytics import YOLO
if __name__ == '__main__':
model = YOLO(model=r'./yolo11n-seg.pt')
model.predict(source=r'./assets/bus.jpg', save=True, show=True,)
参数解释:
model: 模型文件路径。source: 图片或视频路径,摄像头则填 0。save: 是否保存推理结果,True 表示保存。show: 是否显示推理结果窗口,True 表示显示。若训练中断,可通过设置 resume=True 继续训练。
model.train(..., resume=True, model='runs/train/exp/weights/last.pt')
model: 填入上次中断的模型路径(last.pt)。resume: 设置为 True,加载上一次训练的模型权重和优化器状态。本文介绍了 YOLOv11 数据集训练与推理的基本流程,涵盖环境配置、数据准备、训练参数设置及断点续训方法,助力快速上手 YOLOv11 模型应用。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online