yolov5训练自己的VOC数据集

一.VOC数据准备

 

voc数据集目录结构 :

               ----voc

                           ----Annotations

                           ----ImageSets

                                        ----Main

                           ----JPEGImages

在根目录下新建makeTXT.py,将数据集划分,并且在Main文件夹下构建4个TXT:train.txt,test.txt,trainval.txt,val.txt。代码如下:

import os
import random
 
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'voc/Annotations'
txtsavepath = 'voc/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('voc/ImageSets/Main/trainval.txt', 'w')
ftest = open('voc/ImageSets/Main/test.txt', 'w')
ftrain = open('voc/ImageSets/Main/train.txt', 'w')
fval = open('data/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()

 在根目录下新建voc_label.py,生成labels文件夹,及用于yolov5训练的train.txt,text.txt,val.txt。代码如下:

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 = ["aeroplane"]
 
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()

用于训练的数据集如下图:

其中images里面存放的是JPEGImages的全部图片。

二.环境搭建

(1)git clone https://github.com/ultralytics/yolov5.git

(2)pip install -U -r requirements.txt

(3)在项目根目录下新建weights文件夹,下载权重文件,将其放入weights文件夹中。

三.训练自己的模型

(1)在data文件夹里面新建test.yaml,

# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
train: data/train.txt  # voclabel.py生成的train.txt的路径
val: data/train.txt   # voclabel.py生成的val.txt的路径

# number of classes
nc: 1

# class names
names: ['person']

(2)在models文件夹里面找到自己需要的<model>.yaml,修改nc为自己的类别数:

# parameters
nc: 1  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple

# anchors
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

# YOLOv5 backbone
backbone:
  # [from, number, module, args]
  [[-1, 1, Focus, [64, 3]],  # 0-P1/2
   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4
   [-1, 3, BottleneckCSP, [128]],
   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8
   [-1, 9, BottleneckCSP, [256]],
   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16
   [-1, 9, BottleneckCSP, [512]],
   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32
   [-1, 1, SPP, [1024, [5, 9, 13]]],
   [-1, 3, BottleneckCSP, [1024, False]],  # 9
  ]

# YOLOv5 head
head:
  [[-1, 1, Conv, [512, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 6], 1, Concat, [1]],  # cat backbone P4
   [-1, 3, BottleneckCSP, [512, False]],  # 13

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 4], 1, Concat, [1]],  # cat backbone P3
   [-1, 3, BottleneckCSP, [256, False]],  # 17 (P3/8-small)

   [-1, 1, Conv, [256, 3, 2]],
   [[-1, 14], 1, Concat, [1]],  # cat head P4
   [-1, 3, BottleneckCSP, [512, False]],  # 20 (P4/16-medium)

   [-1, 1, Conv, [512, 3, 2]],
   [[-1, 10], 1, Concat, [1]],  # cat head P5
   [-1, 3, BottleneckCSP, [1024, False]],  # 23 (P5/32-large)

   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

(3)训练模型:python train.py --data data/test.yaml --cfg models/<model>.yaml  --weights weights/yolov5s.pt --device 0

device=0表示用第1个GPU训练

中断后,恢复训练:python train.py --data data/test.yaml --cfg models/<model>.yaml  --weights weights/yolov5s.pt --device 0  --resume

注意:

官方的训练:

 python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64
                                         yolov5m                                40
                                         yolov5l                                24
                                         yolov5x                                16

(4)训练之后,权重会保存在 ./runs 文件夹里面的每个 exp 文件里面的 weights文件夹下。

(5)推理:图片结果会保存在 ./inferenct/output/ 文件夹下:python detect.py --source 图片路径 --weights ./weights/(自己训练的模型).pt

python detect.py --source 0 # webcam

            file.jpg # image

            file.mp4 # video

             path/ # directory

          path/*.jpg # glob

四:生成ONNX

(1)pip install onnx

(2)python ./models/export.py --weights ./weights/(自己训练的模型).pt --img 640 --batch 4

 

 

 

版权声明:本文为CSDN博主「qqyouhappy」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qqyouhappy/article/details/110451619

qqyouhappy

我还没有学会写个人说明!

暂无评论

发表评论

相关推荐

YOLO-V3-SPP详细解析

YOLO-V3-SPP 继前两篇简单的YOLO博文 YOLO-V1 论文理解《You Only Look Once: Unified, Real-Time Object Detection》YOLO-V2论文理解《YOLO9000: Bet

目标检测部署(卡牌识别)

最近在折腾yolov5,训练了一个识别纸牌的模型,最后使用onnxruntime进行部署,感兴趣的可以上github上clone下来玩玩,模型的权重文件上传到了百度网盘,链接

Yolo(3)(项目)Yolo v3 目标检测(85分类)

目录 基础理论 一、 读取文件 二、神经网络初始化 1、搭建神经网络 2、GPU加速 三、打开摄像头、按帧读取图像 四、向神经网络输入 五、获取神经网络输出 1、获取各层名称 2、获取输出层名称 3、获取输出层图像&#xff

基于YOLOv5的垃圾目标检测

使用yolov5实现垃圾目标检测(有图形化界面,webapp)。 计算机视觉爱好者,有自己的算力(8块2080Ti),熟练运用pytorch深度学习框架&#x