YOLOv11 数据集训练与推理指南及网络结构解析
YOLOv11 是 Ultralytics 团队发布的最新目标检测模型。内容涵盖环境配置、数据集准备(标注、格式转换、划分)、训练配置与执行、推理部署及断点续训。涉及 LabelImg 工具使用、VOC 转 YOLO 格式脚本、PyTorch 依赖安装、训练参数调整及预测代码编写。适用于目标检测、实例分割等任务,提供完整的从零开始实践流程。

YOLOv11 是 Ultralytics 团队发布的最新目标检测模型。内容涵盖环境配置、数据集准备(标注、格式转换、划分)、训练配置与执行、推理部署及断点续训。涉及 LabelImg 工具使用、VOC 转 YOLO 格式脚本、PyTorch 依赖安装、训练参数调整及预测代码编写。适用于目标检测、实例分割等任务,提供完整的从零开始实践流程。

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

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

数据集使用标注软件标注好,推荐 labelimg 或 labelme,可以在 python 环境使用 pip install labelimg 或者 pip install labelme 进行安装。
安装完成在终端输入命令启动标注软件。

设置自动保存标注生成的标注文件。

标注格式如果选择 VOC 格式,后面需要代码转换格式,如果选择 YOLO 格式就不用转换。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'your_image_path' # 图像文件路径
xmlpath = r'your_xml_path' # xml 文件路径
txtpath = r'your_txt_path' # 生成的 txt 文件路径
if not os.path.exists(txtpath):
os.makedirs(txtpath, exist_ok=True)
listdir = os.listdir(xmlpath)
error_file_list = []
for i in range(0, len(listdir)):
try:
path = os.path.join(xmlpath, listdir[i])
if ('.xml' in path) or ('.XML' in path):
convert_annotation(path, listdir[i])
print(f'file {listdir[i]} convert success.')
else:
print(f'file {listdir[i]} is not xml format.')
except Exception as e:
print(f'file {listdir[i]} convert error.')
print(f'error message:\n{e}')
error_file_list.append(listdir[i])
print(f'this file convert failure\n{error_file_list}')
print(f'Dataset Classes:{classes}')
代码需要修改的地方如下:
划分训练集和验证集代码如下:
import os, shutil
from sklearn.model_selection import train_test_split
val_size = 0.2
postfix = 'jpg'
imgpath = r'your_image_path'
txtpath = r'your_label_path'
output_train_img_folder = r'your_output/train/images'
output_val_img_folder = r'your_output/val/images'
output_train_txt_folder = r'your_output/train/labels'
output_val_txt_folder = r'your_output/val/labels'
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)
listdir = [i for i in os.listdir(txtpath) if 'txt' in i]
train, val = train_test_split(listdir, 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 环境都是通用的,只需要安装一次就行。
基础环境配置参考官方文档或相关教程链接。
安装 requirements.txt 文件的环境,需要注释掉下面两行,前面的步骤已经安装了,不注释的话会覆盖前面的会安装最新版本的 pytorch,所以注释掉。
没有这个文件可以自己新建一个 requirements.txt,然后把下面代码复制进去就好了。
# 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
# Logging -------------------------------------
# tensorboard>=2.13.0
# dvclive>=2.12.0
# clearml
# comet
# Plotting ------------------------------------
pandas>=1.1.4
seaborn>=0.11.0
# Export --------------------------------------
# coremltools>=7.0
# onnx>=1.12.0
# onnxsim>=0.4.1
# nvidia-pyindex
# nvidia-tensorrt
# scikit-learn==0.19.2
# tensorflow>=2.4.1
# tflite-support
# tensorflowjs>=3.9.0
# openvino-dev>=2023.0
# Extras --------------------------------------
psutil
py-cpuinfo
thop>=0.1.1
# ipython
# albumentations>=1.0.3
# pycocotools>=2.0.6
# roboflow
(1) 在根目录新建一个 python 文件,取名为:train.py。
(2) 把训练代码复制到 train.py 文件。
训练的代码如下:
# -*- coding: utf-8 -*-
import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO
if __name__ == '__main__':
model = YOLO(model=r'path/to/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,)
注意:模型配置路径改成你自己的路径,还有数据集配置文件也修改成你自己的路径。
训练代码的参数解释:
我这里演示加载预训练权重,训练输出如下所示:

(1)官网的预训练模型下载
进入官网的源码下载地址,往下面拉,看到模型位置,YOLOv11 针对不同的场景和应用提供了 YOLOv11n、YOLOv11s 等不同大小的模型,具体看官网提供的,需要下载哪个,鼠标左键单击下载就行。
(2)在根目录新建一个 python 文件,取名为:detect.py。
(3)把推理代码复制到 detect.py 文件。
注意:模型路径改成你自己的路径,还有预测图像也改成你自己的路径。
推理的代码如下:
# -*- coding: utf-8 -*-
from ultralytics import YOLO
if __name__ == '__main__':
# Load a model
model = YOLO(model=r'path/to/yolo11n-seg.pt')
model.predict(source=r'path/to/bus.jpg', save=True, show=True,)
推理代码的参数解释:
分割模型推理结果如下:

目标检测模型推理结果如下:

在训练过程不小心中断了,那怎么继续上次的训练了,这里先不慌,官网也的代码写得非常好,它有这个断点训练功能,那么 YOLOv8 v10 v11 处理的方法都是一模一样。
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