Python Yolo V8 训练自己的数据集
前期准备工作
需要使用到的库,需要训练的素材一份图片或者视频
import ultralytics # Yolo V8 本体
import lableimg # 图片标注工具
接着新建一份工作目录如下
--- data
--- Annotations # 存放标记数据
--- images # 存放需要训练的图片素材
--- imageSets # 存放训练集 测试集 验证集的路径数据
--- labels # 存放 Yolo 格式的数据集
视频转图片
可以使用 OpenCV 按帧进行转换,使用如下代码就得到一份图片素材
import os
import cv2
def video_to_frame(video_path):
videCapture = cv2.VideoCapture()
videCapture.open(video_path)
vide_name = os.path.basename(video_path).split('.mp4')[0]
n = 1
frametime = 30
frames = videCapture.get(cv2.CAP_PROP_FRAME_COUNT)
print(frames)
frame_path = os.path.join(os.path.dirname(video_path), vide_name)
if not os.path.exists(frame_path): os.mkdir(frame_path)
for i in range(int(frames)):
ret, frame = videCapture.read()
if ret:
if i % frametime == 0:
pic_path = os.path.join(frame_path, f'{vide_name}_{n}.jpg')
cv2.imencode('.jpg', frame)[1].tofile(pic_path)
print(pic_path)
n += 1
if __name__ == "__main__":
video_folder_path = r'C:\Users\Downloads\Video'
vide_names = os.listdir(video_folder_path)
for video_name in vide_names:
video_path = os.path.join(video_folder_path, video_name)
try:
video_to_frame(video_path)
except Exception as e:
print(f'ERROR : {e}')
进行图片标注
这里就不细讲了,具体可百度 labelimg 的使用
按比例划分训练集和验证集
import os
import random
path_folder_data = os.path.dirname(os.path.realpath(__file__))
os.chdir('./data')
# 训练集和验证集的比例分配
trainval_percent = 0.1
train_percent = 0.9
# 标注文件的路径
xmlfilepath = 'Annotations'
# 生成的txt文件存放路径
txtsavepath = 'ImageSets\Main'
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
ftrainval = open('ImageSets/Main/trainval.txt', 'w')
ftest = open('ImageSets/Main/test.txt', 'w')
ftrain = open('ImageSets/Main/train.txt', 'w')
fval = open('ImageSets/Main/val.txt', 'w')
for i in list:
name = total_xml[i][:-4] + '\n'
if i in trainval:
ftrainval.write(name)
if i in train:
ftest.write(name)
else:
fval.write(name)
else:
ftrain.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()
将标注数据转化为 Yolo 格式
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
path_folder_data = os.path.dirname(os.path.realpath(__file__)) + "\data"
# 原始脚本中包含了VOC2012,这里,我们把它删除
# sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
sets=['train', 'test', 'val']
# classes也需要根据自己的实际情况修改
# classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
classes = ['person', 'bicycle', 'car', 'motorcycle']
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[1])/2.0
y = (box[2] + box[3])/2.0
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):
in_file = open(f'{path_folder_data}//Annotations//{image_id}.xml', encoding='utf-8')
out_file = open(f'{path_folder_data}//labels//{image_id}.txt', '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))
bb = convert((w,h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
for image_set in sets:
if not os.path.exists(f'{path_folder_data}//labels/'):
os.makedirs(f'{path_folder_data}//labels/')
image_ids = open(f'{path_folder_data}//imageSets//Main//{image_set}.txt').read().splitlines()
list_file = open(f'{path_folder_data}//{image_set}.txt', 'w')
for image_id in image_ids:
list_file.write(f'{path_folder_data}//images//{image_id}.jpg\n')
convert_annotation(image_id)
list_file.close()
生成配置文件
# train/val/test sets
train: C:\User\WorkSpace\Python\Yolo\data\train.txt
val: C:\User\WorkSpace\Python\Yolo\data\val.txt
test: C:\User\WorkSpace\Python\Yolo\data\test.txt
# class names
names:
0: person
1: bicycle
2: car
3: motorcycle
# nc: number of classes
nc: 4
开始训练
至此需要训练的数据已准备完毕,可以开始训练,具体参数可以查看官网
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640
# data 为配置文件,epoch 为训练次数,model 为原始模型文件
训练完成后会在 data 下生成 run 文件夹,一路点进去就可以找到训练的结果以及生成的模型文件
训练模型的使用
yolo detect predict model=yolov8n.pt source="https://ultralytics.com/images/bus.jpg" save=True # predict with official model
yolo detect predict model=path/to/best.pt source="https://ultralytics.com/images/bus.jpg" save=True # predict with custom model