Tensorflow object detection API 实现自己数据集的建立和检测

写在前边:

Tensorflow object detection API 实现自己数据集的建立和检测 流水账,详细步骤请参考大神博客还有视频讲解:

https://blog.csdn.net/dy_guox/article/details/79111949


环境:

Window 7 64X

Anaconda 3 + python 3.5.2 +Tensorflow 1.9.0 +CPU + Tensorflow object detection API


(一) 数据集的建立

        A: 标注数据集 : 使用 LabelImg这款小软件,对数据集进行标注,每张图片生成一个同名字的.xml文件。(大神博主使用将图片和.xml放在同一个文件夹下。)

        B:数据集格式转换:Tensorflow 框架拥有自己的数据平台,需要输入专门的TFRecords Format 格式。

大神写两个小python脚本文件,xml_to_csv.py:将文件夹内的xml文件内的信息统一记录到.csv表格中(运行时修改数据地址,以及.cvs的文件名),generate_tfrecord.py :从.csv表格中创建TFRecords格式,见大神博主的github。(小白的代码保留位置)

注意:生成的.csv文件中文件名要和数据集相同。将原始图像数据集存放在\models\research\object_detection\images文件夹下(没有就创建一个),如果训练数据集和测试数据集不重叠需要放在两个文件夹下,我均放在了images文件夹下,也没有保存。

-data/  --test_labels.csv  --test.record   --train_labels.csv   --train.record

-images/   --test/*.jpg    --train/*.jpg

将转化后的.csv文件存放在object_detection\data文件夹下,博主提出需要将generate_tfrecord.py文件放在object_detection\文件夹下,并修改一下代码,最终生成对应的.tfrecond文件。

# 改 .csv文件存放地址
os.chdir('D:\\Python3.6.1\\TF_models\\models\\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

# 改 row_label 标签名字,和有几个标签类别,
# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'fire':
        return 1
    # elif row_label == 'vehicle':
    #    return 2
    else:
        None

结果图:


(二)配置文件与模型

(1) 接下来需要设置配置文件, 进入 Object Detection github  参数对应页面下载寻找 配置文件的Sample。

以 faster_rcnn_resnet50_coco.config 为例,将其放在training 文件夹下(没有就创建一个),用文本编辑器打开(我用的notebook),进行如下操作:

(1)
    num_classes: 1
(2)
      batch_size: 1
(3)听话的注释掉了一下两行内容 
 # fine_tune_checkpoint: "PATH_TO_BE_CONFIGURED/model.ckpt"
 # from_detection_checkpoint: true
(4)修改自己的地址和.record名字 
    //train_input_reader: 
        input_path: "data/Fire_train.record"
        label_map_path:"data/Fire.pbtxt"
    //eval_input_reader:
        input_path: "data/Fire_test.record"
        label_map_path: "data/Fire.pbtxt"

(2)在data文件夹下创建上一步中修改的label_map_path:"data/Fire.pbtxt"所对应的文件。复制一个原有的.pbtxt文件命名为Fire.pbtxt,内容修改为:

item {
  id: 1
  name: 'fire'
}
#item {
#  id: 2
#  name: 'blabla'
#}

完成配置,可以训练模型了!!


(三)训练

(1)在models\research\object_detection文件夹下打开命令行,运行如下命令:(注意位置参数)

python ./legacy/train.py --logtostderr --train_dir=E:/TFmodel/models/research/object_detection/training/ --pipeline_config_path=E:/TFmodel/models/research/object_detection/training/faster_rcnn_resnet50_coco.config

注:中途打断也不要紧,可以再次运行上述Python命令,会从上次的checkpoint继续。

(2)Tensorboard来可视化训练过程。(models\research\object_detection文件夹下

tensorboard --logdir='training'

(3)保存模型

    在 models\research\object_detection 文件夹下找到 export_inference_graph.py 文件,要运行这个文件,还需要传入config以及checkpoint的相关参数。为了方便在models\research\object_detection 文件夹下创建文件Fire_detection文件夹用于存放此次检测的参数和测试数据,之后再object_detection 文件夹下打开命名行,运行

python export_inference_graph.py \ --input_type image_tensor \ --pipeline_config_path training/faster_rcnn_resnet50_coco.config \  --trained_checkpoint_prefix training/model.ckpt-150 \  --output_directory Fire_detection

--trained_checkpoint_prefix training/model.ckpt-150   这个checkpoint(.ckpt-后面的数字)可以在training文件夹下找到你自己训练的模型的情况,填上对应的数字(如果有多个,选最大的)。

--output_directory Fire_detection是参数存放的地址。

(5)测试
     可根据object_detection_tutorial.ipynb 更改。

我的测试代码如下:为.py文件,删除了部分无用注释。


# coding: utf-8

# import cv2
import numpy as np
import os
import six.moves.urllib as urllib
import sys
# import tarfile
import tensorflow as tf
# import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops

if tf.__version__ < '1.4.0':
  raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')

from utils import label_map_util
from utils import visualization_utils as vis_util

# 修改
MODEL_NAME = 'JGB_detection'
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
PATH_TO_LABELS = os.path.join('data', 'Fire.pbtxt')
# 修改
NUM_CLASSES = 1

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)


def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)

# 修改
PATH_TO_TEST_IMAGES_DIR = 'Fire_detection/test_images'
TEST_IMAGE_PATHS = os.listdir('E:\\TFmodel\\models\\research\\object_detection\\Fire_detection\\test_images')
os.chdir('E:\\TFmodel\\models\\research\\object_detection\\Fire_detection\\test_images')

IMAGE_SIZE = (12, 8)

def run_inference_for_single_image(image, graph):
  with graph.as_default():
    with tf.Session() as sess:
      # Get handles to input and output tensors
      ops = tf.get_default_graph().get_operations()
      all_tensor_names = {output.name for op in ops for output in op.outputs}
      tensor_dict = {}
      for key in [
          'num_detections', 'detection_boxes', 'detection_scores',
          'detection_classes', 'detection_masks'
      ]:
        tensor_name = key + ':0'
        if tensor_name in all_tensor_names:
          tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
              tensor_name)
      if 'detection_masks' in tensor_dict:
        # The following processing is only for single image
        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
            detection_masks, detection_boxes, image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(
            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
        # Follow the convention by adding back the batch dimension
        tensor_dict['detection_masks'] = tf.expand_dims(
            detection_masks_reframed, 0)
      image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

      # Run inference
      output_dict = sess.run(tensor_dict,
                             feed_dict={image_tensor: np.expand_dims(image, 0)})

      # all outputs are float32 numpy arrays, so convert types as appropriate
      output_dict['num_detections'] = int(output_dict['num_detections'][0])
      output_dict['detection_classes'] = output_dict[
          'detection_classes'][0].astype(np.uint8)
      output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
      output_dict['detection_scores'] = output_dict['detection_scores'][0]
      if 'detection_masks' in output_dict:
        output_dict['detection_masks'] = output_dict['detection_masks'][0]
  return output_dict

i=1
for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)
  # Actual detection.
  output_dict = run_inference_for_single_image(image_np, detection_graph)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks'),
      use_normalized_coordinates=True,
      line_thickness=8)
  
  # plt.figure(figsize=IMAGE_SIZE)
  plt.figure(figsize=image.size)
  plt.imshow(image_np)
  plt.axis('off')
  plt.savefig('E:TFmodel\\models\\research\\object_detection\\Fire_detection\\output_images\\%d.jpg'%(i))
  
  i=i+1

300张图片200次迭代输出结果,已经很不错了,使用fasterRcnn亲测没有SSD快!

  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值