![cover](https://img-blog.csdnimg.cn/img_convert/a207abb8f4884e9e932676849d81856b.png)
yolov7(同样适用于yolov7-tiny)训练自己的数据集
windows上使用自己的数据集训练yolov7-tiny
花了两天时间来训练yolov7-tiny,踩了不少坑,遂记录一下,希望可以帮到大家
1.环境配置
# Usage: pip install -r requirements.txt
# Base ----------------------------------------
matplotlib>=3.2.2
numpy>=1.18.5,<1.24.0
opencv-python>=4.1.1
Pillow>=7.1.2
PyYAML>=5.3.1
requests>=2.23.0
scipy>=1.4.1
torch>=1.7.0,!=1.12.0
torchvision>=0.8.1,!=0.13.0
tqdm>=4.41.0
protobuf<4.21.3
# Logging -------------------------------------
tensorboard>=2.4.1
# wandb
# Plotting ------------------------------------
pandas>=1.1.4
seaborn>=0.11.0
# Export --------------------------------------
# coremltools>=4.1 # CoreML export
# onnx>=1.9.0 # ONNX export
# onnx-simplifier>=0.3.6 # ONNX simplifier
# scikit-learn==0.19.2 # CoreML quantization
# tensorflow>=2.4.1 # TFLite export
# tensorflowjs>=3.9.0 # TF.js export
# openvino-dev # OpenVINO export
# Extras --------------------------------------
ipython # interactive notebook
psutil # system utilization
thop # FLOPs computation
# albumentations>=1.0.3
# pycocotools>=2.0 # COCO mAP
# roboflow
2.下载yolov7
下载链接如下:https://gitcode.com/WongKinYiu/yolov7/tree/main?utm_source=csdn_github_accelerator&isLogin=1
目录如下图所示:
3.处理数据集
在data的文件夹下面新建文件夹mydata(可做不同的数据集分类),然后在mydata文件夹下面新建如下四个文件夹:
dataSet文件夹:之后会写一个脚本(split_train_val.py)内自动生成train.txt,val.txt,test.txt和trainval.txt四个文件,存放训练集、验证集、测试集图片的路径
images文件夹里面放的是咱们自己的数据集,我的为jpg格式
labels下面放的是咱们数据集的txt格式
xml文件夹下里面则放的是咱们数据集的xml格式
(1)训练集、验证集、测试集的划分
在data文件下新建一个split_train_val.py文件,代码内容如下:
import os
import random
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'E:/yolov7-main/yolov7-main/data/mydata/xml'
txtsavepath = 'E:/yolov7-main/yolov7-main/data/mydata/dataSet'
image_path = 'E:/yolov7-main/yolov7-main/data/mydata/images'
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
file_list = list(range(num))
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(file_list, tv)
train = random.sample(trainval, tr)
ftrainval = open(os.path.join(txtsavepath, 'trainval.txt'), 'w')
ftest = open(os.path.join(txtsavepath, 'test.txt'), 'w')
ftrain = open(os.path.join(txtsavepath, 'train.txt'), 'w')
fval = open(os.path.join(txtsavepath, 'val.txt'), 'w')
for i in file_list:
name = total_xml[i][:-4]
image_file_path = os.path.normpath(os.path.join(image_path, name + '.jpg')) # 构造图片的完整路径
if i in trainval:
ftrainval.write(image_file_path + '\n') # 写入图片完整路径
if i in train:
ftest.write(image_file_path + '\n') # 写入图片完整路径
else:
fval.write(image_file_path + '\n') # 写入图片完整路径
else:
ftrain.write(image_file_path + '\n') # 写入图片完整路径
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()
运行后dataSet文件夹如下图所示:
txt文件中的内容类似于下图:(训练集、验证集、测试集图片的路径)
(2)数据集的转化(xml转化为txt格式):若数据集为txt格式,则跳过此步骤
在mydata文件夹下面新建一个voc_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']
//修改1:我们数据集的分类名称
classes = ["missing_hole","mouse_bite","open_circuit","short","spur","spurious_copper"]
def convert(size, box):
if size[0] == 0:
dw = 0
else:
dw = 1. / size[0]
if size[0] == 0:
dh = 0
else:
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
//修改2:按照自己的文件路径修改
def convert_annotation(image_id):
in_file = open('E:/yolov7-main/yolov7-main/data/mydata/xml/%s.xml' % (image_id))
out_file = open('E:/yolov7-main/yolov7-main/data/mydata/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
if obj.find('difficult'):
difficult = int(obj.find('difficult').text)
else:
difficult = 0
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('E:/yolov7-main/yolov7-main/data/mydata/labels/'):
os.makedirs('E:/yolov7-main/yolov7-main/data/mydata/labels/')
image_ids = open('E:/yolov7-main/yolov7-main/data/mydata/dataSet/%s.txt' % (image_set)).read().strip().split()
list_file = open('E:/yolov7-main/yolov7-main/data/mydata/%s.txt' % image_set, 'w')
for image_id in image_ids:
list_file.write('E:/yolov7-main/yolov7-main/data/mydata/images/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
(3)配置自己数据集的yaml文件啦
在data文件夹路径下新建.yaml文件(我的是pcb.yaml)
内容如下:
//修改为自己的路径
train: E:/yolov7-main/yolov7-main/data/mydata/dataSet/train.txt
val: E:/yolov7-main/yolov7-main/data/mydata/dataSet/val.txt
test: E:/yolov7-main/yolov7-main/data/mydata/dataSet/test.txt
//分类数
nc : 6
depth_multiple: 1.0
width_multiple: 1.0
//类别
names: ['missing_hole','mouse_bite','open_circuit','short','spur','spurious_copper']
5.下载预训练模型
下载yolov7(yolov7-tiny的weights跟pt文件)下载链接如下:Release YOLOv7 · WongKinYiu/yolov7 (github.com)
我下载的是这两个:
6.开始训练啦
根据自己数据集的类别数修改cfg/deploy/yolov7-tiny.yaml中的nc
修改train.py文件
epochs:指的就是训练过程中整个数据集将被迭代多少次,视自己电脑情况而定
batch-size:一次看完多少张图片才进行权重更新,视自己电脑情况而定。
cfg:看你训练的是yolov7还是yolov7-tiny还是其他的
data:就是前面我们建的yaml文件啦
device:device=0通常指的是使用第一个GPU设备
workers:最大数据加载器工作线程数,即指定每个DDP模式下的工作线程数,视自己电脑情况而定。
运行训练命令如下:
python train.py --img 640 --batch 32 --epoch 300 --data data/mydata.yaml --cfg cfg/deploy/yolov7x.yaml --weights weights/yolov7x.pt --device '0'
7 遇到的错误
(1)KeyError: 'anchors'
解决方法:去掉anchors前面的注释
(2)OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
解决方法:在train.py文件中加入:
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
更多推荐
所有评论(0)