操作系統(tǒng):Windows 10
IDE:Pycharm
Python: 3.6.2 且已安裝好?tensorflow?,?keras,pyqt5,lxml包
二锡溯、快速使用yolo3預(yù)測(cè)圖片
keras-yolo3源代碼, 下載到本地后用 Pycharm 打開。
初始權(quán)重文件,在QQ群文件中跑筝,下載好后放在 上述文件keras-yolo3 一級(jí)目錄下死讹。
命令行中執(zhí)行如下命令將 darknet 下的 yolov3 配置文件轉(zhuǎn)換成 keras 適用的 .h5 文件瞒滴。
命令:python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5
運(yùn)行預(yù)測(cè)圖像程序
命令:python yolo_video.py --image
一切正常的話,會(huì)讓你輸入待識(shí)別的圖片路徑,圖片目錄以keras-yolo3為一級(jí)目錄妓忍。若待測(cè)圖片放在該一級(jí)目錄下虏两,則直接輸入圖片名即可。
命令:Input image filename:test.jpg
三世剖、訓(xùn)練自己的數(shù)據(jù)集進(jìn)行目標(biāo)檢測(cè)
在該項(xiàng)目中新建文件夾如下所示:
安裝數(shù)據(jù)標(biāo)記工具 labelImg
用 powershell 進(jìn)入到該項(xiàng)目根目錄下定罢,執(zhí)行
命令:pyrcc5 -o resources.py resources.qrc
命令:python labelImg.py
彈出用戶界面,使用如下:
在 keras-yolo3 一級(jí)目錄下新建 test.py ,如上上圖旁瘫。復(fù)制如下代碼:
/**華麗的代碼分割線**/
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()
/**華麗的代碼分割線**/
運(yùn)行之后祖凫,在keras-yolo3-master\VOCdevkit\VOC2007\ImageSets\Main目錄下就是制作好的數(shù)據(jù)集。
修改voc_annotion.py中的classes變量為自己需要的各式標(biāo)簽
/**華麗的代碼分割線**/
classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] #這里是10個(gè)數(shù)字標(biāo)簽
# classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
/**華麗的代碼分割線**/
然后運(yùn)行該文件酬凳,會(huì)在keras-yolo3-master一級(jí)目錄下生成三個(gè)2007_***.txt的文件惠况。
修改參數(shù)文件yolo3.cfg
打開yolo3.cfg文件。搜索 yolo(共出現(xiàn)三次)宁仔,每次按下圖都要修改稠屠。
/**華麗的代碼分割線**/
[convolutional]
size=1
stride=1
pad=1
filters=45? ? # 3*(5+len(classes)).? original value = 255
activation=linear
[yolo]
mask = 6,7,8
anchors = 10,13,? 16,30,? 33,23,? 30,61,? 62,45,? 59,119,? 116,90,? 156,198,? 373,326
classes=10? ? ? #train labels.? original value = 80
num=9
jitter=.3
ignore_thresh = .5
truth_thresh = 1
random=0? ? ? ? #if you memory is small, choice 0. origninal value = 1
/**華麗的代碼分割線**/
修改model_data下的voc_classes.txt為自己訓(xùn)練的類別
/**華麗的代碼分割線**/
label0
label2
...
...
label9
/**華麗的代碼分割線**/
修改train.py代碼如下,做訓(xùn)練翎苫。
/**華麗的代碼分割線**/
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()
/**華麗的代碼分割線**/
記得在keras-yolo3-master中新建文件logs\000权埠,這個(gè)文件是用來存放自己的數(shù)據(jù)集訓(xùn)練得到的模型。
修改yolo.py文件
/**華麗的代碼分割線**/
? ? _defaults = {
? ? ? ? "model_path": 'logs/000/trained_weights.h5', #此處修改成自己的路徑
? ? ? ? "anchors_path": 'model_data/yolo_anchors.txt', #此處修改成自己的路徑
? ? ? ? "classes_path": 'model_data/voc_classes.txt', #此處修改成自己的路徑
? ? ? ? "score" : 0.3,
? ? ? ? "iou" : 0.45,
? ? ? ? "model_image_size" : (416, 416),
? ? ? ? "gpu_num" : 1,
? ? }
/**華麗的代碼分割線**/
運(yùn)行預(yù)測(cè)圖像程序
/**華麗的代碼分割線**/
python yolo_video.py --image
/**華麗的代碼分割線**/