文章写作初衷:

       由于本人用的电脑是win10操作系统,也带有gpu显卡。在研究车位识别过程中想使用yolov3作为训练模型。翻看安装yolo的过程中有看到 
https://pjreddie.com/darknet/yolo/ <https://pjreddie.com/darknet/yolo/> 
这是linux安装yolo最详细的文档(如果大家使用的是linux强烈推荐该文档)。本来想在自己的win10系统上安装一个虚拟机并安装linux操作系统,但是后来在论坛中有人说是双系统,虚拟机的显卡是虚拟出来的,没法用cuda加速,只能作罢。于是搜索win10下如何安装yolov3,搜到一篇文章 
https://zhuanlan.zhihu.com/p/35828626 <https://zhuanlan.zhihu.com/p/35828626>
 ,由于yolo是由c/c++编写,win10需要安装配置Visual Studio进行yolo的配置修改和运行。但是自己电脑并没有配置相应的Visual
Studio,也嫌麻烦不想安装。在迟疑之际忽然搜到有win10下keras版本的yolov3(由于之前电脑已经配置好了keras,再使用就显得方便很多。)。搜到很多的文章,但是有一篇无疑是最值得推荐的 
Patrick_Lxc <https://blog.csdn.net/Patrick_Lxc/article/details/80615433>大神写的博客: 
https://blog.csdn.net/Patrick_Lxc/article/details/80615433
<https://blog.csdn.net/Patrick_Lxc/article/details/80615433>
。虽然大神写的已经够详细,但是自己在实现过程中也发现有几个不太好注意的地方,因为本人复现代码用了大半天,还是希望别人用更快的速度去实现yolo的使用和训练自己的模型。这也是写作文章的初衷。

一、环境要求

      tensorflow-gpu

      keras

      pycharm

二、快速使用

      1、下载yolov3代码:https://github.com/qqwweee/keras-yolo3
<https://github.com/qqwweee/keras-yolo3> ,并解压缩之后用pycharm打开。

      2、下载权重:https://pjreddie.com/media/files/yolov3.weights
<https://pjreddie.com/media/files/yolov3.weights>并将权重放在keras-yolo3的文件夹下。如下图所示:

             

      3、执行如下命令将darknet下的yolov3配置文件转换成keras适用的h5文件。

             python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

      4、运行预测图像程序

             python yolo.py

             

            输入需要预测的图片路径即可,结果示例如下:

            

           这样就可以实现yolov3的快速使用了。

三、训练自己的数据集进行目标检测

          1、在工程下新建一个文件夹VOCdevkit,目录结构为VOCdevkit/VOC2007/,在下面就是新建几个默认名字的文件夹   
     
 Annotation,ImageSet(该目录还有三个文件需要建立),JPEGImages(把你所有的图片都复制到该目录里面,如下图),SegmentationClass,SegmentationObject。

           

           2、生成Annotation下的文件,安装工具labelImg。安装过程可参照:

                 https://blog.csdn.net/u012746060/article/details/81016993
<https://blog.csdn.net/u012746060/article/details/81016993>,结果如下图:

                 

            3、生成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()
                 运行代码之后,生成如下文件,VOC2007数据集制作完成。

                  

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

                  生成的数据集不能供yolov3直接使用。需要运行voc_annotation.py
,classes以检测两个类为例(车和人腿),在voc_annotation.py需改你的数据集为:

                  

                运行之后,生成如下三个文件:

                 

                5、修改参数文件yolo3.cfg

                 打开yolo3.cfg文件。搜索yolo(共出现三次),每次按下图都要修改

                 

                  filter:3*(5+len(classes))

                  classes:你要训练的类别数(我这里是训练两类) 

                  random:原来是1,显存小改为0

                 6、修改model_data下的voc_classes.txt为自己训练的类别

                  

                7、 修改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()
                   替换完成后,千万千万值得注意的是
,因为程序中有logs/000/目录,你需要创建这样一个目录,这个目录的作用就是存放自己的数据集训练得到的模型。不然程序运行到最后会因为找不到该路径而发生错误。生成的模型trained_weights.h5如下:

                    

               8、修改yolo.py文件,如下将self这三行修改为各自对应的路径。

                    

                   运行python yolo.py,输入自己要检测的类的图片即可查看训练效果了。

                   

             

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信