darknet-yolov3训练自己的数据

注意:本篇博客直接使用VOC2007数据集

1.数据集

Labelimg软件构建数据集,Labelimg项目地址:https://github.com/tzutalin/labelImg,Labelimg快捷键:

Ctrl + u Load all of the images from a directory
Ctrl + r Change the default annotation target dir
Ctrl + s Save
Ctrl + d Copy the current label and rect box
Space Flag the current image as verified
w Create a rect box
d Next image
a Previous image
del Delete the selected rect box
Ctrl++ Zoom in
Ctrl-- Zoom out
↑→↓← Keyboard arrows to move selected rect box

voc2007数据集目录结构 :

               ----voc2007

                           ----Annotations

                           ----ImageSets

                                        ----Main

                           ----JPEGImages

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

import os
import random

trainval_percent = 0.8
train_percent = 0.8
xmlfilepath = 'VOC2007\Annotations'
txtsavepath = 'VOC2007\ImageSets\Main'
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('VOC2007/ImageSets/Main/trainval.txt', 'w')
ftest = open('VOC2007/ImageSets/Main/test.txt', 'w')
ftrain = open('VOC2007/ImageSets/Main/train.txt', 'w')
fval = open('VOC2007/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:
            ftrain.write(name)
        else:
            fval.write(name)
    else:
        ftest.write(name)

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

在 voc2007同目录下新建voc_labels.py,生成labels。代码如下:

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

#sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]

sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]

classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]


def convert(size, box):
    dw = 1./(size[0])
    dh = 1./(size[1])
    x = (box[0] + box[1])/2.0 - 1
    y = (box[2] + box[3])/2.0 - 1
    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(year, image_id):
    #in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
    #out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, image_id), 'w')
    in_file = open('VOC%s/Annotations/%s.xml' % (year, image_id))
    out_file = open('VOC%s/labels/%s.txt'%(year, 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()
'''
for year, image_set in sets:
    if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
        os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
    image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
    list_file = open('%s_%s.txt'%(year, image_set), 'w')
    for image_id in image_ids:
        list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
        convert_annotation(year, image_id)
    list_file.close()
os.system("cat 2007_train.txt 2007_val.txt 2012_train.txt 2012_val.txt > train.txt")
os.system("cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt > train.all.txt")
'''
for year, image_set in sets:
    if not os.path.exists('VOC%s/labels/'%(year)):
        os.makedirs('VOC%s/labels/'%(year))
    image_ids = open('VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
    list_file = open('%s_%s.txt'%(year, image_set), 'w')
    for image_id in image_ids:
        list_file.write('%s/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
        convert_annotation(year, image_id)
    list_file.close()

os.system("cat 2007_train.txt 2007_val.txt  > train.txt")
os.system("cat 2007_train.txt 2007_val.txt 2007_test.txt  > train.all.txt")

 

2.环境

(1)git clone https://github.com/AlexeyAB/darknet

(2)cd darknet

(3)pip install -r requirements.txt

(4)make

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

(6)测试:./darknet detect cfg/yolov3.cfg weights/yolov3.weights data/dog.jpg    或     ./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/dog.jpg

3.训练模型

(1)下载darknet53.conv.74,将darknet53.conv.74放入其中。

(2)在data目录下新建**.name文件,存放你的数据集类别名称。本文用coco.names:

aeroplane
bicycle
bird
boat
bottle
bus
car
cat
chair
cow
diningtable
dog
horse
motorbike
person
pottedplant
sheep
sofa
train
tvmonitor

(3)在data目录下新建**.data文件,本文用coco.data:

classes = 20#类别数
train = data\2007_train.txt#voc_labels.py生成的训练集的位置
valid = data\2007_test.txt
names = data\coco.names
backup = backup\

(4) 更新cfg文件的classes,本文使用的classes=20。yolo上一卷积层的filters=3*(classes+5),其中5代表的是4个坐标+1个置信度。

(5)开始训练:python ./darknet detector train cfg/voc.data cfg/yolov3-voc.cfg weights/darknet53.conv.74

注意:max_batches = 50200 ### 迭代次数

 

你可能感兴趣的:(目标检测)