YOLOV7训练专属于自己的目标检测模型(保姆级教程,含数据集预处理)

  • ubuntu20.04
  • cuda11.0
  • cudnn8.0.4
  • python3.8
  • torch1.12.0
  • torchvision0.11.0

(1)把yolov7克隆到本地

git clone https://github.com/WongKinYiu/yolov7.git

(2)指定格式存放数据集

在data目录下新建Annotations, images, ImageSets, labels 四个文件夹
images目录下存放数据集的图片文件
Annotations目录下存放图片的xml文件(labelImg标注)

目录结构如下所示

.
├── ./data
│   ├── ./data/Annotations
│   │   ├── ./data/Annotations/fall_0.xml
│   │   ├── ./data/Annotations/fall_1000.xml
│   │   ├── ./data/Annotations/fall_1001.xml
│   │   ├── ./data/Annotations/fall_1002.xml
│   │   ├── ./data/Annotations/fall_1003.xml
│   │   ├── ./data/Annotations/fall_1004.xml
│   │   ├── ...

│   ├── ./data/images
│   │   ├── ./data/images/fall_0.jpg
│   │   ├── ./data/images/fall_1000.jpg
│   │   ├── ./data/images/fall_1001.jpg
│   │   ├── ./data/images/fall_1002.jpg
│   │   ├── ./data/images/fall_1003.jpg
│   │   ├── ./data/images/fall_1004.jpg
│   │   ├── ...

│   ├── ./data/ImageSets
│   └── ./data/labels
│   ├── ./data/coco.yaml
│   ├── ./data/hyp.scratch.p5.yaml
│   ├── ./data/hyp.scratch.p6.yaml
│   ├── ./data/hyp.scratch.tiny.yaml
├── ./cfg
├── ./detect.py
├── ./figure
├── ./hubconf.py
├── ./inference
├── ./models
├── ./README.md
├── ....

(3)按比例划分数据集

在yolov7根目录下新建一个文件splitDataset.py
随机分配训练/验证/测试集图片,代码如下所示:

import os
import random

trainval_percent = 0.9
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:
            ftrain.write(name)
        else:
            fval.write(name)
    else:
        ftest.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

(4)将xml文件转换成YOLO系列标准读取的txt文件

在同级目录下再新建一个文件XML2TXT.py
注意classes = [“…”]一定需要填写自己数据集的类别,在这里我是一个类别”fall”,因此classes = [“fall”],代码如下所示:
如果数据集中的类别比较多不想手敲类别的,可以使用(5)中的脚本直接获取类别,同时还能查看各个类别的数据量,如果不想可以直接跳过(5)。


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 = ['fall']

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):
    '''
    将对应文件名的xml文件转化为label文件,xml文件包含了对应的bunding框以及图片长款大小等信息,
    通过对其解析,然后进行归一化最终读到label文件中去,也就是说
    一张图片文件对应一个xml文件,然后通过解析和归一化,能够将对应的信息保存到唯一一个label文件中去
    labal文件中的格式:calss x y w h  同时,一张图片对应的类别有多个,所以对应的bunding的信息也有多个
    '''

    in_file = open('data/Annotations/%s.xml' % (image_id), encoding='utf-8')

    out_file = open('data/labels/%s.txt' % (image_id), 'w', encoding='utf-8')

    tree = ET.parse(in_file)

    root = tree.getroot()

    size = root.find('size')

    if size != None:

        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))
            print(image_id, cls, b)

            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:
    '''
    对所有的文件数据集进行遍历
    做了两个工作:
    1.将所有图片文件都遍历一遍,并且将其所有的全路径都写在对应的txt文件中去,方便定位
    2.同时对所有的图片文件进行解析和转化,将其对应的bundingbox 以及类别的信息全部解析写到label 文件中去
         最后再通过直接读取文件,就能找到对应的label 信息
    '''

    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()

(5)查看自定义数据集标签类别及数量

在同级目录下再新建一个文件ViewCategory.py,将代码复制进去

import os
from unicodedata import name
import xml.etree.ElementTree as ET
import glob

def count_num(indir):
    label_list = []

    os.chdir(indir)
    annotations = os.listdir('.')
    annotations = glob.glob(str(annotations) + '*.xml')

    dict = {}
    for i, file in enumerate(annotations):

        in_file = open(file, encoding='utf-8')
        tree = ET.parse(in_file)
        root = tree.getroot()

        for obj in root.iter('object'):
            name = obj.find('name').text
            if (name in dict.keys()):
                dict[name] += 1
            else:
                dict[name] = 1

    print("各类标签的数量分别为:")
    for key in dict.keys():
        print(key + ': ' + str(dict[key]))
        label_list.append(key)
    print("标签类别如下:")
    print(label_list)

if __name__ == '__main__':

    indir = 'data/Annotations'
    count_num(indir)

至此数据集的准备已经就绪,索引文件在data目录下的train.txt/val.txt/test.txt

(1)安装requirements

首先需要先利用终端进入yolov7文件夹,创建python环境,这里以Anaconda举例

cd yolov7
conda create -n yolov7 python=3.8
conda activate yolov7
pip install -r requirements.txt

(2)修改模型配置文件

进入cfg/training文件夹,选择需要训练的模型配置文件,这里选择yolov7.yaml,将其中的nc修改为自己的类别数量,这里修改为1


nc: 1
depth_multiple: 1.0
width_multiple: 1.0

anchors:
  - [12,16, 19,36, 40,28]
  - [36,75, 76,55, 72,146]
  - [142,110, 192,243, 459,401]

backbone:

  [[-1, 1, Conv, [32, 3, 1]],

   [-1, 1, Conv, [64, 3, 2]],
   [-1, 1, Conv, [64, 3, 1]],

   [-1, 1, Conv, [128, 3, 2]],
   [-1, 1, Conv, [64, 1, 1]],
   [-2, 1, Conv, [64, 1, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [[-1, -3, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [256, 1, 1]],

   [-1, 1, MP, []],
   [-1, 1, Conv, [128, 1, 1]],
   [-3, 1, Conv, [128, 1, 1]],
   [-1, 1, Conv, [128, 3, 2]],
   [[-1, -3], 1, Concat, [1]],
   [-1, 1, Conv, [128, 1, 1]],
   [-2, 1, Conv, [128, 1, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [[-1, -3, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [512, 1, 1]],

   [-1, 1, MP, []],
   [-1, 1, Conv, [256, 1, 1]],
   [-3, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [256, 3, 2]],
   [[-1, -3], 1, Concat, [1]],
   [-1, 1, Conv, [256, 1, 1]],
   [-2, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [[-1, -3, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [1024, 1, 1]],

   [-1, 1, MP, []],
   [-1, 1, Conv, [512, 1, 1]],
   [-3, 1, Conv, [512, 1, 1]],
   [-1, 1, Conv, [512, 3, 2]],
   [[-1, -3], 1, Concat, [1]],
   [-1, 1, Conv, [256, 1, 1]],
   [-2, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [[-1, -3, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [1024, 1, 1]],
  ]

head:
  [[-1, 1, SPPCSPC, [512]],

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [37, 1, Conv, [256, 1, 1]],
   [[-1, -2], 1, Concat, [1]],

   [-1, 1, Conv, [256, 1, 1]],
   [-2, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [256, 1, 1]],

   [-1, 1, Conv, [128, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [24, 1, Conv, [128, 1, 1]],
   [[-1, -2], 1, Concat, [1]],

   [-1, 1, Conv, [128, 1, 1]],
   [-2, 1, Conv, [128, 1, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [-1, 1, Conv, [64, 3, 1]],
   [[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [128, 1, 1]],

   [-1, 1, MP, []],
   [-1, 1, Conv, [128, 1, 1]],
   [-3, 1, Conv, [128, 1, 1]],
   [-1, 1, Conv, [128, 3, 2]],
   [[-1, -3, 63], 1, Concat, [1]],

   [-1, 1, Conv, [256, 1, 1]],
   [-2, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [-1, 1, Conv, [128, 3, 1]],
   [[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [256, 1, 1]],

   [-1, 1, MP, []],
   [-1, 1, Conv, [256, 1, 1]],
   [-3, 1, Conv, [256, 1, 1]],
   [-1, 1, Conv, [256, 3, 2]],
   [[-1, -3, 51], 1, Concat, [1]],

   [-1, 1, Conv, [512, 1, 1]],
   [-2, 1, Conv, [512, 1, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [-1, 1, Conv, [256, 3, 1]],
   [[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
   [-1, 1, Conv, [512, 1, 1]],

   [75, 1, RepConv, [256, 3, 1]],
   [88, 1, RepConv, [512, 3, 1]],
   [101, 1, RepConv, [1024, 3, 1]],

   [[102,103,104], 1, IDetect, [nc, anchors]],
  ]

(3)修改数据加载配置文件

进入data/文件夹,新建fall.yaml,内容如下:

train: ./data/train.txt
val: ./data/val.txt
test: ./data/test.txt

nc: 1

names: ['fall']

至此,配置文件修改完成

yolov7仓库中有两个训练脚本,一个叫train.py,一个叫train_aux.py,前者是训练P5的模型,包含yolov7-tiny、yolov7-tiny-silu、yolov7、yolov7x,后者是训练P6的模型,包含yolov7-w6、yolov7-e6、yolov7-d6、yolov7-e6e。


python train.py --weights yolov7.pt --data data/fall.yaml --epochs 300 --batch-size 8 --cfg cfg/training/yolov7.yaml --workers 0 --device 0 --img-size 640 640

python train_aux.py --weights yolov7-e6e.pt --data data/fall.yaml --epochs 300 --batch-size 8 --cfg cfg/training/yolov7-e6e.yaml --workers 0 --device 0 --img-size 1280 1280

其中,–weights是指预训练模型权重,可以去yolov7官方链接下载,指定到相应目录下(推荐),如果没有配置网络可能会存在git不了权重文件
–data是指数据加载文件路径
–epoch是指模型训练轮次
–batch-size是指一批次输入多少数据一起训练,根据自己显卡的显存决定
–cfg是指模型加载文件路径,关于–cfg中的training和deploy可以参考这篇文章:training和deploy的区别
–workers是指dataloader同时读取多少个进程,如果num_worker设为0,意味着每一轮迭代时,dataloader不再有自主加载数据到RAM这一步骤(因为没有worker了),而是在RA中找batch,找不到时再加载相应的batch。缺点当然是速度慢。设置为0可以避免一些错误发生
–device是指选用几号GPU
–img-size是指训练集和测试集图像大小,可选640或1280等
–rect是指是否采用矩阵推理的方式去训练模型,采用矩阵推理就不要求送入的训练的图片是正方形
–resume断点续训
–evolve超参数进化,模型提供的默认参数是通过在COCO数据集上使用超参数进化得来的
–linear-lr利用余弦函数对训练中的学习率进行调整

如果计算机上存在多张GPU卡,则可以使用分布式训练方法:


python -m torch.distributed.launch --nproc_per_node 4 --master_port 9527 train.py --workers 8 --device 0,1,2,3 --sync-bn --batch-size 8 --data data/fall.yaml --img 640 640 --cfg cfg/training/yolov7.yaml --weights '' --name yolov7 --hyp data/hyp.scratch.p5.yaml

python -m torch.distributed.launch --nproc_per_node 8 --master_port 9527 train_aux.py --workers 8 --device 0,1,2,3,4,5,6,7 --sync-bn --batch-size 8 --data data/fall.yaml --img 1280 1280 --cfg cfg/training/yolov7-e6e.yaml --weights '' --name yolov7-w6 --hyp data/hyp.scratch.p6.yaml

使用test.py文件可以对训练出的模型进行测试,与训练命令基本类似,但是这里需要注意的是,需要把:


python test.py --weights exp/best.pt --data data/fall.yaml --batch-size 8 --device 0 --img-size 640 640

python detect.py --weights runs/train/exp/weights/best.pt --source 0

使用export.py脚本,可以导出成中间格式的onnx模型

python export.py --weights runs/train/exp/best.pt

–weights是通过yolov7训练得到的pt文件,一般存在于runs/train下面的文件夹中,导出后,方便后续部署(onnx/tensorrt/openvino/coreml)

Original: https://blog.csdn.net/weixin_45921929/article/details/126448031
Author: Patience�
Title: YOLOV7训练专属于自己的目标检测模型(保姆级教程,含数据集预处理)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/647532/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球