在配置完TensorFlow-object-detection-api的环境变量后,可以运行官方的demo。接下来就是通过自己训练的模型识别自己所需要的图片。先说明在此过程中遇到的两大巨坑:
1,在anaconda prompt下文件名中不能用空格,即空格可用_替代,这样可以为以后省下不少麻烦
2,在下载TensorFlow时,使用TensorFlow-gpu,因为cpu下实在太慢,下载gpu时,要用到cudnn和cuda,这是在网上找的教程,较为详细:
https://v.youku.com/v_show/id_XMzgwOTUzNDU3Ng==.html?x&sharefrom=android&sharekey=d9547d3a1b5e967e76a1d062b6c6446b1
下面为具体过程:
1,使用labelIMg进行数据集的收集,在image文件夹下建立train和test文件(分别包含jpg和xml文件)
因为TensorFlow默认识别一种为record的文件夹,所以要用两个脚本文件,分别实现xml_to_csv,和生成record文件,代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 23:58:21 2018
@author: asus
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 00:52:02 2018
@author: Xiang Guo
"""
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
os.chdir('D:\\object_detection_api\\models-master\\research\\object_detection\\image\\test')
path = 'D:\\object_detection_api\\models-master\\research\\object_detection\\image\\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)
xml_df.to_csv('LYF_test.csv', index=None)
print('Successfully converted xml to csv.')
main()
在xml转csv过程中,主要文件路径(是两个反斜杠),还有最后生成的文件名。之后可分别在test和train文件下生成LYF_test.csv和LYF_train_csv文件。之后,将这两个文件夹放入object_detection文件夹下的data文件夹内
之后,运行generate_TFR.py,生成record文件,这一步中,要特别注意在代码92行,记得路径问题,另外需要注意的是,需在D:\object_detection_api\models-master\research目录下运行此python脚本文件。此python脚本文件如下:
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 01:04:55 2018
@author: Xiang Guo
"""
"""
Usage:
# From tensorflow/models/
# Create train data:
python generate_TFR.py --csv_input=data/LYF_train.csv --output_path=data/LYF_train.record
# Create test data:
python generate_TFR.py --csv_input=data/LYF_test.csv --output_path=data/LYF_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
os.chdir('D:\\object_detection_api\\models-master\\research\\object_detection\\')
flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS
# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'LYF':
return 1
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)
path = os.path.join(os.getcwd(), 'image\\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()
至此,在data文件夹下分别有两个csv文件和record文件。
2,config文件的配置:
模型地址:https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs
以选的模型ssd_mobilenet_v1_coco.config为例,将ssd_mobilenet_v1_coco.config放在training文件夹内,并用文本编辑器notepad++打开,因为我的标识对象只有一个“LYF”,修改第九行num_classes:为1,141行的bitch_wise为4,在171行-189行分别设置训练和测试的路径,并在data文件夹下新建一个LYF.pbtxt文件夹。config文件代码和LYF.pbtxt文件代码分别如下:
# 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: 4
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/LYF_train.record"
}
label_map_path: "data/LYF.pbtxt"
}
eval_config: {
num_examples: 8000
# 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/LYF_test.record"
}
label_map_path: "data/LYF.pbtxt"
shuffle: false
num_readers: 1
}
item {
id: 1
name: "LYF"
}
3,训练模型
注意:!!!!!!为避免GPU显存被占满,在训练命令执行前,先执行命令
Windows SET CUDA_VISIBLE_DEVICES=0
Linux export CUDA_VISIBLE_DEVICES=0
之后执行训练命令:
python legacy/train.py --pipeline_config_path=D:/object_detection_api/models-master/research/object_detection/training/ssd_mobilenet_v1_coco.config --train_dir=D:/object_detection_api/models-master/research/object_detection/training --num_train_steps=100 --num_eval_steps=5 --alsologtostderr
之后,可以看到训练开始了,如图所示是我训练八个小时后的结果:
打开tensorboard可视化训练过程:
tensorboard --logdir=training
4,导出模型
在object_detection文件夹下运行export_inference_graph.py文件,运行时,需要使用以下命令行:
python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/ssd_inception_v3_pets.config --trained_checkpoint_prefix training/model.ckpt-15441 --output_directory person_detection
ckpt后的数字根据自己上一步training文件夹下最大的训练步数判断,LYF_detection是我在object_detection文件夹下新创建的,运行成功后,会在文件夹下生成如下文件:
其中,.pb文件就是下一步需要测试的模型。
测试结果及源码见:http://localhost:8888/notebooks/object_detection_tutorial-Copy1.ipynb
部分测试结果如下:
可见,由于数据集过小,测试结果不尽人意,但终于走通了第一步!
整个过程自己走了很过弯路,也不算是弯路吧,想成功一点终究要付出辛苦的,路漫漫其修远兮,吾将上下而求索!