使用object_detection_api进行训练和预测

使用object_detection_api进行训练和预测

将object_detection_api安装好以后,我们可以使用其进行transfer learning从而实现对新检测应用的快速学习,当然也可以使用训练好的模型进行预测。以下分别讲如何使用现有模型进行预测以及在训练好的模型基础上使用新数据集学习新的模型。
官网提供了在linux下使用的说明,这里说明如何在windows下进行使用,笔者在win7下进行了测试并运行成功。

使用现有模型进行预测

运行object_detection模型下的object_detection_tutorial.ipynb可以使用ssd_mobilenet_v1模型进行预测。将该notebook中的MODEL_NAME = 'faster_rcnn_resnet101_coco_2018_01_28'进行更改即可使用不同的模型进行预测。注意若当前文件夹下若存放相应模型文件,该代码会自动在当前路径下下载模型文件。

使用模型从头开始训练

Running the Training Job
    A local training job can be run with the following command:

        # From the tensorflow/models/research/ directory
        python object_detection/train.py \
            --logtostderr \
            --pipeline_config_path=${PATH_TO_YOUR_PIPELINE_CONFIG} \
            --train_dir=${PATH_TO_TRAIN_DIR}

    where ${PATH_TO_YOUR_PIPELINE_CONFIG} points to the pipeline config and ${PATH_TO_TRAIN_DIR} points to the directory in which training checkpoints and events will be written to. By default, the training job will run indefinitely until the user kills it.

按照官网说明,只需找到对应模型的pipeline写好即可。

使用pre-trained模型在新数据集上进行学习

detection_model_zoo中包含了很多预训练模型。
为了使用这些模型,我们需要依次准备以下内容:准备数据,设置object detection pipeline。

准备数据

数据准备可以参考原github中的说明。该网站中也提供了各种公开数据集的下载地址。这里使用的数据是2012 PASCAL VOC data set。准备数据的过程中的输入为原始数据的解压文件夹,输出为两个.tfrecord文件。使用的代码为create_pascal_tf_record.py(其目录为object_detection/dataset_tools/create_pascal_tf_record.py)
运行命令如下:

python ./dataset_tools/create_pascal_tf_record.py \
--data_dir=./data/VOCdevkit \
--year=VOC2012 \
--set=train \
--label_map_path=./data/pascal_label_map.pbtxt \
--output_path=./data/pascal_train.record

对应的文件结构如下:

--object_detection
    |-- dataset_tools
    |     |-- create_pascal_tf_record.py
    |-- data
    |     |-- VOCdevkit
    |     |-- pascal_label_map.pbtxt
    |

代码运行后会在object_detection/data目录下生成pascal_train.recordpascal_cal.record两个文件。之后我们使用这两个文件作为数据输入即可。

建立.config设置

在pre-trained模型下载下来后,其内会包含一个.config的文件,我们将其复制一下,改名为faster_rcnn_resnet101_voc.config,之后打开该文件,将PATH_TO_BE_CONFIGURED的路径修改为自己存储的路径。如我将文件以如下结构存放:

--object_detection
    |
    |--demo_VOC2012
    |    |
    |    |--faster_rcnn_resnet101_voc.config 
    |    |
    |    |--model.ckpt
    |    |
    |    |--pascal_train.record
    |    |--pascal_val.record
    |    |--pascal_label_map.pbtxt

可将其内代码改为fine_tune_checkpoint: "./demo_VOC2012/model.ckpt",input_path: "./demo_VOC2012/pascal_train.record", label_map_path: "./demo_VOC2012/pascal_label_map.pbtxt".其他代码保持不变即可。

模型训练运行以下代码即可:

python train.py --logtostderr --pipeline_config_path=./demo_VOC2012/faster_rcnn_resnet101_voc.config --train_dir=./demo_VOC2012/train

可能出现的问题

由于object_detection_API官方教程在linux下运行,加之其仍在测试阶段,所以可能会有一些bug和错误出现,这里列举一些我遇到的问题和解决方法。

  1. failed: tried to convert ‘t’ to a tensor. Argument must be a dense tensor range (0, 3) got shape [3], but wanted []
    这个问题出在learning_schedule.py文件。需找到安装api时的目录下的learning_schedule.py,将

    rate_index = tf.reduce_max(tf.where(tf.greater_equal(global_step, boundaries),
                                    range(num_boundaries),
                                    [0] * num_boundaries))
    rate_index = tf.reduce_max(tf.where(tf.greater_equal(global_step, boundaries),
                                    list(range(num_boundaries)),
                                    [0] * num_boundaries))
    

    方法来源:github_issue

  2. DataLossError: Unable to open table file Input/output Error

    这个问题是model restore的问题,由于新的模型存储从.ckpt变为存储为三个.ckpt文件,所以将fine_tune_checkpoints=设置为三个文件所在文件夹/model.ckpt即可。

  3. No module named ‘pycocotools’

    这个应该是由于cocoAPI没有安装的问题,但是官网仅仅提供了linux下安装的方法,win7下的安装目前我仍未成功。
    参考github-issuegithub-issue,我从philferriere-github中下载了cocoapi-master,解压后分别运行

    python setup.py build_ext --inplace
    python setup.py build_ext install
    

    (即makefile中的命令). 执行后没报错,且eval.py运行不再报上述问题了。

使用tensorflow object detection api训练自己的数据

数据存放结构

为了可以在api中使用自己生成的数据,与PASCAL VOC处理方法相似,我们需将数据文件夹转为tfrecord。相似地,我们采用相同的数据存放结构,我们将自己的数据以如下文件结构存放:

--data
  |--label_map.pbtxt
  |--VOC2007
  |    |--Annotations
  |    |--ImageSets
  |    |    |--Main
  |    |    |    |--train.txt
  |    |--JPEGImages
--create_xx_tf_record.py

其中annotations文件夹中存放标注文件(以xml格式文件存放),
JPEGImages文件夹中存放原图(以jpg格式存放),而label_map.pbtxt文件需自己来写,其内以字典形式存放不同的label类别(分类名称对应的整型分类),如:

item {
  id: 1
  name: cat
}
item {
  id: 2
  name: dog
}

这些文件都可以参考PASCAL VOC的示例来写。

数据处理代码

create_pascal_tf_record.py(在object_detection/dataset_tool目录下)复制到与data文件夹同目录下,这里我重命名为create_xx_tf_record.py。我们需要对其相关参数进行修改使其与自己的数据相匹配。如下:

data_dir 设为 ./data
label_map_path 设为 ./data/label_map.pbtxt
output_path 设为 ./data/xx_train.tfrecord

# 注释下列几个不用的语句
  # difficult_obj.append(int(difficult))
  # truncated.append(int(obj['truncated']))
  # poses.append(obj['pose'].encode('utf8'))
  # 'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),
  # 'image/object/truncated': dataset_util.int64_list_feature(truncated),
  # 'image/object/view': dataset_util.bytes_list_feature(poses),

# 若xml中未设置图像的width和height,则将
  width = int(data['size']['width'])
  height = int(data['size']['height'])
  改为 width, height = image.size

# 修改main函数中image path
    examples_path = os.path.join(data_dir, year, 'ImageSets', 'Main',
                             'train' + '.txt')
# 调试时一定要确保dict_to_tf_example()函数中full_path和主函数中的data都读取正确。
# 生成各文件时需保证.jpg和.xml一一对应,且和.pbtxt中的一致。

将以上改动设置好以后,运行create.py则可在output_path中生成tfrecord文件。

xml文件修改

create_xx_tf_record.pyimg_path变量的设置中用到了xml中的folder标签值(data[‘folder’]),因此需将xml中folder标签值改为image存放路径:VOC2007。该问题使用以下代码运行即可。

from xml.etree.ElementTree import parse, Element
import os

filepath = './xml'
xml_files = os.listdir(filepath)
for xml_file in xml_files:
    print("now {} is being processed".format(xml_file))
    xml_path = os.path.join(filepath, xml_file)
    doc = parse(xml_path)
    root = doc.getroot()

    # # Remove a few elements
    # root.remove(root.find('sri'))
    # root.remove(root.find('cr'))
    # # Insert a new element after <nm>...</nm>
    # root.getchildren().index(root.find('nm'))
    #
    # e = Element('spam')
    # e.text = 'This is a test'
    # root.insert(2, e)
    folder = root.find('folder')  # folder是<>中的值
    folder.text = 'VOC2007'  # text是<><>之间的值

    # Write back to a file
    # doc.write(xml_file, xml_declaration=True)
    doc.write(xml_file)

参考:python3-cookbook解析和修改xml

一些error

  1. 转存后的xml文件encoding=”US-ASCII”出错:
    这时需要注意doc.write()中encoding, xnl_declaration参数的设置
  2. float: division by zero
    width不能设置为0,按照上述方法设置
  3. 图片读入时出错,if image.format != ‘JPEG’:
    图片后缀是jpg不一定是jpg。需要使用二进制查看图片确定文件头(如wxMEdit)

修改.config配置文件

同样的,需在预训练模型的config文件基础上进行修改。主要修改以下参数:

  • num_classes: 分类数目。视数据分类数目而定
  • fine_tune_checkpoint:修改成github上下载的faster_rcnn的ckpt文件会导致无法训练的情况
  • step: 控制迭代数

训练代码文件存放结构

参考上篇总结,进行相似存放即可。训练时运行

python train.py --logtostderr --pipeline_config_path=./demo_XX/faster_rcnn_resnet101_xx.config --train_dir=./demo_XX/train    

eval时运行

python eval.py --logtostderr --pipeline_config_path=./demo_VOC2012/faster_rcnn_resnet101_xx.config --checkpoint_dir=./demo_xx/train --eval_dir=./demo_xx/eval

即可。

使用训练得到的ckpt进行预测

预测使用的代码是从object_detection_tutorial复制改写得到的,改名为demo_faster_rcnn_resnet101_xx.py。需要修改其中以下内容:

PATH_TO_CKPT = "./demo_XX/output/frozen_inference_graph.pb"  # .pb文件存储训练好的模型
PATH_TO_LABELS = './demo_XX/xx_label_map.pbtxt'  
num_classes = 4
PATH_TO_TEST_IMAGE_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, '00000{}.jpg'.format(i)) for i in range(1, 10) ]

其文件结构如下:

object detection
  |
  |--test_images
  |--demo_XX
  |     |
  |     |--train
  |     |--output
  |     |    |
  |     |    |--frozen_inference_graph.pb
  |     |--xx_label_map.pbtxt
  |--export_inference_graph.py
  |--demo_faster_rcnn_resnet101_xx.py

执行时需先将训练好的模型转为.pb格式文件(过程后述),然后在test_images文件夹中存放测试图像,同时测试数据的名称要以列表形式存放在TEST_IMAGE_PATHS中。准备妥当以后,运行

python demo_faster_rcnn_resnet101_xx.py

即可进行预测。

.ckpt转存为.pb文件

同样在/object detection文件夹中,export_inference_graph.py可以完成这个功能。运行该脚本只需将原始ckpt.meta所在文件夹目录, 输出目录, 以及pipeline目录设置好即可。如执行以下命令:

python export_inference_graph.py --input_type image_tensor --pipeline_config_path ./demo_XX/faster_rcnn_resnet101_xx.config --trained_checkpoint_prefix ./demo_XX/train/model.ckpt-83082 --output_directory ./demo_XX/output

整个过程总结与文件存放结构

  • 生成数据

    |--create_xx_tf_record.py
    |
    |--data
    |    |--VOC2007
    |    |    |--Annotations
    |    |    |    |--xml文件
    |    |    |--ImageSets
    |    |    |    |--Main
    |    |    |    |   |--txt文件
    |    |    |--JPEGImages
    |    |    |    |--jpg文件
    
  • 完成训练

    object_detection
        |
        |--demo_xx (存放某个应用/数据训练的结果)
        |    |
        |    |--train(训练model目录)
        |    |--faster_rcnn_resnet101_xx.config (预训练模型config,设置模型超参数)
        |    |--model.ckpt(三个)
        |    |--train.record
        |    |--val.record
        |    |--.pbtxt(数据label标注文件)
    
  • 完成测试(或完成eval)

    object detection
        |
        |--test_images (存放测试数据集图像)
        |--demo_XX (存放某个应用/数据训练的结果)
        |     |
        |     |--train(训练好的model目录)
        |     |--output
        |     |    |
        |     |    |--frozen_inference_graph.pb(训练好转存为.pb文件)
        |     |--xx_label_map.pbtxt
        |--export_inference_graph.py
        |--demo_faster_rcnn_resnet101_xx.py
    

整个文件结构(注意生成数据可以不依赖object detection库,可以在单独的文件夹下执行)

object detection
    |
    |--dataset tools
    |    |--create_xx_tf_record.py
    |    |
    |    |--data
    |    |    |--VOC2007
    |    |    |    |--Annotations
    |    |    |    |    |--xml文件
    |    |    |    |--ImageSets
    |    |    |    |    |--Main
    |    |    |    |    |   |--txt文件
    |    |    |    |--JPEGImages
    |    |    |    |    |--jpg文件
    |
    |--demo_xx (存放某个应用/数据训练的结果)
    |    |
    |    |--train(训练model目录)
    |    |--output
    |    |    |--frozen_inference_graph.pb(训练好转存为.pb文件)

    |    |--faster_rcnn_resnet101_xx.config (预训练模型config,设置模型超参数)
    |    |--model.ckpt(三个)
    |    |--train.record
    |    |--val.record
    |    |--.pbtxt(数据label标注文件)

    |--test_images (存放测试数据集图像)
    |--export_inference_graph.py(用于将.ckpt文件转化为.pb)
    |--demo_faster_rcnn_resnet101_xx.py(用于预测test)

猜你喜欢

转载自blog.csdn.net/u010103202/article/details/79958423