记录:win10下使用yolo3识别自己的数据集并检测

配置及安装:

yolo3的下载地址:https://github.com/AlexeyAB/darknet

https://github.com/qqwweee/keras-yolo3 解压缩后用pycharm打开。

权重:https://pjreddie.com/media/files/yolov3.weights
并将权重放在keras-yolo3的文件夹下。

在cmd里进入以下文件夹记录:win10下使用yolo3识别自己的数据集并检测_第1张图片
输入:python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

检测试验:

python yolo.py --image
之后在它提示你输入图片名称的时候输入图片地址。
记录:win10下使用yolo3识别自己的数据集并检测_第2张图片
结果:
记录:win10下使用yolo3识别自己的数据集并检测_第3张图片

训练自己的数据集:

1.按照VOC2007数据集的格式创建文件夹。
具体如下:
记录:win10下使用yolo3识别自己的数据集并检测_第4张图片
其中xml文件是使用labelImg软件标注得到的,具体文章链接:
https://blog.csdn.net/qq_45128278/article/details/106470242

2.生成ImageSet/Main/4个文件。
在VOC2007下新建一个python文件,复制如下代码 :

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

运行后生成这些文件:
记录:win10下使用yolo3识别自己的数据集并检测_第5张图片
记录了训练集、测试集等的图片信息。

# 3.生成yolo3所需的train.txt,val.txt,test.txt
在voc_annotation.py中修改以下代码:第一个是上文中运行的图片名,第二个是你要分类的类名。
记录:win10下使用yolo3识别自己的数据集并检测_第6张图片

运行代码后,生成在这里插入图片描述

这是为了生成让yolo3训练代码看得懂的参数。

4、修改参数文件yolo3.cfg
搜索yolo(共出现三次),每次按下图都要修改:
记录:win10下使用yolo3识别自己的数据集并检测_第7张图片
filters是过滤器,计算方法:3*(5+分类数)
classes:你要训练的类别数(我这里是训练两类)
random:原来是1,显存小改为0

5.修改model_data下的voc_classes.txt为自己训练的类别
记录:win10下使用yolo3识别自己的数据集并检测_第8张图片
6.修改train.py代码
直接覆盖:

"""
Retrain the YOLO model for your own dataset.
"""
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping
 
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
 
 
def _main():
    annotation_path = '2007_train.txt'
    log_dir = 'logs/000/'
    classes_path = 'model_data/voc_classes.txt'
    anchors_path = 'model_data/yolo_anchors.txt'
    class_names = get_classes(classes_path)
    anchors = get_anchors(anchors_path)
    input_shape = (416,416) # multiple of 32, hw
    model = create_model(input_shape, anchors, len(class_names) )
    train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir)
 
def train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'):
    model.compile(optimizer='adam', loss={
        'yolo_loss': lambda y_true, y_pred: y_pred})
    logging = TensorBoard(log_dir=log_dir)
    checkpoint = ModelCheckpoint(log_dir + "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5",
        monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)
    batch_size = 10
    val_split = 0.1
    with open(annotation_path) as f:
        lines = f.readlines()
    np.random.shuffle(lines)
    num_val = int(len(lines)*val_split)
    num_train = len(lines) - num_val
    print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
 
    model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),
            steps_per_epoch=max(1, num_train//batch_size),
            validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),
            validation_steps=max(1, num_val//batch_size),
            epochs=500,
            initial_epoch=0)
    model.save_weights(log_dir + 'trained_weights.h5')
 
def get_classes(classes_path):
    with open(classes_path) as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    return class_names
 
def get_anchors(anchors_path):
    with open(anchors_path) as f:
        anchors = f.readline()
    anchors = [float(x) for x in anchors.split(',')]
    return np.array(anchors).reshape(-1, 2)
 
def create_model(input_shape, anchors, num_classes, load_pretrained=False, freeze_body=False,
            weights_path='model_data/yolo_weights.h5'):
    K.clear_session() # get a new session
    image_input = Input(shape=(None, None, 3))
    h, w = input_shape
    num_anchors = len(anchors)
    y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
        num_anchors//3, num_classes+5)) for l in range(3)]
 
    model_body = yolo_body(image_input, num_anchors//3, num_classes)
    print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
 
    if load_pretrained:
        model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
        print('Load weights {}.'.format(weights_path))
        if freeze_body:
            # Do not freeze 3 output layers.
            num = len(model_body.layers)-7
            for i in range(num): model_body.layers[i].trainable = False
            print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
 
    model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
        arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
        [*model_body.output, *y_true])
    model = Model([model_body.input, *y_true], model_loss)
    return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
    n = len(annotation_lines)
    np.random.shuffle(annotation_lines)
    i = 0
    while True:
        image_data = []
        box_data = []
        for b in range(batch_size):
            i %= n
            image, box = get_random_data(annotation_lines[i], input_shape, random=True)
            image_data.append(image)
            box_data.append(box)
            i += 1
        image_data = np.array(image_data)
        box_data = np.array(box_data)
        y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
        yield [image_data, *y_true], np.zeros(batch_size)
 
def data_generator_wrap(annotation_lines, batch_size, input_shape, anchors, num_classes):
    n = len(annotation_lines)
    if n==0 or batch_size<=0: return None
    return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
 
if __name__ == '__main__':
    _main()

7.创建log/000目录。
如图
在这里插入图片描述
用来存放生成的模型。

测试过程:

修改yolo.py文件,如下将self这三行修改为各自对应的路径。
记录:win10下使用yolo3识别自己的数据集并检测_第9张图片
运行python yolo.py --image,输入自己要检测的图片即可。

参考文章:
https://blog.csdn.net/u012746060/article/details/81183006?ops_request_misc=&request_id=&biz_id=102&utm_term=%E4%BD%BF%E7%94%A8yolo3%E8%AE%AD%E7%BB%83%E8%87%AA%E5%B7%B1%E7%9A%84%E6%95%B0%E6%8D%AE%E9%9B%86&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-81183006

测试过程的图是博主的。

你可能感兴趣的:(yolo3)