YOLO,是You Only Look Once的缩写,一种基于深度卷积神经网络的物体检测算法,YOLO v3是YOLO的第3个版本,检测算法更快更准。
本文源码:https://github.com/SpikeKing/keras-yolo3-detection

YOLO
YOLO v3已经提供 COCO(Common Objects in Context)数据集的模型参数。我们可以把COCO的模型参数作为预训练参数,再结合已有的数据集,创建自己的检测算法。
本例使用WIDER FACE人脸数据,训练一个高精度的人脸检测模型。
WIDER
数据集:WIDER Face

WIDER
建立时间:2015-11-19
WIDER FACE 数据集是一个人脸检测基准(benchmark)数据集,图片选取自 WIDER(Web Image Dataset for Event Recognition) 数据集。图片数 32,203 张,人脸数 393,703 个,在大小(scale)、位置(pose)、遮挡(occlusion)等不同形式中,人脸是高度变换的。WIDER FACE 数据集是基于61个事件类别,每个事件类别,随机选取训练40%、验证10%、测试50%。训练和测试含有边框(bounding box)真值(ground truth),而验证不含。
数据集在官网可以公开下载,其中在Face annotations 中,wider_face_train_bbx_gt.txt是边框真值,数据格式如下:
0--Parade/0_Parade_marchingband_1_849.jpg 1 449 330 122 149 0 0 0 0 0 0
数据说明:
第1行:图片的位置和名称;
第2行:边框的数量;
第3~n行:每个人脸的边框和属性:
其中1~4位是
x1, y1, w, hblur:模糊,0清晰、1一般、2严重;
expression:表情,0正常、1夸张;
illumination:曝光,0正常、1极度;
occlusion:遮挡,0无、1部分、2大量;
pose:姿势,0正常,1非典型;
wider_face_val_bbx_gt.txt与此类似。
图片数据的清晰度一般,大小不一,尺寸为1024x,宽度相同。
数据转换
为了符合训练要求,需要转换wider数据集中的边框格式,为训练要求的边框格式。
即文件路径,边框xmin,ymin,xmax,ymax,label:
data/WIDER_val/images/10--People_Marching/10_People_Marching_People_Marching_2_433.jpg 614,346,771,568,0 245,382,392,570,0 353,222,461,390,0 498,237,630,399,0
转换源码。遍历数据文件夹,逐行解析不同格式的数据,写入文件。注意:
物体框,Wider的数据格式是x,y,w,h,而训练的数据格式是xmin,ymin,xmax,ymax;
只检测人脸一个类别,则类别索引均为0;
具体参考工程的wider_annotation.py脚本。
def generate_train_file(bbx_file, data_folder, out_file):
paths_list, names_list = traverse_dir_files(data_folder)
name_dict = dict() for path, name in zip(paths_list, names_list):
name_dict[name] = path
data_lines = read_file(bbx_file)
sub_count = 0
item_count = 0
out_list = [] for data_line in data_lines:
item_count += 1
if item_count % 1000 == 0:
print('item_count: ' + str(item_count))
data_line = data_line.strip()
l_names = data_line.split('/') if len(l_names) == 2: if out_list:
out_line = ' '.join(out_list)
write_line(out_file, out_line)
out_list = []
name = l_names[-1]
img_path = name_dict[name]
sub_count = 1
out_list.append(img_path) continue
if sub_count == 1:
sub_count += 1
continue
if sub_count >= 2:
n_list = data_line.split(' ')
x_min = n_list[0]
y_min = n_list[1]
x_max = str(int(n_list[0]) + int(n_list[2]))
y_max = str(int(n_list[1]) + int(n_list[3]))
p_list = ','.join([x_min, y_min, x_max, y_max, '0']) # 标签全部是0,人脸
out_list.append(p_list) continue类别文件wider_classes.txt仅有一行,就是face。
训练
YOLO v3的训练过程,参数:标注数据、类别、存储路径、预训练模型、anchors、输入尺寸。
annotation_path = 'dataset/WIDER_train.txt' # 数据classes_path = 'configs/wider_classes.txt' # 类别log_dir = 'logs/002/' # 日志文件夹pretrained_path = 'model_data/yolo_weights.h5' # 预训练模型anchors_path = 'configs/yolo_anchors.txt' # anchorsclass_names = get_classes(classes_path) # 类别列表num_classes = len(class_names) # 类别数anchors = get_anchors(anchors_path) # anchors列表input_shape = (416, 416) # 32的倍数,输入图像
创建模型:
input_shape是输入图像的尺寸;anchors是检测框的尺寸;
num_classes是类别数;freeze_body,模式1是全部冻结,模式2是训练最后三层;weights_path,预训练权重的路径;logging是TensorBoard的回调,checkpoint是存储权重的回调;
model = create_model(input_shape, anchors, num_classes,
freeze_body=2,
weights_path=pretrained_path) # make sure you know what you freezelogging = 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=3) # 只存储weights,训练数据与验证数据:
val_split = 0.1 # 训练和验证的比例with open(annotation_path) as f: lines = f.readlines() np.random.seed(10101) np.random.shuffle(lines) np.random.seed(None) num_val = int(len(lines) * val_split) # 验证集数量num_train = len(lines) - num_val # 训练集数量
模型编译与fit数据:
损失函数只使用
y_pred预测结果;批次数是32个;
训练数据与验证数据都来源于
data_generator_wrapper;训练过程中,通过checkpoint存储权重,最终再存储最终的权重;
model.compile(optimizer=Adam(lr=1e-3), loss={ # use custom yolo_loss Lambda layer.
'yolo_loss': lambda y_true, y_pred: y_pred}) # 损失函数batch_size = 32 # batch尺寸print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train // batch_size),
validation_data=data_generator_wrapper(
lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val // batch_size),
epochs=200,
initial_epoch=0,
callbacks=[logging, checkpoint])
model.save_weights(log_dir + 'trained_weights_stage_1.h5') # 存储最终的参数,再训练过程中,通过回调存储模型创建:
创建YOLO v3的模型,
yolo_body,参数图像输入、每个尺度的anchor数、类别数;加载预训练权重,冻结参数,保留最后三层;
自定义Lambda,模型的损失函数层;
输入是YOLO模型输入和真值,输出是损失函数;
def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/yolo_weights.h5'):
K.clear_session() # 清除session
image_input = Input(shape=(None, None, 3)) # 图片输入格式
h, w = input_shape # 尺寸
num_anchors = len(anchors) # anchor数量
# YOLO的三种尺度,每个尺度的anchor数,类别数+边框4个+置信度1
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) # model
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 in [1, 2]: # Freeze darknet53 body or freeze all but 3 output layers.
num = (185, len(model_body.layers) - 3)[freeze_body - 1] 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) # 模型,inputs和outputs
return model数据生成器:
data_generator_wrapper用于条件检查;将输入的标注行随机;
根据批次数,将图像放入
image_data中,将边框和参数放入真值y_true中;输出图像和边框,还有批次数的填充,用于存储置信度。
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): '''data generator for fit_generator''' n = len(annotation_lines) i = 0 while True: image_data = [] box_data = [] for b in range(batch_size): if i == 0: np.random.shuffle(annotation_lines) image, box = get_random_data(annotation_lines[i], input_shape, random=True) # 获取图片和盒子 image_data.append(image) # 添加图片 box_data.append(box) # 添加盒子 i = (i + 1) % n 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_wrapper(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)
具体源码参考yolo3_train.py,即可生成人脸检测模型。
验证
在yolo3_predict.py中,替换已训练好的模型参数:
模型:ep108-loss44.018-val_loss43.270.h5
检测图片:

output
其他:增加更多的数据集,与具体的需求图片结合,都可以提升检测效果。
OK, that's all! Enjoy it!
作者:SpikeKing
链接:https://www.jianshu.com/p/8214d947e031

随时随地看视频