一、YoloV11源码下载地址
官网的源码下载地址:官网源码
二、数据集准备
1、数据标注
这里准备自己的数据集进行标注,标注工具可以使用Labelme、Labelimg或者LabelStudio等,这边我使用的是Labelimg
使用如下命令打开软件
下面是软件的界面
软件tips:需要设置自动保存标注生成的标注文件
创建项目和如何进行标注可以不再进行赘述
2、数据集划分
划分验证集和训练集的代码如下:
import os, shutil
from sklearn.model_selection import train_test_split
val_size = 0.2
#test_size = 0.2
postfix = 'png'
imgpath = r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\Images'
txtpath = r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\Labels'
output_train_img_folder =r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited/images/train'
output_val_img_folder = r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited/images/val'
output_train_txt_folder = r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited\labels/train'
output_val_txt_folder = r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited\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)
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)
#todo:需要test放开
# train, test = train_test_split(listdir, test_size=test_size, shuffle=True, random_state=0)
# train, val = train_test_split(train, 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)
#
# for i in train:
# shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/images/train/{}.{}'.format(i[:-4], postfix))
# shutil.copy('{}/{}'.format(txtpath, i), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/labels/train/{}'.format(i))
#
# for i in val:
# shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/images/val/{}.{}'.format(i[:-4], postfix))
# shutil.copy('{}/{}'.format(txtpath, i), r'E:\1-cheng\4-yolo-dataset-daizuo\multi-classify\bird-boat-horse-aeroplane-sheep\dataset20231219/labels/val/{}'.format(i))
#todo:需要test则放开
# for i in test:
# shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/test/{}.{}'.format(i[:-4], postfix))
# shutil.copy('{}/{}'.format(txtpath, i), 'labels/test/{}'.format(i))
需要修改的地方如下,主要是路径和图片格式:
以下是两种常见的数据集划分方式,常用的是第一种:
3、增加数据集的训练配置文件
这里我命名为pills.yaml,你可以随意更改,只要在后面配置路径的地方对应上就可以了
代码如下:
train: C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited\images\train # train images (relative to 'path') 4 images
val: C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited\images\val # val images (relative to 'path') 4 images
nc: 1
# class names
names: ['yellow_pill']
三、环境配置、训练和推理
1、环境安装
YoloV11/YoloV10/YoloV9/YoloV8/YoloV7/YoloV5 的环境都是通用的,
只需要安装一次就行
requirements.txt
certifi==2025.4.26
charset-normalizer==3.4.2
colorama==0.4.6
contourpy==1.3.0
cycler==0.12.1
filelock==3.18.0
fonttools==4.58.0
fsspec==2025.3.2
idna==3.10
importlib_resources==6.5.2
Jinja2==3.1.6
kiwisolver==1.4.7
MarkupSafe==3.0.2
matplotlib==3.9.4
mpmath==1.3.0
networkx==3.2.1
numpy==1.24.4
opencv-python==4.11.0.86
packaging==25.0
pandas==2.2.3
pillow==11.2.1
pip==25.1
psutil==7.0.0
py-cpuinfo==9.0.0
pyparsing==3.2.3
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
requests==2.32.3
scipy==1.13.1
seaborn==0.13.2
setuptools==78.1.1
six==1.17.0
sympy==1.14.0
thop==0.1.1.post2209072238
torch==2.7.0+cu118
torchaudio==2.7.0+cu118
torchvision==0.22.0+cu118
tqdm==4.67.1
typing_extensions==4.13.2
tzdata==2025.2
urllib3==2.4.0
wheel==0.45.1
zipp==3.21.0
2、YoloV11训练
(1)在根目录新建train.py,代码如下
"""
@Auth :jjjiboyang
@File :test.py
@IDE :PyCharm
@Email :jjjiboyang@gmail.com
"""
import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO
if __name__ == '__main__':
model = YOLO(model=r'C:\Jiboyang\DeepLearningModel\Yolov11\ultralytics\ultralytics\cfg\models\11\yolo11.yaml')
model.load('yolo11n.pt') # 加载预训练权重,改进或者做对比实验时候不建议打开,因为用预训练模型整体精度没有很明显的提升
model.train(data=r'pills.yaml',
imgsz=640,
epochs=50,
batch=4,
workers=0,
device='cpu',
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,默认是8。
-
device参数:该参数代表用哪个显卡训练,留空表示自动选择可用的GPU或CPU
-
optimizer参数:该参数代表优化器类型
-
close_mosaic参数:该参数代表在多少个epoch后关闭 mosaic 数据增强
-
resume参数:该参数代表是否从上一次中断的训练状态继续训练。设置为False表示从头开始新的训练。如果设置为True,则会加载上一次训练的模型权重和优化器状态,继续训练。这在训练被中断或在已有模型的基础上进行进一步训练时非常有用
-
project参数:该参数代表项目文件夹,用于保存训练结果
-
name参数:该参数代表命名保存的结果文件夹
-
single cls参数:该参数代表是否将所有类别视为一个类别,设置为False表示保留原有类别该参数代表是否缓存数据,设置为False表示不缓存。。cache参数:
Ps:般做科研改进工作时候可以不用预训练权重,因为用预训练模型整体精度很难提高
需要修改的参数如下:
(2)、如果在训练的过程中中断了训练,可以用如下方法继续开始上次中断的训练
把路径设置为last.pt的路径,然后设置resume为True
3、推理
(1)、新建detect.py
"""
@Auth :jjjiboyang
@File :test.py
@IDE :PyCharm
@Email :jjjiboyang@gmail.com
"""
from ultralytics import YOLO
if __name__ == '__main__':
# Load a model
model = YOLO(model=r'C:\Jiboyang\DeepLearningModel\Yolov11\ultralytics\runs\train\exp\weights\best.pt')
model.predict(source=r'C:\Jiboyang\DeepLearningModel\DataSets\Pills\splited\images\val\pill_bag_003.png',
save=True,
show=True,
)
推理代码的参数解释
- model参数:该参数可以填入模型文件路径
- source参数:该参数可以填入需要推理的图片或者视频路径,如果打开摄像头推理则填入0就行
- save参数:该参数填入True,代表把推理结果保存下来,默认是不保存的,所以一般都填入True
- show参数:该参数填入Tue,代表把推理结果以窗口形式显示出来,默认是显示的,这个参数根据自己需求打开就行,不显示你就填False就行
以下是图片的测试效果:
(2)、使用预训练好的模型进行推理
从官网下载预训练模型