- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
拉取项目
git clone https://github.com/ultralytics/ultralytics
安装依赖
cd ultralytics
pip install -r requirement.txt
pip install -e .
准备数据集
下载数据集zip包,并解压,数据集的地址在原作者博客中有。
unzip archive (3).zip
mv archive (3) fruit_data
制作数据集
以下操作全部在fruit_data目录下
cd fruit_data
生成图片列表,划分数据集
使用脚本split_train_val.py,从标注xml文件中抽取出图像的列表和标签信息,并保存到相应的文件中。
#!/usr/bin/env python
# coding: utf-8import os
import random
import argparseparser = argparse.ArgumentParser()parser.add_argument('--xml_path', default='annotations', type=str, help='input xml label path')
parser.add_argument('--txt_path', default='imageSets/Main', type=str, help='output txt label path')opt = parser.parse_args()trainval_percent = 1.0
train_percent = 0.9xmlfilepath = opt.xml_path
txtsavepath = opt.txt_pathtotal_xml = os.listdir(xmlfilepath)if not os.path.exists(txtsavepath):os.makedirs(txtsavepath)num = len(total_xml)list_index = range(num)tv = int(num * trainval_percent)
tr = int(tv * train_percent)trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_test = open(txtsavepath + '/test.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')for i in list_index:name = total_xml[i][:-4] + '\n'if i in trainval:file_trainval.write(name)if i in train:file_train.write(name)else:file_val.write(name)else:file_test.write(name)file_trainval.close()
file_train.close()
file_val.close()
file_test.close()
python split_train_val.py
生成VOC格式的数据文件
因为YOLO框架使用的是VOC格式的数据集,因此需要生成一个VOC格式的数据文件
使用脚本voc_label.py
#!/usr/bin/env python
# coding: utf-8import xml.etree.ElementTree as ET
import os
from os import getcwdsets = ['train', 'val', 'test']classes = ['banana', 'snake fruit', 'pineapple', 'dragon fruit']abs_path = os.getcwd()
print(abs_path)def convert(size, box):dw = 1. / (size[0])dh = 1. / (size[1])x = (box[0] + box[1]) / 2.0 - 1y = (box[2] + box[3]) / 2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn x, y, w, hdef convert_annotation(image_id):in_file = open('./annotations/%s.xml' % (image_id), encoding='UTF-8')out_file = open('./labels/%s.txt' % (image_id), 'w')tree = ET.parse(in_file)root = tree.getroot()filename = root.find('filename').textfilenameFormat = filename.split('.')[1]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').textcls = obj.find('name').textif 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 = bif b2 > w:b2 = wif b4 > h:b4 = hb = (b1, b2, b3, b4)bb = convert((w, h), b)out_file.write(str(cls_id) + ' ' + ' '.join([str(a) for a in bb]) + '\n')return filenameFormatwd = getcwd()for image_set in sets:if not os.path.exists('./labels/'):os.makedirs('./labels')image_ids = open('./imageSets/Main/%s.txt' % (image_set)).read().strip().split()list_file = open('./%s.txt' % (image_set), 'w')for image_id in image_ids:filenameFormat = convert_annotation(image_id)list_file.write(abs_path + '/images/%s.%s\n' % (image_id, filenameFormat))list_file.close()
python voc_label.py
编写数据集配置文件
在项目根目录下创建一个文件data.yaml
cd ..
vim data.yaml
配置文件内容如下
train: ./data/train.txt
val: ./data/val.txt# number of classes
nc: 4# 类别名
names: ['banana', 'snake fruit', 'pineapple', 'dragon fruit']
开始训练
yolo task=detect mode=train model=yolov8s.yaml data=/root/autodl_tmp/ultralytics/data.yaml epochs=100 batch=4
训练过程如下:
训练结果
通过上面训练结束可以看出,总体上达到了98.7%的准确率,99.7%的召回率,效果还是非常不错的。
训练过程如图
训练结果如图