原教程地址:https://blog.csdn.net/dy_guox/article/details/79081499
本文是在原教程的基础上加以修改的,也是记录自己在搭建学习时遇到的问题。
记录时间是:2019年3月
电脑配置信息
电脑是笔记本电脑
CPU:i7 8核
GPU:GTX940 2G
内存:16G
操作系统:win10 64位
开始搭建环境
-
本教程在Anaconda3.0的环境下完成,所以先下载 Anaconda 并安装。(使用Anaconda的好处是 你可以创建多个 虚拟环境进行试验)
-
在Anaconda中创建一个虚拟环境 TF-Object 。
-
进入 TF-Object 下的控制台,安装必要的模块:
安装TensorFlow
# 等号后面可以输入指定的版本号进行安装
pip install --upgrade tensorflow==1.9.0
# GPU版本的安装,但是这个需要系统配置 CUDA 和 cuDNN ,比较复杂。
pip install --upgrade tensorflow-gpu==1.9.0
安装其他模块:
pip install matplotlib
pip install pandas
pip install Pillow
- 验证TensorFlow是否安装成功。在当前控制台下输入 python 进入python的运行环境,然后再输入下面代码验证。
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
# 执行结果为 Hello,TensorFlow! 则安装成功
-
下载Tensorflow object detection API
https://github.com/tensorflow/models
从github上下载项目(右上角“Clone or download”-“DownloadZIP”),下载到本地目录(避免中文),解压。我是解压到我的 F:\TensorFlow 文件夹下,解压以后会在该文件夹下出现一个 models-master 文件夹。 -
Protobuf 安装与配置
在 https://github.com/google/protobuf/releases 网站中选择windows 版本(最下面),解压后将bin文件夹中的【protoc.exe】放到C:\Windows。然后进入让一步解压的文件夹下 "research\ " 的。 如我的 “F:\TensorFlow\models-master\research”。
在此目录下打开命令行窗口,输入:
# From tensorflow/models/
protoc object_detection/protos/*.proto --python_out=.
在这一步有时候会出错,可以尝试把/*.proto 这部分改成文件夹下具体的文件名,一个一个试,每运行一个,文件夹下应该
出现对应的.py结尾的文件。不报错即可。
下面这段代码是我在按一个一个文件去执行的命令,可以直接复制使用:
protoc object_detection/protos/anchor_generator.proto --python_out=.
protoc object_detection/protos/argmax_matcher.proto --python_out=.
protoc object_detection/protos/bipartite_matcher.proto --python_out=.
protoc object_detection/protos/box_coder.proto --python_out=.
protoc object_detection/protos/box_predictor.proto --python_out=.
protoc object_detection/protos/eval.proto --python_out=.
protoc object_detection/protos/faster_rcnn.proto --python_out=.
protoc object_detection/protos/faster_rcnn_box_coder.proto --python_out=.
protoc object_detection/protos/graph_rewriter.proto --python_out=.
protoc object_detection/protos/grid_anchor_generator.proto --python_out=.
protoc object_detection/protos/hyperparams.proto --python_out=.
protoc object_detection/protos/image_resizer.proto --python_out=.
protoc object_detection/protos/input_reader.proto --python_out=.
protoc object_detection/protos/keypoint_box_coder.proto --python_out=.
protoc object_detection/protos/losses.proto --python_out=.
protoc object_detection/protos/matcher.proto --python_out=.
protoc object_detection/protos/mean_stddev_box_coder.proto --python_out=.
protoc object_detection/protos/model.proto --python_out=.
protoc object_detection/protos/multiscale_anchor_generator.proto --python_out=.
protoc object_detection/protos/optimizer.proto --python_out=.
protoc object_detection/protos/pipeline.proto --python_out=.
protoc object_detection/protos/post_processing.proto --python_out=.
protoc object_detection/protos/preprocessor.proto --python_out=.
protoc object_detection/protos/region_similarity_calculator.proto --python_out=.
protoc object_detection/protos/square_box_coder.proto --python_out=.
protoc object_detection/protos/ssd.proto --python_out=.
protoc object_detection/protos/ssd_anchor_generator.proto --python_out=.
protoc object_detection/protos/string_int_label_map.proto --python_out=.
protoc object_detection/protos/train.proto --python_out=.
protoc object_detection/protos/calibration.proto --python_out=.
protoc object_detection/protos/flexible_grid_anchor_generator.proto --python_out=.
- PYTHONPATH 环境变量设置
在 ‘此电脑’-‘属性’- ‘高级系统设置’ -‘环境变量’-‘系统变量’ 中新建名为‘PYTHONPATH’的变量,将
models-master/research/ 及 models-master/research/slim 两个文件夹的完整目录添加,分号隔开,效果如下图:
接下来可以测试API,在 models-master/research/ 文件夹下运行命令行:
python object_detection/builders/model_builder_test.py
不报错说明运行成功。
注意:如果报错“ModuleNotFoundError: No module named ‘object_detection’”,说明刚刚配置的环境变量没有生效,此时重启电脑,再试试。
D:\APPData\pycharm\TensorFlow-object-test\models-master\research;D:\APPData\pycharm\TensorFlow-object-test\models-master\research\slim;
测试自带案例
在TF-Object的控制台中,CD 至 F:\TensorFlow\models-master\research\object_detection 文件夹下
然后输入jupyter notebook,就会调用浏览器(Chrome)打开当前文件夹,点开 object_detection_tutorial.ipynb,
(如果未安装 jupyter notebook 请 执行 “pip install jupyter” 命令安装 该软件。 )
在新标签页中打开 Object Detection Demo,点击上方的 “Cell”-“Run All”,
就可以直接看到结果,最后输出的是两张图片的识别结果,分别是狗,以及沙滩。第一次运行由于需要下载训练好的模型,耗时较长。第二次之后可以将 .ipynb文件中 Download Model 即 in[5]部分的代码注释掉,以加快运行速度。
如果在notebook中运行有问题,可以将.ipynb中in[]的代码复制到.py中,然后在 开始-Anaconda3-spyder 中运行。
至此Tensorflow object detection API 的环境搭建与测试工作完成。
准备训练图片
- 网上下载图片,我下载的是熊猫的图片 一共下载了 85张。在research\object_detection(我的路径“F:\TensorFlow\models-master\research\object_detection”)文件夹下创建一个images文件夹,再在images文件夹下分别创建train和test文件夹,将刚才下载的图片分成两份,一份作为训练,一份作为测试,分别放入train(训练)、test(测试)文件夹。(我是讲85张图片分成75张训练,10张测试)。
- 下载 LabelImg,该软件在Windows下有打包好的exe文件连接是LabelImg的exe可执行文件。LabelImg软件是专门用来给图片做标注的,标注后,每张图片会产生对应的xml文件。(需要注意的是 这个软件避免在中文路径下运行)
- 执行exe文件进入如下界面,
Open Dir 是打开图片所在路径,例如打开我的训练图片路径 “F:\TensorFlow\models-master\research\object_detection\images\train”;
Change Save Dir 是将标注后产生的xml 文件保存到哪里。
Next Image 是下一张图片;
Prev Image 是上一张图片;
Save 是保存标注操作,快捷键 Ctrl + S;
Create\nRectBox 是画框标注,快捷键W;
Delete\nRectBox 是删除画框标注;
- 开始标准。打开图片所在文件夹(训练和测试图片都需要标注),然后文件夹中的图片会自动加载出来,按 Create\nRectBox 按钮开始手动画框,将制定的对象框出以后,会自动弹出对象名称输入框,在框中输入 “panda”,然后点击“OK”完成标准(一张图片中可以标准多个对象的),标准完成后保存标准结果。所有图片都标准完成以后,每一张图片都会生成对应的 XML 文件。
- 标注完成以后需要将所有标注产生的XML综合一下生成 CSV 文件。此时需要在 research\object_detection 文件夹下创建一个xml_to_csv.py脚本,将如下代码复制进去。
1)设置xml文件所在的路径。
2)设置生成的csv文件的名称。
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 00:52:02 2018
@author: Xiang Guo
将文件夹内所有XML文件的信息记录到CSV文件中
"""
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
# 1)此处是设置文件所在的路径。
os.chdir('F:\\TensorFlow\\models-master\\research\\object_detection\\images\\test')
path = 'F:\\TensorFlow\\models-master\\research\\object_detection\\images\\test'
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (root.find('filename').text,
int(root.find('size')[0].text),
int(root.find('size')[1].text),
member[0].text,
int(member[4][0].text),
int(member[4][1].text),
int(member[4][2].text),
int(member[4][3].text)
)
xml_list.append(value)
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
def main():
image_path = path
xml_df = xml_to_csv(image_path)
# 2)此处需要设置 生成的csv文件的名称,'panda_test.csv' 是设置的文件名
xml_df.to_csv('panda_test.csv', index=None)
print('Successfully converted xml to csv.')
main()
-
将csv文件转换成对应的 TFRecords Format 文件。在此之前需要将两个csv文件复制到research\object_detection\data文件夹下,然后在 research\object_detection 文件夹下创建generate_tfrecord.py文件,将如下代码复制进去。
1)设置 object_detection 文件夹路径。
2)设置 csv文件路径。
3)设置生成的文件文件名称。
4)注意将对应的label改成自己的类别!!!!!!!!!!
5)设置图片路径。
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 01:04:55 2018
@author: Xiang Guo
由CSV文件生成TFRecord文件
"""
"""
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --csv_input=data/tv_vehicle_labels.csv --output_path=train.record
# Create test data:
python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record
"""
import os
import io
import pandas as pd
import tensorflow as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict
# 1)设置 object_detection 文件夹路径。
os.chdir('F:\\TensorFlow\\models-master\\research\\object_detection\\')
flags = tf.app.flags
# 2)设置 csv文件路径。
flags.DEFINE_string('csv_input', 'data/panda_test.csv', 'Path to the CSV input')
# 3)设置生成的文件文件名称。
flags.DEFINE_string('output_path', 'data/panda_test.record', 'Path to output TFRecord')
FLAGS = flags.FLAGS
# TO-DO replace this with label map
# 4)注意将对应的label改成自己的类别!!!!!!!!!!
def class_text_to_int(row_label):
if row_label == 'panda':
return 1
else:
None
# 如果是多个类别的话,写成如下方式:
# def class_text_to_int(row_label):
# if row_label == 'tv':
# return 1
# elif row_label == 'vehicle':
# return 2
# else:
# None
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
def create_tf_example(group, path):
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = group.filename.encode('utf8')
image_format = b'jpg'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for index, row in group.object.iterrows():
xmins.append(row['xmin'] / width)
xmaxs.append(row['xmax'] / width)
ymins.append(row['ymin'] / height)
ymaxs.append(row['ymax'] / height)
classes_text.append(row['class'].encode('utf8'))
classes.append(class_text_to_int(row['class']))
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),
'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
}))
return tf_example
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
# 5)设置图片路径
path = os.path.join(os.getcwd(), 'images/test')
examples = pd.read_csv(FLAGS.csv_input)
grouped = split(examples, 'filename')
for group in grouped:
tf_example = create_tf_example(group, path)
writer.write(tf_example.SerializeToString())
writer.close()
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))
if __name__ == '__main__':
tf.app.run()
运行完成后将会分别得到 panda_train.record 和 panda_test.record。
配置文件与模型
1.创建 ssd_mobilenet_v1_coco.config 文件,将如下代码复制进去。(或者从GitHub上下载对应的文件 ssd_mobilenet_v1_coco.config)
1)按实际情况修改 num_classes 的值,因为我只有一个对象,所以此处设置为1.
2)设置batch_size的值,此处我设置的值为1,你们可以根据自身的电脑的情况设置更大的值,该值会加快训练速度。
3)删除或者注释掉下面两行代码
# fine_tune_checkpoint: “PATH_TO_BE_CONFIGURED/model.ckpt”
# from_detection_checkpoint: true
4)设置 train_input_reader 对象下的 input_path 的值。
5)这里需要注意一点的就是 num_examples 这个值,如果从官网复制的默认值是 8000 ,如果你的训练样本比较少的话,比如 就 几百个 样本量的话,建议你修改一下,如果不修改的话,可能会造成训练几万、十几万步 都没有检测效果。我目前训练200个样本 设置的值是 10,该值仅供参考,如感兴趣可以去详细的了解一下 。
# SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.
model {
ssd {
num_classes: 1
box_coder {
faster_rcnn_box_coder {
y_scale: 10.0
x_scale: 10.0
height_scale: 5.0
width_scale: 5.0
}
}
matcher {
argmax_matcher {
matched_threshold: 0.5
unmatched_threshold: 0.5
ignore_thresholds: false
negatives_lower_than_unmatched: true
force_match_for_each_row: true
}
}
similarity_calculator {
iou_similarity {
}
}
anchor_generator {
ssd_anchor_generator {
num_layers: 6
min_scale: 0.2
max_scale: 0.95
aspect_ratios: 1.0
aspect_ratios: 2.0
aspect_ratios: 0.5
aspect_ratios: 3.0
aspect_ratios: 0.3333
}
}
image_resizer {
fixed_shape_resizer {
height: 300
width: 300
}
}
box_predictor {
convolutional_box_predictor {
min_depth: 0
max_depth: 0
num_layers_before_predictor: 0
use_dropout: false
dropout_keep_probability: 0.8
kernel_size: 1
box_code_size: 4
apply_sigmoid_to_scores: false
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
}
feature_extractor {
type: 'ssd_mobilenet_v1'
min_depth: 16
depth_multiplier: 1.0
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
loss {
classification_loss {
weighted_sigmoid {
}
}
localization_loss {
weighted_smooth_l1 {
}
}
hard_example_miner {
num_hard_examples: 3000
iou_threshold: 0.99
loss_type: CLASSIFICATION
max_negatives_per_positive: 3
min_negatives_per_image: 0
}
classification_weight: 1.0
localization_weight: 1.0
}
normalize_loss_by_num_matches: true
post_processing {
batch_non_max_suppression {
score_threshold: 1e-8
iou_threshold: 0.6
max_detections_per_class: 100
max_total_detections: 100
}
score_converter: SIGMOID
}
}
}
train_config: {
batch_size: 1
optimizer {
rms_prop_optimizer: {
learning_rate: {
exponential_decay_learning_rate {
initial_learning_rate: 0.004
decay_steps: 800720
decay_factor: 0.95
}
}
momentum_optimizer_value: 0.9
decay: 0.9
epsilon: 1.0
}
}
# Note: The below line limits the training process to 200K steps, which we
# empirically found to be sufficient enough to train the pets dataset. This
# effectively bypasses the learning rate schedule (the learning rate will
# never decay). Remove the below line to train indefinitely.
num_steps: 200000
data_augmentation_options {
random_horizontal_flip {
}
}
data_augmentation_options {
ssd_random_crop {
}
}
}
train_input_reader: {
tf_record_input_reader {
input_path: "data/panda_train.record"
}
label_map_path: "data/panda.pbtxt"
}
eval_config: {
num_examples: 10
# Note: The below line limits the evaluation process to 10 evaluations.
# Remove the below line to evaluate indefinitely.
max_evals: 10
}
eval_input_reader: {
tf_record_input_reader {
input_path: "data/panda_test.record"
}
label_map_path: "data/panda.pbtxt"
shuffle: false
num_readers: 1
}
开始训练模型
前期配置文件都准备好以后,接下来就要开始训练啦。
在TF-Object的虚拟控制台下 CD 到 research\object_detection目录下,然后执行如下代码即可开始训练。
# 默认训练步数 上限是20W步
python legacy/train.py --logtostderr --train_dir=./training/ --pipeline_config_path=./training/ssd_mobilenet_v1_coco.config
# 设置 训练的步数, --num_train_steps 是设置的步数值, --num_eval_steps 是设置的验证值
python legacy/train.py --logtostderr --train_dir=./training/ --pipeline_config_path=./training/ssd_mobilenet_v1_coco.config --num_train_steps=50000 --num_eval_steps=2000 --alsologtostderr
注意:
- 需要注意一下 “train.py”,这个文件中的 第62行对应的**“clone_on_cpu”** 这个值,这个值我理解的意思是“是否将任务放在cpu上运行”,默认是 False ,但是在我的电脑上运行训练到两百多步的时候就会报错,停止训练。只有把这个值设为 True 的时候,才会正常运行。但是此时应该就没有使用GPU去训练。
- 如果训练过程中出现错误,可能需要删除 **“training”**文件夹下生成的文件,否则将可能报错。训练过程也可以随时停止,再次执行训练将会从最近的记录点接着训练。
训练过程的截图:
训练过程可视化:
在TF-Object的虚拟控制台下 CD 到 research\object_detection目录下,然后执行如下代码即可看到可视化界面。
tensorboard --logdir=training
训练过程中程序会自动报存近期的训练结果,顺利的情况下将会在 “training” 文件夹下产生如下文件:
生成最终的训练文件
停止训练以后,我们需要依靠“training”文件夹里的训练文件生成最终的模型文件。
- 先在 “object_detection” 文件夹下新建 “panda_detection” 文件夹,用来存放最终的模型文件。
- 在 “object_detection” 文件夹下执行如下代码,执行成功即可生成最终的模型文件(代码中 “model.ckpt-200000” 是表示 “training” 文件夹下我们将要使用的 “model.ckpt-200000.meta” 文件)。
python export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path training/ssd_mobilenet_v1_coco.config \ --trained_checkpoint_prefix training/model.ckpt-200000 \ --output_directory panda_detection
执行成功将会在 “panda_detection”文件夹下生成如下文件:
测试训练文件
在 “object_detection” 文件夹下创建 test.py ,将如下代表复制进去,然后修改 “self.PATH_TO_CKPT = ‘ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb’” 中的PD文件路径和**“ self.PATH_TO_LABELS = os.path.join(‘data’, ‘mscoco_label_map.pbtxt’)”** 中的pbtxt文件路径即可运行测试。
# coding:utf8
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
sys.path.append("..")
from utils import label_map_util
from utils import visualization_utils as vis_util
class TOD(object):
def __init__(self):
# Path to frozen detection graph. This is the actual model that is used for the object detection. 冻结检测图的路径。 这是用于对象检测的实际模型。
self.PATH_TO_CKPT = 'ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box. 用于为每个框添加正确标签的字符串的列表。
self.PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
self.NUM_CLASSES = 90
self.detection_graph = self._load_model()
self.category_index = self._load_label_map()
def _load_model(self):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return detection_graph
def _load_label_map(self):
label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=self.NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
return category_index
def detect(self, image):
with self.detection_graph.as_default():
with tf.Session(graph=self.detection_graph) as sess:
# Expand dimensions since the model expects images to have shape: [1, None, None, 3] 扩展维度,因为模型期望图像具有以下形状:[1,None, None, 3]
image_np_expanded = np.expand_dims(image, axis=0)
image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected. 每个框表示检测到特定对象的图像的一部分。
boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects. 每个分数表示每个对象的置信度。
# Score is shown on the result image, together with the class label. 分数与类标签一起显示在结果图像上。
scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection. 实际检测。
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection. 检测结果的可视化。
vis_util.visualize_boxes_and_labels_on_image_array(
image,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
self.category_index,
use_normalized_coordinates=True,
line_thickness=8)
while True:
cv2.namedWindow("detection", cv2.WINDOW_NORMAL)
cv2.imshow("detection", image)
if cv2.waitKey(110) & 0xff == 27:
break
if __name__ == '__main__':
image = cv2.imread('test_images/image1.jpg')
detecotr = TOD()
detecotr.detect(image)
我的测试结果如下图(效果不好 是因为训练使用的样本文件太少):