windown+cpu+Keras/Tensorflow+python+yolo3訓練自己的數據集

轉自:https://blog.csdn.net/Patrick_Lxc/article/details/80615433 感謝博主

第一步:下載VOC2007數據集,把所有文件夾裏面的東西刪除,保留所有文件夾的名字。

    像這樣

    第二步:把你所有的圖片都複製到JPEGImages裏面

    像這樣:

    第三步:生成Annotations下的文件

    工具:LabelImg ,鏈接:https://pan.baidu.com/s/1GJFYcFm5Zlb-c6tIJ2N4hw 密碼:h0i5

    像這樣:

    第四步:生成ImageSets/Main/4個文件。在VOC2007下建個文件test.py,然後運行

    像這樣:

    test.py代碼:

import os
import random

trainval_percent = 0.1
train_percent = 0.9
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()

    第五步:生成yolo3所需的train.txt,val.txt,test.txt

    VOC2007數據集製作完成,但是,yolo3並不直接用這個數據集,開心麼?

    需要的運行voc_annotation.py ,classes以三個顏色爲例,你的數據集記得改

   

    運行之後,會在主目錄下多生成三個txt文件,

    像這樣:

手動刪除2007_,

    第六步:修改參數文件yolo3.cfg

    註明一下,這個文件是用於轉換官網下載的.weights文件用的。訓練自己的網絡並不需要去管他。詳見readme

    IDE裏直接打開cfg文件,ctrl+f搜 yolo, 總共會搜出3個含有yolo的地方,睜開你的卡姿蘭大眼睛,3個yolo!!

    每個地方都要改3處,filters:3*(5+len(classes));

                                    classes: len(classes) = 3,這裏以紅、黃、藍三個顏色爲例

                                    random:原來是1,顯存小改爲0

   

    第七步:修改model_data下的文件,放入你的類別,coco,voc這兩個文件都需要修改。

    像這樣:

  

    第八步:修改代碼,準備訓練。代碼以yolo3模型爲目標,tiny_yolo不考慮。

    爲什麼說這篇文章是從頭開始訓練?代碼原作者在train.py做了兩件事情:

    1、會加載預先對coco數據集已經訓練完成的yolo3權重文件,

    像這樣:

    2、凍結了開始到最後倒數第N層(源代碼爲N=-2),

   像這樣:

   但是,你和我想訓練的東西,coco裏沒有啊,所以,就乾脆從頭開始訓練吧

    對train.py做了一下修改,直接複製替換原文件就可以了,細節大家自己看吧,直接運行,loss達到10幾的時候效果就可以了

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

第九步:預測圖片。修改了yolo.py下的預測圖片的函數,將檢測的圖片都儲存在了outdir裏

'''
def detect_img(yolo):
    while True:
        img = input('Input image filename:')
        try:
            image = Image.open(img)
        except:
            print('Open Error! Try again!')
            continue
        else:
            r_image = yolo.detect_image(image)
            r_image.show()
    yolo.close_session()
'''
import glob
def detect_img(yolo):
    path = "D:\VOCdevkit\VOC2007\JPEGImages\*.jpg"
    outdir = "D:\\VOCdevkit\VOC2007\SegmentationClass"
    for jpgfile in glob.glob(path):
        img = Image.open(jpgfile)
        img = yolo.detect_image(img)
        img.save(os.path.join(outdir, os.path.basename(jpgfile)))
    yolo.close_session()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章