上一次初步的介绍了一下Yolov8,这次就详细的说明一下如何训练自己的数据集。首先要准备数据,我这里用的是K同学啊的水果数据集。该数据集一共包括两个部分,图片和数据。图片是不同角度下的水果照片,数据集包括水果在图片里的位置,图片大小等信息,格式为xml。数据如下:
有了以上的数据和图片后,我们就可以训练自己的数据集了。参照coco128的数据集,我们得要将xml文件转换成我们需要的文件格式,文件格式如下:
以第一行为例,第一个数字代表的是目标的序列,后面的数字是目标的位置信息。将xml转换为上图格式的代码如下:
import os
import xml.etree.ElementTree as ET
if not os.path.exists('./labels'):
os.makedirs('./labels')
classes = ['pineapple', 'snake fruit', 'dragon fruit']
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[1])/2
y = (box[2] + box[3])/2
w = box[1] - box[0]
h = box[3] - box[2]
x = x*dw
y = y*dh
w = w*dw
h = h*dh
return x, y, w, h
def xml_to_yolo(name):
in_file = open('./annotations/%s.xml' % name, encoding='UTF-8')
out_file = open('./labels/%s.txt' % name, 'w')
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')
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')
for file in os.listdir('./images'):
name = file.split('.')[0]
xml_to_yolo(name)
以上的代码需要根据你的数据集进行调整,完成后我们就得到了labels的数据标注集,参照数据集coco128,我们建立以下的文件:
先建立shuiguo文件夹,下面有images和labels,再在里面分别创建train文件夹,再将我们图片和数据标注集分别放入train文件夹里。完成以上步骤后就可以开始训练了,这里的yaml文件的内容如下:
path: D:\pythonProject\yolov8\shuiguo # 数据集源路径root dir
train: images/train2017 # root下的训练集地址 128 images
val: images/train2017 # root下的验证集地址 128 images
test: # root下的验证集地址 128 images
# 数据集类别信息
nc: 3 # 数据集类别数量
names: ['pineapple', 'snake fruit', 'dragon fruit'] # 数据集类别名
训练代码如下,训练次数为100:
from ultralytics import YOLO
model = YOLO('yolov8n.pt') # load a pretrained YOLOv8n detection model
model.train(data='shuiguo.yaml', epochs=100) # train the model
训练好后我们就可以在runs/detect/train/weights文件夹中找到我们训练好的模型,一般使用best.pt模型。让我们来看一下结果:
from ultralytics import YOLO
from PIL import Image
model = YOLO('runs/detect/train3/weights/best.pt')
picture = 'images/fruit13.jpg'
results = model(picture)
for i, r in enumerate(results):
# Plot results image
im_bgr = r.plot() # BGR-order numpy array
im_rgb = Image.fromarray(im_bgr[..., ::-1]) # RGB-order PIL image
# Show results to screen (in supported environments)
r.show()
这里我们就完成了训练自己的模型了。