您的位置:首页 > 移动开发 > Objective-C

目标检测实战(一)--使用TensorFlow Object Detection API检测自己的图像数据集

2020-01-14 07:31 1676 查看

下载并使用labelimg

网上有很多关于labelimg的下载方法
labelimg下载链接

打开labelimg效果如下

左边的工具栏说明:
1.open是打开单张图片
2.open dir是打开一个包含图像的文件夹
3.change save dir是选定你图片标注好之后,标注文件保存的位置
4.next image和prev image分别代表下张图片和上张图片
5.save是每此一张图片标注完之后保存
6.PascalVOC或者yolo可以来回切换保存格式,一般用前者(为xml)
7.Creat/nrectBox表示画矩形框

下载安装TensorFlow Object Detection API

博客安装教程
下载地址

处理数据

图片是从网上采集的,通过labelimg我们得到了多个xml标注文件文件(每张图片的),我们必须把它们转换成tfrecord文件。
首先使用以下代码(xml_to_csv.py):

# -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 14:20:54 2019

@author: asus
"""
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

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():
os.chdir(r"C:\Users\asus\mouse_project_file\annotations")
image_path = os.path.join(os.getcwd(), 'train_xml')
xml_df = xml_to_csv(image_path)
os.chdir(r"C:\Users\asus\mouse_project_file\data")
xml_df.to_csv('train_labels.csv', index=None)
print('Successfully converted xml to csv.')

main()

注意:
需要将main函数里面的输入文件和输出文件改成自己的;
xml_to_csv函数的参数为输入文件(就是xml所在文件夹);
最后输出的是一个csv文件(我的csv文件名叫train_labels用于训练,同时也可以生成test_labels用于测试),如下图:

进入该代码文件位置,执行python xml_to_csv.py
无异常会输出:Successfully converted xml to csv.

接下来将csv文件转换为tfrecord文件,执行以下代码

"""
Created on Thu Oct 10 14:34:30 2019

@author: asus
"""

"""
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=train.record
# Create test data:
python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
"""

# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

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

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 == 'belt':
return 1
elif row_label == 'milk':
return 2
else:
return 3

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(_):
os.chdir(r"C:\Users\asus\mouse_project_file\data")
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
os.chdir(r"C:\Users\asus\mouse_project_file")
path = os.path.join(os.getcwd(), r'images\test_images')
print(path)
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()
os.chdir(r"C:\Users\asus\mouse_project_file\data")
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))

if __name__ == '__main__':
tf.app.run()

注意修改class_text_to_int函数,将自己的类别修改到编号
进入到相应的目录,执行
#Create train data:
python generate_tfrecord.py --csv_input=train_labels.csv --output_path=train.record

#Create test data:
python generate_tfrecord.py --csv_input=test_labels.csv --output_path=test.record
这里的csv_input为csv文件,output_path为输出的tfrecord文件,这样就得到了train.record文件和test.record文件

参数配置

这里首先配置一个pbtxt文件(建议下载一个Notepad,查看代码,文件比较方便),具体内容如下:

如果有多个类别,就写多个item就行了

接下来配置模型参数文件
不同的模型有不同的参数配置文件,这里我们使ssd_mobilenet_v1_coco
模型下载链接:
模型文件model zoo
这个链接里面有许多模型可供下载
同时在tensorflow\models\research\object_detection\samples\configs有每个模型对应的config文件
模型下载解压之后,得到ssd_mobilenet_v1_coco_2018_01_28模型文件夹,然后找到对应的config文件tensorflow\models\research\object_detection\samples\configs\ssd_mobilenet_v1_coco.config


config中有几个必须要修改的参数:
1.num_classes:设置为你的类别数量
2.batch_size:设置batch值
3.fine_tune_checkpoint:预训练模型位置
4.num_steps:总步数
5.input_path:record训练或测试文件位置
6.label_map_path: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: 6
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
}
}
fine_tune_checkpoint: "mouse_project_file/model/model.ckpt"
from_detection_checkpoint: true
# 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: 9000
data_augmentation_options {
random_horizontal_flip {
}
}
data_augmentation_options {
ssd_random_crop {
}
}
}

train_input_reader: {
tf_record_input_reader {
input_path: "mouse_project_file/data/train.record"
}
label_map_path: "mouse_project_file/training/label.pbtxt"
}

eval_config: {
num_examples: 30
# Note: The below line limits the evaluation process to 10 evaluations.
# Remove the below line to evaluate indefinitely.
max_evals: 20
}

eval_input_reader: {
tf_record_input_reader {
input_path: "mouse_project_file/data/test.record"
}
label_map_path: "mouse_project_file/training/label.pbtxt"
shuffle: False
num_readers: 1
}

可以在以上的基础上修改

开始训练

进入(cd)tensorflow\models\research\object_detection\legacy有一个train.py文件
执行以下语句:

python object_detection/legacy/train.py \
--logtostderr \
--train_dir=mouse_project_file\result \
--pipeline_config_path=mouse_project_file/ssd_mobilenet_v1_coco.config

train_dir为模型保存路径
pipeline_config_path为参数配置路径
其它参数的具体含义可以查看train.py文件

测试及可视化

在训练过程中,你也可以测试模型的效果,打开另一个窗口,执行以下语句:

python eval.py \
--logtostderr \
--pipeline_config_path=mouse_project_file/ssd_mobilenet_v1_coco.config \
--checkpoint_dir=mouse_project_file\result \
--eval_dir=mouse_project_file/eval

pipeline_config_path:参数配置文件
checkpoint_dir:模型保存文件夹
eval_dir:测试结果保存文件
其它参数配置,详见eval.py文件

同时,你也可以进行可视化,这是对测试结果的可视化,执行以下命令:

tensorboard \
--logdir=mouse_project_file/eval

也可以对训练结果可视化:

tensorboard \
--logdir=mouse_project_file/result


上图是测试集可视化的效果

导出模型

python object_detection/export_inference_graph.py --input_type=image_tensor --pipeline_config_path=mouse_project_file\ssd_mobilenet_v1_fpn_shared_box_predictor_640x640_coco14_sync.config --trained_checkpoint_prefix=mouse_project_file\ssd_mobilenet_v1_fpn_shared_box_predictor_640x640_coco14_sync_result\model.ckpt-2996 --output_directory=mouse_project_file\frz_out

1.input_type:输入节点类型,一共有三种类型(

image_tensor
,
encoded_image_string_tensor
,
tf_example

2.pipeline_config_path:模型对应的配置文件路径
3.trained_checkpoint_prefix:模型文件位置
4.output_directory:导出文件位置
其它参数详见export_inference_graph.py
导出样例如下:

训练效果



参考文献:
1.https://blog.csdn.net/qq_38593211/article/details/82823255
2.https://blog.csdn.net/Kalenee/article/details/80629262

  • 点赞
  • 收藏
  • 分享
  • 文章举报
到达起点 发布了25 篇原创文章 · 获赞 0 · 访问量 403 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐