keras-yolo3-master使用记录

keras-yolo3-master使用记录

    • 源码下载 环境配置 快速测试
    • 制作自己的项目
    • 生成yolo3所需的train.txt,val.txt,test.txt
    • 修改model_data下的文件,放入你的类别,coco,voc这两个文件都需要修改。
    • 训练自己的网络

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

源码下载 环境配置 快速测试

在macos windows liunx系统都测试过,本文采用macos

  1. 项目代码:https://github.com/qqwweee/keras-yolo3

  2. 下载yolo3weights :https://pjreddie.com/darknet/yolo/

    将yolo3weights文件夹放到keras-yolo3-master文件夹里

  3. terminal cd 到keras-yolo3-master文件夹
    生成现在权重下h5文件:
    python3 convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

  4. 进行快速测试,看看能不能用。
    terminal cd到keras-yolo3-master目录下
    python3 yolo_video.py --image
    之后让你输入图片路径:(若将图片放在keras-yolo3-master文件夹下,直接输入相对地址即可)

制作自己的项目

  1. 下载VOC2007数据集
    下载地址: https://pjreddie.com/projects/pascal-voc-dataset-mirror/

  2. 这里面用到的文件夹是Annotation、ImageSets和JPEGImages

    其中文件夹Annotation中主要存放xml文件,每一个xml对应一张图像在这里插入图片描述;而ImageSets我们只需要用到Main文件夹,这里面存放的是一些文本文件,通常为train.txt、test.txt等,该文本文件里面的内容是需要用来训练或测试的图像的名字;JPEGImages文件夹中放我们已按统一规则命名好的原始图像。
    keras-yolo3-master使用记录_第1张图片

将自己数据转移到对应目录

// 将自己原始图片,标注过的图片放到VOC数据集相应位置,并生成训练集测试集验证集
//生成训练集测试集验证集对应txt文件,放入相应位置
#%%

import os
import random
import shutil    #拷贝文件并移动的库

path = '/code/kaggle/wechat/' #自己的数据路径

img = os.listdir(path + 'pyq')  #所有原始图像

img_xml = os.listdir(path + 'labeled')  #所有xml文件
print('img_num:  ',len(img))
print('img_xml_num:  ',len(img_xml))

#清空VOC数据集文件夹内容
path_img_ori = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/JPEGImages'
path_xml = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/Annotations'
img_ = os.listdir(path_img_ori)
xml_ = os.listdir(path_xml)
for img__ in img_:
    os.remove(os.path.join(path_img_ori,img__))
for xml__ in xml_:
    os.remove(os.path.join(path_xml,xml__))
    
#生成VOC数据集文件夹内容
k = 0
for i in range(len(img)):
    path_img_ori = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/JPEGImages/'
    path_xml = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/Annotations/'
    #拷贝转移文件,并按012命名新文件
    #shutil.copyfile(old——path, new-path)
    
    shutil.copyfile(path + 'pyq/' + img[i] , path_img_ori + str(k) + '.' + 'jpg')
    shutil.copyfile(path + 'labeled/' + img_xml[i] , path_xml + str(k) + '.' + img_xml[i].split('.')[-1])    
    
    context.append(str(k))
    
    k = k+1

trainval_percent = 0.2
train_percent = 0.8           #自己定比例
xmlfilepath = path_xml
txtsavepath =  '/code/kaggle/keras-yolo3-master/VOCdevkit/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)


#到达的文件路径~/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt'

ftrainval = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt', 'w')
ftest = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/test.txt', 'w')
ftrain = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/train.txt', 'w')
fval = open('/code/kaggle/keras-yolo3-master/VOCdevkit/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:
            ftest.write(name)
        else:
            fval.write(name)
    else:
        ftrain.write(name)

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


#%%



生成yolo3所需的train.txt,val.txt,test.txt

打开keras-yolo3-master文件夹下voc_annatation.py文件进行修改

import xml.etree.ElementTree as ET
from os import getcwd

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

classes = ["dz_tx"]   #这里改为自己标注数据集中的标签名


def convert_annotation(year, image_id, list_file):
    in_file = open('/code/keras-yolo3-master/VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id),'rb')
    tree=ET.parse(in_file)
    root = tree.getroot()

    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 = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
        list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))

wd = getcwd()

for year, image_set in sets:
    image_ids = open('/code/keras-yolo3-master/VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
    list_file = open('%s.txt'%( image_set), 'w')
    for image_id in image_ids:
        list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg'%(wd, year, image_id))
        convert_annotation(year, image_id, list_file)
        list_file.write('\n')
    list_file.close()

修改model_data下的文件,放入你的类别,coco,voc这两个文件都需要修改。

一个标签占一行
keras-yolo3-master使用记录_第2张图片

训练自己的网络

直接复制替换原来train.py即可

此时自己在keras-yolo3-master下新建文件夹logs logs下再建文件夹000

  1. run时可能会报错
    AttributeError: module ‘keras.backend’ has no attribute ‘control_flow_ops’

    解决办法:https://blog.csdn.net/CAU_Ayao/article/details/89312354

  2. 可能Tensorboard报错
    我发现Tensorboard这行代码是灰色的,所以我把它作为释义不用了

  3. 建议先将epoch调小一些进行测试

"""
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 = '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()    

你可能感兴趣的:(CV,yolo,深度学习,keras)