python训练数据集_Python-yolov3训练自己的数据集,pytorchyolov3

注意:本篇博客直接使用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

在根目录下新建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 = '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()

在 根目录下新建voclabel.py,生成labels。代码如下:

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", "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

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

数据格式如下图:

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxeW91aGFwcHk=,size_16,color_FFFFFF,t_70

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

2.环境

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

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

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

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

3.训练模型

(1)下载。

(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 train.py --data data/coco.data --cfg cfg/yolov3.cfg  --weights weights/yolov3.pt

中断后,恢复训练:python train.py --data data/coco.data --cfg cfg/yolov3.cfg  --weights weights/yolov3.pt  --resume

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

(6)测试:

python detect.py --cfg cfg/yolov3.cfg --weights/******.pt --source data/samples/file.jpg

Image:

--source file.jpg

Video:

--source file.mp4

(7)评估模型:

python test.py --data  data/coco.data  --cfg cfg/yolov3.cfg --weights weights/******.pt

(8)可视化:

Python -c from utils import utils; utils.plot_results()

你可能感兴趣的:(python训练数据集)