pytorch框架yolov3算法训练自己数据集 win7~win10

本文介绍了如何在Win7~Win10环境下使用PyTorch框架训练YOLOv3算法识别自定义数据集。内容包括环境搭建(PyTorch、CUDA、CUDNN的安装)、数据集构建(使用Labelimg标注,转换为VOC2007格式)、配置文件更新、模型训练、图片和视频测试以及摄像头测试。还提供了可视化结果的实现方法和完整代码的百度云链接。
摘要由CSDN通过智能技术生成

1. 环境搭建

首先需要安装的工具pytorch,这是一个从torch改进过来的框架,进入官网的网站,选择自己的电脑系统,下载方式,语言,还有对应的CUDA,此时会给出一行pip命令,复制命令,打开cmd命令行,粘贴,同时加上国内源提高下载速度,等待2个钟头左右,pytorch安装完毕。
不同的pytorch有不同的CUDA和CUDNN的版本。CUDA和CUDNN英伟达出品的并行计算架构,简单通俗的说就是可以让GPU代替CPU的计算,当然由于是并发,所以处理大量运算的时候速度更快,在下载CUDA的时候一定要注意是否和之前pytorch下载的时候选择的CUDA版本一致,下载地址就在英伟达的官方网站首页。Cudnn是一个加速库,面向神经网络,同样可以在英伟达的官网找到,也要注意支持的CUDA版本。
在全部下载完毕后,输出代码torch.cuda.device(0)和torch.cuda.is.available()测试GPU是否能正常使用,如果不行说明CUDA没有安装好,或者显卡不支持。
pytorch安装连接 https://pytorch.org/

2. 数据集构建

1. xml文件生成需要Labelimg软件

在Windows下使用LabelImg软件进行标注,快捷键:

Ctrl + u 加载目录中的所有图像,鼠标点击Open dir同功能
Ctrl + r 更改默认注释目标目录(xml文件保存的地址)
Ctrl + s 保存
Ctrl + d 复制当前标签和矩形框 space 将当前图像标记为已验证 w
创建一个矩形框
d 下一张图片
a 上一张图片
del 删除选定的矩形框
Ctrl++ 放大
Ctrl-- 缩小
↑→↓← 键盘箭头移动选定的矩形框

2. VOC2007 数据集格式

-data
---- VOCdevkit2007
---- VOC2007
---- Annotations (标签XML文件,用对应的图片处理工具人工生成的)
---- ImageSets (生成的方法是用sh或者MATLAB语言生成)
---- ---- test.txt
---- ---- train.txt
---- ---- trainval.txt
---- ---- val.txt
- JPEGImages(原始文件)
- labels (xml文件对应的txt文件)

imageSets下面的文件可以由makeTxt.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()

xml对应的txt文件由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']

classes = ["face","face_mask"]  # 我们只是检测细胞,因此只有一个类别


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')
    height=root.find('height')
    w=1024
    h=1024
    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')
       # out_file.write(str(cls_id) + " " + " ".join([str(a) for a in b]) + '\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()


此时为了避免错误检查一下xml文件,是否有size=0的情况,可以通关python进行批量删除,代码如下:

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
def convert_annotation(image_id):
    in_file = open('data/Annotations/%s.xml' % (image_id))
    path='data/Annotations/%s.xml' % (image_id)
    path2='data/Annotations/%s.xml' % (image_id)
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    if(size is None):
        print(image_id)
        in_file.close()
        os.remove(path)
    else:
        w=int(size.find('width').text)
        h = int(size.find('height').text)
        if(w==0 or h==0):
            print(image_id)
            in_file.close()
            os.remove(path)      
image_ids =[x for x in range(100,6366)]
for image_id in image_ids:
    convert_annotation(image_id)




若有size=0的情况,可重新执行上面两段代码

3. 创建*.names

其中保存的是你的所有的类别,每行一个类别,如data/mask.names:
face face_mask

4. 更新data/mask.data

classes = 2 # 改成你的数据集的类别个数
train = data/train.txt # 通过voc_label.py文件生成的txt文件
valid = data/test.txt # 通过voc_label.py文件生成的txt文件
names = data/mask.names # 记录类别
backup = backup/ # 记录checkpoint存放位置
eval = coco # 选择map计算方式

5. 更新cfg文件,修改类别相关信息

[net]
# Testing
batch=1
subdivisions=1
# Training
# batch=64
# subdivisions=2
width=416
height=416
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1

learning_rate=0.001
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1

[convolutional]
batch_normalize=1
filters=16
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=2

[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=2

[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=2

[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=2

[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=2

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[maxpool]
size=2
stride=1

[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky

###########

[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky

[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky

[convolutional]
size=1
stride=1
pad=1
filters=21
activation=linear



[yolo]
mask = 3,4,5
anchors = 10,14,  23,27,  37,58,  81,82,  135,169,  344,319
classes=2
num=6
jitter=.3
ignore_thresh = .7
truth_thresh = 1
random=1

[route]
layers = -4

[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky

[upsample]
stride=2

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值