一、YOLO_tensorflow-master直接测试[转]
参考博文:https://blog.csdn.net/c20081052/article/details/80260726
0.运行环境:
Win7 + python3.5+ PyCharm 2018 x64+TensorFlow1.6.0+12G内存
1. 代码下载
链接是:https://github.com/hizhangp/yolo_tensorflow
下载代码YOLO_tensorflow-master.zip解压后,新建两级文件夹data/weight,用于存放YOLO模型。
2.YOLO权重文件下载,
链接: https://pan.baidu.com/s/1htt9YBE 密码: ehw2
下载后的weights文件YOLO_small.ckpt放在data/weight文件夹下
3.直接运行test.py
只用修改测试图片的名字
二、Keras/Tensorflow+python+yolo3训练自己的数据集
参考博文:https://blog.csdn.net/Patrick_Lxc/article/details/80615433
该程序环境搭建:https://blog.csdn.net/imwaters/article/details/84938839
代码下载:https://github.com/qqwweee/keras-yolo3
2.制作自己的VOC数据集
2.1首先新建一个名字为VOC2007的文件夹,在该文件夹下再分别创建Annotations、ImageSets、JPEGImages三个子文件夹
在ImageSets文件夹下创建名为Main的文件夹。【参考链接】
2.2 将训练用的图片重命名为VOC形式0000X-00XXX后保存到JPEGImage文件夹中。【使用代码重命名图片】
2.3 安装像标注工具LabelImage。
网盘下载:https://pan.baidu.com/s/1NEAyAZxP7mfEhDG5FXXuGQ
下载图像标注工具LabelImage【官方下载】,标记生成xml文件。
- 在“predefined_classes.txt”修改默认标签名称,重启LabelImage
- 点击Open Dir 选择 JPEGImage 文件夹
- 点击Change Save Dir 选择 保存在Annotations 文件夹
- 点击Create RectBox 进行标签工作。快捷键 “w” ,标注完点“Save”
- 点击Next Image 进行下一张标签,快捷键 “d”,上一张图 ,快捷键 “a”
3.生成训练数据集及标签
3.1 代码生成ImageSets/Main/4个文件,在VOC2007文件夹下,新建并运行下列代码
4个txt文件,其中test.txt是测试集,train.txt是训练集,val.txt是验证集,trainval.txt是训练和验证集。【原文链接】
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()
3.2 生成yolo3所需的train.txt,val.txt,test.txt
VOC2007数据格式数据集制作完成,需要转换成keras-tensorflow使用的格式。
修改并运行voc_annotation.py
运行之后,会在主目录下多生成三个txt文件,
重命名,手动删除2007_,
3.3 修改model_data下的文件,放入你的类别,coco_classes,voc_classes这两个文件都需要修改。
4.修改yolo3.cfg配置
作者:Patrick_Lxc
原文:https://blog.csdn.net/Patrick_Lxc/article/details/80615433
IDE里直接打开cfg文件,ctrl+f搜 yolo, 总共会搜出3个含有yolo的地方!!
每个地方都要改3处,filters:3*(5+len(classes));
classes: len(classes) = 5,这里本人有三个
random:原来是1,显存小改为0
5.修改train.py(可直接复制下列代码) ,训练自己的数据集
其中,文件目录,批次大小,train与val级大小,迭代次数有很大区别(epochs)
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
import os
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
import os
os.environ['TF_MIN_GPU_MULTIPROCESSOR_COUNT'] = '1'
def _main():
annotation_path = 'train.txt'
log_dir = './logs/'
classes_path = 'model_data/voc_classes_181220.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,
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/',exist_h5='logs/guilin_181220.h5'):
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, verbose = 1, save_best_only=True, period=1)
monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)
#批次大小是重要数据
batch_size =5
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))
if os.path.exists(exist_h5):
model.load_weights(exist_h5)
# 若成功加载前面保存的参数,输出下列信息
print("------------checkpoint_loaded--------")
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,
#epochs=500,
initial_epoch=0,
#保存训练过程
callbacks=[checkpoint, TensorBoard(log_dir=log_dir)])
#训练好后的名字
model.save_weights(log_dir + 'guilin_181220.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()
图像标注工具labelImg安装方法
1.参考百度链接。【失败】
2.官方github安装 https://github.com/tzutalin/labelImg [成功]
直接下载windows安装包,
windows下 labelImgexe闪退解决方案【转】
https://blog.csdn.net/csdn_zhishui/article/details/84583888
删除 C:\Users\YourAccount\..labelImgSettings.pkl
,重新打开labelImg,问题解决。