keras-tensorflow-yolo-v3 win10目标检测训练自己的数据集(一)
文章目录
Chapter 0:准备工作
配置:
- Windows 10
- Pycharm
- tensorflow-gpu 1.9.0
- keras 2.2.4
- cudnn 7.6.0
- cudatoolkit 9.0
文件下载地址:
keras-yolo3-master
VOC2007
yolov3.weights
labelImg
Chapter 1:数据集制作
下载VOC2007数据集将VOCdevkit文件夹放至keras-yolo-master文件夹下,并将里面的图片、文件全部删掉,只保留文件夹,如下:
——VOCdevkit
————VOC2007
——————Annotations
——————ImageSets
————————Layout
————————Main
————————Segmentation
——————JPEGImages
——————SegmentationsClass
——————SegmentationObject
1.1:导入自己的数据集
把自己的数据集,放至JPEGImage文件夹下
1.2:图像标注
用labelImg对数据集进行标注(关于labelImg的安装使用详见:图像标注软件——labelImg使用教程)
标注完成的.xml文件保存至Annotations文件夹
1.3:生成训练-验证-测试文件
在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()
运行test.py文件,ImageSets/Main目录下生成如下四个文件
Chapter 2:修改类别
1.打开keras-yolo3-master目录下voc_annotation.py文件
2.修改你数据集的类别名称
3.运行该文件之后会在主目录keras-yolo3-master下生成3个.txt文件,手动将文件名修改为train.txt \ val.txt \ test.txt
Chapter 3:参数设定
3.1 修改yolo3.cfg
修改yolo3.cfg文件参数
1.Pycharm打开yolo3.cfg
2.快捷键Ctrl + F 查找yolo(一共3个yolo),每一处的filter 、classes、random都需做相应更改
filter = 3*(len(classes)+5) #我这里只有一类,所以是18
classes = 1 #有几类写几类
random = 0 #显存小设为0,否则为1
3.2:修改classes.txt
打开model_data/coco_classes.txt 和 voc_classes.txt 文件,修改classes
Chapter 4:训练
在主目录下新建文件夹 logs/000
修改 train.py
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) a 1b5d8 s 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()
运行train.py 观察loss损失值,降到十几左右就可以停止训练了,logs/000目录下生成trained-weights.h5
问题
- ResourcesExhaustion报错:减小Batch (我是4GB运存,Batch=4,仅供参考)
- tensorflow版本与cudnn版本不兼容报错,建议使用我前面给出的相关版本
Chapter 5:重新设置参数文件路径
打开 yolo.py 文件夹,修改
1.权重文件路径
2.分类路径
Chapter 6:测试
6.1 检测图片
法一:在Pycharm的Terminal里输入:python yolo_video.py --image
法二:cmd->cd 至文件夹keras-yolo3-master所在路径 输入:python yolo_video.py --image
6.2 视频检测
法一:在Pycharm的Terminal里输入:python yolo_video.py --input=run.mp4
法二:cmd->cd 至文件夹keras-yolo3-master所在路径 输入:python yolo_video.py --input=run.mp4
- Win10下用TensorFlow训练自己的数据集来做目标检测
- TX2实现yolov2(目标检测,计数,训练自己的数据集)
- 《Keras/Tensorflow+python+yolo3训练自己的数据集》实践踩坑心得
- 目标检测(Google object_detection) API 上训练自己的数据集
- YOLO基础教程(四):yolo v3 训练自己的数据集
- tensorflow学习(1)——训练自己的数据集并进行物体检测(object detection)
- 目标检测SSD:训练自己的数据集
- 目标检测2-训练自己数据集(完整版)
- yolov1_tensorflow 训练自己的数据集
- Tensorflow训练自己的Object Detection模型并进行目标检测
- 目标检测算法SSD在window环境下GPU配置训练自己的数据集
- YOLOv3 ubuntu 配置及训练自己的VOC格式数据集
- TensorFlow下使用YOLOv1训练+测试自己的数据集
- tensorflow训练自己的数据集实现CNN图像分类1
- 用YOLOv2训练自己的数据集
- Tensorflow-SSD测试及训练自己的数据集
- win10 Faster-RCNN训练自己数据集遇到的问题集锦 (转)
- 修改caffe输出multilabel,并自己训练完成了一个神经网络,初步达到目标检测的效果
- mxnet 之 目标检测数据集制作+SSD 模型训练
- Tensorflow 训练自己的数据集(二)(TFRecord)