通过对最新的yoloV8进行了解https://github.com/ultralytics/ultralytics,其项目对目标检测、图像分割、姿态、分类等任务进行了大整合,功能变得更加强大。根据不同的task来选择不同的任务模式,具体可以参考其说明文档。
https://docs.ultralytics.com/usage/cli/
yolo TASK MODE ARGS
Where TASK (optional) is one of [detect, segment, classify,pose ]
MODE (required) is one of [train, val, predict, export, track]
ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
一、目标检测数据集
接下来,我将就检测任务的数据集准备做详细说明:
首先参考一下,demo代码中提到的coco128的样例数据结构
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.yaml") # build a new model from scratch
model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
# Use the model
model.train(data="coco128.yaml", epochs=3) # train the model
metrics = model.val() # evaluate model performance on the validation set
results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
path = model.export(format="onnx") # export the model to ONNX format
通过对yaml文件的阅读,train、val这里我们也配置为图片的文件夹(采用dir: path/to/imgs)
# Ultralytics YOLO 🚀, AGPL-3.0 license
# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
# Example usage: yolo train data=coco128.yaml
# parent
# ├── ultralytics
# └── datasets
# └── coco128 ← downloads here (7 MB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/coco128 # dataset root dir
train: images/train2017 # train images (relative to 'path') 128 images
val: images/train2017 # val images (relative to 'path') 128 images
test: # test images (optional)
# Classes
names:
0: person
1: bicycle
2: car
........
1、准备标注好的xml及图片数据文件放入labelimgRes中,创建dealData的两个py脚本(见下文);mycoco2为脚本生成目录,无需创建;mycoco2.yaml可参考后文改写。
dealData1.py
目的:处理labelimg标注的xml文件,提取信息至txt文件,红色至蓝色框中所示。dealData1.py代码如下
# -*- coding: utf-8 -*-
# target:处理labelimg标注的xml文件,提取信息至txt文件
# 通过labelimg标注后的文件放在目录中
# |labelimgRes
# │ ├─ images
# │ │ └─ ······
# │ ├─ labels
# │ │ └─ ······
# │ └─ xml
# │ └─ ······
# │dealData1.py
# │dealData2.py
# 数据处理脚本或直接运行dealData1.py
# python dealData1.py
import xml.etree.ElementTree as ET
from tqdm import tqdm
import os
import shutil
# 1.指定标注后的img+xml文件夹路径
dataBasePath = "./labelimgRes"
# 2.指定标注的类别字典
classes = ["water"] # 检测类别名字
def dealDatasetsTargetDir(labels_dir):
if os.path.exists(labels_dir):
shutil.rmtree(labels_dir)
os.makedirs(labels_dir)
dealDatasetsTargetDir(dataBasePath+'/labels')
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(image_id):
# try:
in_file = open(dataBasePath+'/xml/%s.xml' % (image_id), encoding='utf-8')
# print(in_file)
out_file = open(dataBasePath+'/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
# print(xmlbox)
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
b1, b2, b3, b4 = b
# 标注越界修正
if b2 > w:
b2 = w
if b4 > h:
b4 = h
b = (b1, b2, b3, b4)
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " +
" ".join([str(a) for a in bb]) + '\n')
total_xmls = os.listdir(dataBasePath+'/xml')
print(total_xmls)
for xml_id in tqdm(total_xmls):
if xml_id.index('.') == 0:
continue
xml_name = xml_id.strip().split(".")[0]
convert_annotation(xml_name)
dealData2.py
目的:对img、txt文件进行划分,形成v8所需的结构数据集 labelimgRes=》mycoco2
# -*- coding: utf-8 -*-
# target:对img、txt文件进行划分,形成v8结构化所需的数据集 labelimgRes=》mycoco2
# |mycoco2.yaml
# |mycoco2
# ├─ test
# │ ├─ images
# │ │ └─ ······
# │ └─ labels
# │ └─ ······
# ├─ train
# │ ├─ images
# │ │ └─ ······
# │ └─ labels
# │ └─ ······
# ├─ valid
# │ ├─ images
# │ │ └─ ······
# │ └─ labels
# │ └─ ······
# │dealData1.py
# │dealData2.py
# 数据处理脚本或直接运行dealData2.py
# python dealData2.py
# 读取配置进行训练
# yolo task=detect mode=train model=yolov8n.pt data={dataset.location}/mycoco2.yaml epochs=100 imgsz=640
import os
import random
from tqdm import tqdm
import shutil
# 1.指定 images 文件夹路径
image_dir = "./labelimgRes/images"
# 2.指定 labels 文件夹路径
label_dir = "./labelimgRes/labels"
# 3.指定 labels 文件夹路径
mycoco_dir = "./mycoco2"
# 4.指定 数据集划分比例 train:valid:test = 8:1:1
train, valid, test = 8, 1, 1
test_dir = mycoco_dir + "/test"
valid_dir = mycoco_dir + "/valid"
train_dir = mycoco_dir + "/train"
# 生成mycoco数据集结构
def dealDatasetsTargetDir(mycoco_dir):
if os.path.exists(mycoco_dir):
shutil.rmtree(mycoco_dir)
os.makedirs(mycoco_dir)
os.makedirs(test_dir)
os.makedirs(test_dir+"/images")
os.makedirs(test_dir+"/labels")
os.makedirs(valid_dir)
os.makedirs(valid_dir+"/images")
os.makedirs(valid_dir+"/labels")
os.makedirs(train_dir)
os.makedirs(train_dir+"/images")
os.makedirs(train_dir+"/labels")
def copyfile(srcfile,dstfile):
if not os.path.isfile(srcfile):
print ("%s not exist!"%(srcfile))
else:
fpath=os.path.dirname(srcfile) #获取文件路径
if not os.path.exists(fpath):
os.makedirs(fpath) #没有就创建路径
shutil.copyfile(srcfile,dstfile) #复制文件到默认路径
print ("copy %s -> %s"%( srcfile,os.path.join(fpath,dstfile)))
dealDatasetsTargetDir(mycoco_dir)
# 创建一个空列表来存储有效图片的路径
valid_images = []
# 创建一个空列表来存储有效 label 的路径
valid_labels = []
# 遍历 images 文件夹下的所有图片
for image_name in os.listdir(image_dir):
if image_name.index('.') == 0:
continue
# 获取图片的完整路径
image_path = os.path.join(image_dir, image_name)
# 获取图片文件的扩展名
ext = os.path.splitext(image_name)[-1]
# 根据扩展名替换成对应的 label 文件名
label_name = image_name.replace(ext, ".txt")
# 获取对应 label 的完整路径
label_path = os.path.join(label_dir, label_name)
# 判断 label 是否存在
if not os.path.exists(label_path):
# 删除图片
os.remove(image_path)
print("deleted:", image_path)
else:
# 将图片路径添加到列表中
valid_images.append(image_path)
# 将label路径添加到列表中
valid_labels.append(label_path)
# print("valid:", image_path, label_path)
# 遍历每个有效图片路径
for i in tqdm(range(len(valid_images))):
image_path = valid_images[i]
label_path = valid_labels[i]
# 随机生成一个概率
r = random.random()
# 判断图片应该移动到哪个文件夹
test_bit = test/(train+valid+test)
valid_bit = valid/(train+valid+test)+test_bit
if r < test_bit:
# 移动到 test 文件夹
destination = test_dir
elif r < valid_bit:
# 移动到 valid 文件夹
destination = valid_dir
else:
# 移动到 train 文件夹
destination = train_dir
# 生成目标文件夹中图片的新路径
image_destination_path = os.path.join(destination, "images", os.path.basename(image_path))
# 移动图片到目标文件夹
# os.rename(image_path, image_destination_path)
copyfile(image_path, image_destination_path)
# 生成目标文件夹中 label 的新路径
label_destination_path = os.path.join(destination, "labels", os.path.basename(label_path))
# 移动 label 到目标文件夹
copyfile(label_path, label_destination_path)
# os.rename(label_path, label_destination_path)
print("valid images:", valid_images)
#输出有效label路径列表
print("valid labels:", valid_labels)
print("----处理完成------")
可参考的 mycoco2.yaml
# Example usage: yolo train data=datasets/mycoco2.yaml
# Example usage: yolo task=detect mode=train model=yolov8n.pt data=datasets/mycoco2.yaml epochs=100 imgsz=640 resume=True
# parent
# ├── ultralytics
# └── datasets
# └── mycoco2.yaml
# └── mycoco2
# └──test
# └──train
# └──valid
path: ../datasets/mycoco2 # dataset root dir
train: train/images # train images (relative to 'path')
val: valid/images # val images (relative to 'path')
test: test/images # test images (optional)
# Classes
names:
0: person
1: bicycle
........
2、下载项目文件或git clone https://github.com/ultralytics/ultralytics.git ,并将上述文件夹及内容放入datasets中,形成以下目录。
环境配置
Pip install the ultralytics package including all requirements in a Python>=3.8 environment with PyTorch>=1.7.
pip install ultralytics
进行项目根目录打开训练 yolo task=detect mode=train model=yolov8n.pt data=datasets/mycoco2.yaml epochs=100 imgsz=640 resume=True
二、分类数据集制作
将cat、dog的图片数据集,可参考dealData2.py进行数据集划分,到myclassify中。
其中,train、valid、test的里面只用放所有的训练集图片,cat和dog是我当前需要的分类类别,其中放置对应的类别的图片,根据自身需求创建类别文件夹,放入对应图片即可。
将myclassify.yaml 中类别和类别数量和数据集路径修改好即可训练。
# Example usage: yolo task=detect mode=train model=yolov8n-cls.pt data=datasets/myclassify.yaml epochs=100 imgsz=32
# parent
# ├── ultralytics
# └── datasets
# └── myclassify.yaml
# └── myclassify
# └──test
# └──train
# └──valid
path: ../datasets/myclassify # dataset root dir
train: train # train images (relative to 'path')
val: valid # val images (relative to 'path')
test: test # test images (optional)
# Classes
names:
0: cat
1: dog
nc: 2
执行分类训练:
yolo task=detect mode=train model=yolov8n-cls.pt data=datasets/myclassify.yaml epochs=100 imgsz=32