加上今天总共搞了4天,终于成功了,网上也有很多利用yolov3训练自己数据集的教程,但是都存在这样那样的问题,经过大量搜索与试验,终于成功了。
先不说准确率有多高,跑通了就很开心,毕竟我只用了9张图片。
下面开始正文:
IDE:pycharm community,python3.8
下载地址:这里
下载地址:这里
1. 要注意文件的目录情况要和图中一致
2. 项目上层要有一个叫VOCdevkit的文件夹
3. 将下载的yolov3文件夹放到该项目下,并将其设置为引用源
右键选择该文件夹-->Make dictory as --> souces root
我是使用lableImage进行数据集的标注的,具体可参见这里。对了,我还发现lableImage竟然只能对jpg文件进行标注,操作不了bmp,不知道只是我碰到这个问题还是怎么样,我还没看到有人提到过。
Annotation中主要存放xml文件,JPEGImages文件夹中放我们已按统一规则命名好的原始图像。
在项目下新建test.py文件,复制下面的代码,会在ImageSets/Main下生成4个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()
运行voc_annotation.py ,但是要记得把里面的classes换成你自己的class,比如我这里只有一个类别:bad,所以改成这样:
还有文件路径也要记得改:
最后会在当前文件夹下生成带2007_的3个txt文件。手动把这3个文件的2007_删掉。
IDE里直接打开cfg文件,ctrl+f搜 yolo, 总共会搜出3个含有yolo的地方,3个!
每个地方都要改3处,filters:3*(5+len(classes));
classes: len(classes) = 1,这里以1个类别为例
random:原来是1,显存小改为0
复制,直接替换掉原来的代码
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras.models import Model
from tensorflow.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) 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()
1. 确保train.txt的路径正确,并有相关参数值,否则会报没有找到文件的错
我的做法是把voc_annotation.py这里的代码改掉了:
2. 在yolov3文件夹下新建log/000文件夹,用来保存训练后的权重文件,否则会报错
3. 运行之后会报错,需要修改model.py
在这之前需要修改yolo.py文件
1. 修改权重路径
2. 修改tensorflow的用法
因为tensorflow2下会报一个Tensor is unhashable ,Instead, use tensor.experimental_ref() as the key.的错,所以需要修改
还有在这里,修改:
然后就可以预测了。不过,网上很多教程都是说运行yolo.py,但是经过我的测试,并没有什么反应,查看代码发现预测图片的程序在yolo_video.py中。所以,预测图片是这么做的:
1. 在teminal下,进入到yolo_video.py的路径下
2. 使用 python yolo_video.py --image,回车运行
a/service/service.cc:176] StreamExecutor device (0): Host, Default Version
logs/000/trained_weights.h5 model, anchors, and classes loaded.
Input image filename:
然后就可以在冒号后面输入图片路径进行预测啦!
这是我随便选张图片预测的结果:
可以看到,它框出来认为bad的点,其实不够准确,下面那个点也应该框出来,但这是后面训练精度的问题了。跑通了这个就很开心。
这个程序是一直循环不会终止的,如果需要退出程序,右键选择上面的Terminal-->close tab-->terminate,就可以了。