安装

首先下载TF models,官网地址:https://github.com/tensorflow/models

Research目录下包含了Object Detection这个API。

官方安装指南:

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md

安装很简单,按着官方指南一步步来就可以了。

数据集处理

我的数据是VOC的格式,自己新建一个目录用来存放自己的数据,然后在这个目录下将.xml文件放在xml_file文件夹下,.jpg图片放在images文件夹下。

将数据分成三部分:train、test、validation。贴上代码:

import os
import random
import time
import shutil

xmlfilepath=r'xml_file'
saveBasePath=r"./Annotations"

trainval_percent=0.9
train_percent=0.85
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)

print("train and val size",tv)
print("train size",tr)
start = time.time()

test_num=0
val_num=0
train_num=0

for i  in list:
    name=total_xml[i]
    if i in trainval:
        if i in train:
            directory="train"
            train_num+=1  
            xml_path=os.path.join(os.getcwd(),'Annotations/{}'.format(directory))
            if(not os.path.exists(xml_path)):
                os.mkdir(xml_path)
            filePath=os.path.join(xmlfilepath,name)
            newfile=os.path.join(saveBasePath,os.path.join(directory,name))
            shutil.copyfile(filePath, newfile)

        else:
            directory="validation"
            xml_path=os.path.join(os.getcwd(),'Annotations/{}'.format(directory))  
            if(not os.path.exists(xml_path)):
                os.mkdir(xml_path)
            val_num+=1
            filePath=os.path.join(xmlfilepath,name)
            newfile=os.path.join(saveBasePath,os.path.join(directory,name))
            shutil.copyfile(filePath, newfile)
    else:
        directory="test"
        xml_path=os.path.join(os.getcwd(), 'Annotations/{}'.format(directory))
        if(not os.path.exists(xml_path)):
            os.mkdir(xml_path)
        test_num+=1
        filePath=os.path.join(xmlfilepath,name)
        newfile=os.path.join(saveBasePath,os.path.join(directory,name))
        shutil.copyfile(filePath, newfile)

end = time.time()
seconds=end-start
print("train total : "+str(train_num))
print("validation total : "+str(val_num))
print("test total : "+str(test_num))
total_num=train_num+val_num+test_num
print("total number : "+str(total_num))
print( "Time taken : {0} seconds".format(seconds))

执行完之后会产生一个Annotations目录,这个目录下有train、test、validation三个目录,每个目录下有分好的.xml文件。

将.xml转换成.csv。新建csv文件夹,用来存放.csv文件。代码,注意路径:

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()
        print(root.find('filename').text)
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text), #width
                     int(root.find('size')[1].text), #height
                     member.find('name').text,
                     int(member.find('bndbox')[0].text),
                     int(member.find('bndbox')[1].text),
                     int(member.find('bndbox')[2].text),
                     int(member.find('bndbox')[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():
    for directory in ['train','test','validation']:
        xml_path = os.path.join(os.getcwd(), 'Annotations/{}'.format(directory))
        xml_df = xml_to_csv(xml_path)
        xml_df.to_csv('csv/ngy_{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')

main()

将.csv转成.tfrecord,注意要改一下label,改成你自己数据集的label,代码,注意路径:

"""
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
"""
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 == 'car':
        return 1
    elif row_label == 'umbrellaman':
        return 2
    elif row_label == 'cone':
        return 3
    elif row_label == 'person':
        return 4
    else:
        return 0


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(), 'images')
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    num=0
    for group in grouped:
        num+=1
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())
        print(num)

    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()

然后用一个脚本来执行,修改下自己的路径:

#!/bin/bash

python3 csv_to_tfrecords.py --csv_input=csv/ngy_train_labels.csv --output_path=csv/ngy_train.tfrecord
python3 csv_to_tfrecords.py --csv_input=csv/ngy_test_labels.csv --output_path=csv/ngy_test.tfrecord
python3 csv_to_tfrecords.py --csv_input=csv/ngy_validation_labels.csv --output_path=csv/ngy_validation.tfrecord

就可以得到train、test、validation的tfrecords。

创建标签文件

将.tfrecord文件放在你想放的目录下,

在object_detection目录下创建自己的目录,我自己建了training/ssd_inception_v2_ngy目录,

在该目录下创建ngy_label_map.pbtxt,写入类别标签,跟之前的对应就行:

item {
	id: 1
	name: 'car'
}

item {
	id: 2
	name: 'umbrellaman'
}

item {
	id: 3
	name: 'cone'
}

item {
	id: 4
	name: 'person'
}

下载预训练模型

这个页面有许多模型可供下载,这里我选择ssd_inception_v2:

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

修改配置文件

找到samples/configs目录下的ssd_inception_v2_coco.config,复制到ssd_inception_v2_ngy目录下,修改配置,注意类别数目和自己的各种路径:

num_classes: 4
fine_tune_checkpoint: "ssd_inception_v2_coco_2017_11_17/model.ckpt"
train_input_reader: {
  tf_record_input_reader {
    input_path: "data/ngy_train.tfrecord"
  }
  label_map_path: "training/ssd_inception_v2_ngy/ngy_label_map.pbtxt"
}
eval_input_reader: {
  tf_record_input_reader {
    input_path: "data/ngy_validation.tfrecord"
  }
  label_map_path: "training/ssd_inception_v2_ngy/ngy_label_map.pbtxt"
  shuffle: false
  num_readers: 1
}

开始训练

执行脚本:

python train.py \
    --train_dir=training/ssd_inception_v2_ngy \
    --pipeline_config_path=training/ssd_inception_v2_ngy/ssd_inception_v2_coco.config \

如果一切正常就会看到每一步的loss。

evaluation

可以使用eval.py一边训练一边eval。

但是我显存不够了,查到网上有人用一种方法也可以eval:用cpu来eval。

进eval.py,添加一行代码:

os.environ["CUDA_VISIBLE_DEVICES"]=""

将gpu device设为空,就可以使用cpu进行eval。

修改一下ssd_inception_v2_ngy/ssd_inception_v2_coco.config文件:

eval_config: {
num_examples: 2519
num_visualizations: 10

参数大小根据实际情况设定。

如果训练完了再eval,那程序可能会一直挂那,卡着不动。貌似是官方的一个bug,它要检测出一个新的checkpoint生成再eval,如果训练完是没有新的checkpoint生成的所以会挂那。好像有人解决了这个问题,是在eval_util.py文件中加一行代码:

logging.basicConfig(level=logging.INFO)

导出模型

创建目录:object_detection/inference_graph/ssd_ngy_inference_graph,用来存放导出的模型

执行脚本:

#!/bin/bash

python3 export_inference_graph.py \
    --input_type image_tensor \
    --pipeline_config_path training/ssd_inception_v2_ngy/ssd_inception_v2_coco.config \
    --trained_checkpoint_prefix training/ssd_inception_v2_ngy/model.ckpt-153376 \
    --output_directory inference_graph/ssd_ngy_inference_graph/153376

demo

有一个object_detection_tutorial.ipynb,打开notebook进去改改,把加载模型路径换成自己训练的结果,然后下面那个执行程序它是批量的,自己改成单张就好了,这步比较简单,不说了。当然,改成摄像头程序也是可行的。