写在前面:感谢HH师姐的帮助
一、环境部署:
代码下载:
https://github.com/ultralytics/yolov5
创建虚拟环境:
conda create -n yolov5 python==3.7
进入环境 :
conda activate yolov5
安装所需库:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt(Anaconda prompt 需要进入requirements.txt所在目录)
这一步可能会出现以下错误:
ERROR: Could not find a version that satisfies the requirement torch>=1.6.0 (from -r requirements.txt (line 12)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)
ERROR: No matching distribution found for torch>=1.6.0 (from -r requirements.txt (line 12))
因为torch 和torchvision的下载需要翻墙,导致下载失败,此时我们需要另外下载
如果需要cpu版本的:
https://www.jb51.net/article/186132.htm
如果需要gpu版本的:
1).打开yolov5-master文件夹下的requirements.txt,注释掉这两行
2).重新pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
3).翻墙去google下载 torch-1.6.0-cp37-cp37m-win_amd64.whl 以及 torchvision-0.7.0-cp37-cp37m-win_amd64.whl
在这里提供百度网盘链接:
链接:https://pan.baidu.com/s/1amt6_KLC2xaM6meHtdbo5A
提取码:e5wg
链接:https://pan.baidu.com/s/1R_n_HcSme5C0uXrMrZsL5Q
提取码:9l52
我是不是你们的小可爱 ( •̀ ω •́ )
4)命令版进入存放下载的文件夹下面,输入命令:
pip install torch-1.6.0-cp37-cp37m-win_amd64.whl
pip install torchvision-0.7.0-cp37-cp37m-win_amd64.whl
二、准备数据集
数据存放位置与数据结构
1.在本来存在的data文件夹里新建 Annotations,images,image
Sets,IPEGimages,labels.
2.JPEGImages放图片,再把JPEGImages中的图片复制到images中。Annotations放.xml文件
3.根目录创建make_txt.py,并运行
import os
import random
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'data/Annotations'
txtsavepath = 'data/ImageSets'
total_xml = os.listdir(xmlfilepath)
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('data/ImageSets/trainval.txt', 'w')
ftest = open('data/ImageSets/test.txt', 'w')
ftrain = open('data/ImageSets/train.txt', 'w')
fval = open('data/ImageSets/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()
自动生成所需的test train val.txt 默认trainval_percent = 0.1,train_percent = 0.9,可自己更改
4.根目录创建2voc_label.py并运行
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
sets = ['train', 'test','val']
classes = ['corner']
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('data/Annotations/%s.xml' % (image_id))
out_file = open('data/labels/%s.txt' % (image_id), '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()
print(wd)
for image_set in sets:
if not os.path.exists('data/labels/'):
os.makedirs('data/labels/')
image_ids = open('data/ImageSets/%s.txt' % (image_set)).read().strip().split()
list_file = open('data/%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write('data/images/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
默认classes = [‘corner’],需要改成自己的训练集的分类标签
三、开始训练
需要修改以下文件:
1.coco.yaml
以我的为例:
红框里改成之前生成的txt的路径
蓝框改成自己训练的类别以及标签
2.models 下的yaml 文件
官方提供了四个模型,可以根据自己的需求选择一个模型使用,其中yolov5l的性价比最高,5X效果最好
把nc改成自己的数据类别数就Ok
当然也有余力的话也可以修改anchors+网络结构
3.train.py
需要修改的就这些:
算力不够的话,红框可以改小一些,黄框改成你选用的模型路径,蓝框改成之前更改的coco.yaml的路径
四、查看训练结果
文件路径如图
它们代表的是这些意思:
1)train*.jpg :
training images, labels and augmentation effects.
2)test_batch0_gt.jpg:
test batch 0 ground truth labels
3)test_batch0_pred.jpg:
test batch 0 predictions
4)results.txt:
Training losses and performance metrics ;
Partially completed results.txt files can be plotted with from utils.utils import plot_results; plot_results().
Here we show YOLOv5s trained on coco128 to 300 epochs, starting from scratch (blue), and from pretrained yolov5s.pt (orange).
5)weights
存放训练好的两个模型:best.pt和last.pt
五、测试自己的数据集
1.准备相应文件
以我的为例:
蓝框放被测试的文件,需要把make_txt.py生成的test.txt中对应的图片放进去,图片多的话编个代码,总之test的图片不能和train、trainval的图片重合
2.修改detect
红框:训练好的模型的路径
黄框:被测试的图片路径
蓝框:测试完的结果存放路径
*六、其他问题
见我的另一篇博文https://blog.youkuaiyun.com/qq_39542170/article/details/109244408
参考资料
1.官方教程:https://github.com/ultralytics/yolov5
2.YOLOV5测试及训练自己的数据集
3.yolov5训练自己的数据集