api的安装过程参考其他博客:
将csvData文件夹复制进 object_detection/data 路径
在此路径下创建脚本 generate_tfrecord.py
# generate_tfrecord.py
# -*- coding: utf-8 -*-
"""
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
os.chdir('/home/mingjie/tf_model/models/research/object_detection/data') #修改为自己的路径
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 == 'car': # 修改为自己的类别
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(), 'CsvFile/images') # 需改动
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()
生成训练集文件
python generate_tfrecord.py --csv_input=../object_detection/data/CsvFile/train.csv --output_path=train.record
生成验证集文件
python generate_tfrecord.py --csv_input=../object_detection/data/CsvFile//test.csv --output_path=test.record
成功运行的话,在data路径下会生成 train.record
和test.record
两个文件
在 object_detection/samples/configs 路径下找到对应网络的config文件
以 ssd-mobilenet-v2 为例,对应文件为ssd_mobilenet_v2_coco.config
打开终端,在object detection
路径下输入:
python3 model_main.py \
--pipeline_config_path=training/ssd_mobilenet_v2_coco.config \
--model_dir=training \
--num_train_steps=150000 \
--num_eval_steps=100 \
--alsologtostderr
即开始训练
在训练过程中,每隔一轮会保存ckpt文件于training文件夹,直至达到训练次数或手动停止
tensorboard
能够将训练过程可视化,以此查看训练情况(及时止损)
tensorboard --logdir=training
在浏览器输入地址 http://localhost:6006/ (终端会输出一个网址,将其复制到浏览器地址栏)
打开终端, 进入 object_detection 路径
python3 export_inference_graph.py --input_type image_tensor --pipeline_config_path training/ssd_mobilenet_v2_coco.config --trained_checkpoint_prefix training/model.ckpt-7988 --output_directory trained_model
输入参数:
--pipeline_config_path:
训练时所用的config文件--trained_checkpoint_prefix:
指定训练次数的model.ckpt--output_directory trained_model:
输出pb文件到此路径下以 ssd-mobilenet-v2 为例,需要用到 opencv/samples/dnn 路径下的tf_graph_ssd.py
脚本
python /home/mingjie/pmj_softwares/opencv-4.3.0/samples/dnn/tf_text_graph_ssd.py --input=./trained_model/frozen_inference_graph.pb --output=./trained_model/v2.pbtxt --config=./training/ssd_mobilenet_v2_coco.config
将opencv路径按自己环境修改