Tensorflow1.9训练ssd-mobilenet

使用Tensorflow1.9用自己的数据集训练ssd-mobilenet

1.环境搭建

电脑装了ubuntu20.04,nv驱动的安装比较简单了,直接在设置里就额外驱动里就可以找到,如果那里没有,就下载一个nv驱动,点击安装却并不真地安装,这样而外驱动的选项卡里就会有了

1.1安装docker

就按照官网的步骤安装

https://www.docker.com/

1.2使用docker安装tensorflow

按照官网教程安装

https://tensorflow.google.cn/install/docker

1.3使用docker安装cuda支持

按照教程安装,注意保证网络通畅

https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker

上述都安装完毕以后,就可以打开支持gpu的tensorflow image了,这里选择了tensorflow 1.9 + protobuf 3.6的组合

2.制作训练集

2.1数据采集

首先获取训练集图片,可以自己写一段程序来截图,也可以录制视频再转换成图片,这里使用第二种方法走一遍整个流程。

使用ubuntu自带程序cheese连接相机录制视频(如果没有cheese安装一个)

使用ffmpeg将视频转换为图片

sudo apt-get install cheese 
sudo apt-get install ffmpeg
//            视频路径       每隔几秒截取一张图片    图片路径              
ffmpeg -i  ./test/video.mpg -r 1 -f image2 temp/%05d.png

参考链接:https://blog.csdn.net/felaim/article/details/73656049

2.2数据标注

使用LabelImg标注工具:https://github.com/tzutalin/labelImg

如果环境安装不明白,强烈推荐直接用docker

docker run -it \
--user $(id -u) \
-e DISPLAY=unix$DISPLAY \
--workdir=$(pwd) \
--volume="/home/$USER:/home/$USER" \
--volume="/etc/group:/etc/group:ro" \
--volume="/etc/passwd:/etc/passwd:ro" \
--volume="/etc/shadow:/etc/shadow:ro" \
--volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
-v /tmp/.X11-unix:/tmp/.X11-unix \
tzutalin/py2qt4

参考连接:https://blog.csdn.net/xunan003/article/details/78720189

2.3数据格式转换

1)将xml转为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()
        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():
    for folder in ['train','test']:
        image_path = os.path.join(os.getcwd(), ('images/' + folder))  #这里就是需要访问的.xml的存放地址
        xml_df = xml_to_csv(image_path)                               #object_detection/images/train or test
        xml_df.to_csv(('images/' + folder + '_labels.csv'), index=None)
        print('Successfully converted xml to csv.')


main()

通过修改为自己的xml路径与输出路径,就可以完成转换。这个代码对应的目录结构为:

Tensorflow1.9训练ssd-mobilenet

 生成train_labels.csv 和 test_labels.csv

2)将csv转换为TFrecord

TFrecord是google专门设计的一种数据格式,速度快,占用内存少。

这里据说有两种转换方式:https://blog.csdn.net/qq_38593211/article/details/82823255?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

我是用的别的博客上的python脚本转换的

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

  # Create test data:
  python generate_tfrecord.py --csv_input=images/test_labels.csv  --image_dir=images/test --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('image_dir', '', 'Path to the image directory')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# M1,this code part need to be modified according to your real situation
def class_text_to_int(row_label):
    if row_label == 'nine':
        return 1
    elif row_label == 'ten':
        return 2
    elif row_label == 'jack':
        return 3
    elif row_label == 'queen':
        return 4
    elif row_label == 'king':
        return 5
    elif row_label == 'ace':
        return 6
    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(), FLAGS.image_dir)
    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()

这个脚本用的是tensorflow1,所以如果你用的是tensorflow2那么这个脚本就用不了

这个脚本运行时也有一些坑,主要有两个

一个是数据集路径设置一定要正确

还有一个是class_text_to_int这个函数里的标签设置必须和自己制作的数据集对应

python generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.record
python generate_tfrecord.py --csv_input=images/test_labels.csv  --image_dir=images/test --output_path=test.record

这里代码对应的目录结构为:

object_detection >> images >> train + test

这句代码是在object_detection目录中执行的,可以顺利生成TFrecord文件

3.训练模型

这里许多博客都是说下载自己需要的模型,然后解压到object_detection API的目录下,例如自己下载了一个ssd_model,那么就把它解压到如下目录里

models/research/object_detection/ssd_model

但是那些博客给的模型下载连接都失效了,应给是tf2以后这里发生了比较大的变化,后来我在一篇博客里下载到了一个,但是忘记下载链接了。所谓的模型就是以下几个文件:

Tensorflow1.9训练ssd-mobilenet

这个连接里给的模型我没有试,里边只有一个frozen_inference_graph.pb: https://pan.baidu.com/s/17hyoo-7zrVOc8ZAX8XEh3w 提取码:noff 

3.1拷贝并且修改两个配置文件

    cp object_detection/data/pascal_label_map.pbtxt object_detection/ssd_model/
    cp object_detection/samples/configs/ssd_mobilenet_v1_pets.config object_detection/ssd_model/

.pbtxt文件里存的是识别的类别标签,需要根据自己的数据集进行更改,下边是文件原来的样子

item {
  id: 1
  name: 'aeroplane'
}

item {
  id: 2
  name: 'bicycle'
}

item {
  id: 3
  name: 'bird'
}

item {
  id: 4
  name: 'boat'
}

item {
  id: 5
  name: 'bottle'
}

.config文件是和训练有关的参数,我们必须要改的是5个路径:

  // 这个路径要改成自己的
  fine_tune_checkpoint: "PATH_TO_BE_CONFIGURED/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: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

// 下边路径要改成自己的
train_input_reader: {
  tf_record_input_reader {
    input_path: "PATH_TO_BE_CONFIGURED/mscoco_train.record-?????-of-00100"
  }
  label_map_path: "PATH_TO_BE_CONFIGURED/mscoco_label_map.pbtxt"
}

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

eval_input_reader: {
  tf_record_input_reader {
    input_path: "PATH_TO_BE_CONFIGURED/mscoco_val.record-?????-of-00010"
  }
  label_map_path: "PATH_TO_BE_CONFIGURED/mscoco_label_map.pbtxt"
  shuffle: false
  num_readers: 1
}

注意把from_detection_checkpoint: true打开

3.2训练模型

这里是使用legacy/train.py来训练,下面是代码里的注释:

r"""Training executable for detection models.

This executable is used to train DetectionModels. There are two ways of
configuring the training job:

1) A single pipeline_pb2.TrainEvalPipelineConfig configuration file
can be specified by --pipeline_config_path.

Example usage:
    ./train \
        --logtostderr \
        --train_dir=path/to/train_dir \
        --pipeline_config_path=pipeline_config.pbtxt

2) Three configuration files can be provided: a model_pb2.DetectionModel
configuration file to define what type of DetectionModel is being trained, an
input_reader_pb2.InputReader file to specify what training data will be used and
a train_pb2.TrainConfig file to configure training parameters.

Example usage:
    ./train \
        --logtostderr \
        --train_dir=path/to/train_dir \
        --model_config_path=model_config.pbtxt \
        --train_config_path=train_config.pbtxt \
        --input_config_path=train_input_config.pbtxt
"""
python object_detection/legacy/train.py --logtostderr --train_dir=object_detection/ssd_mobilenet_v1_coco_2018_01_28/training --model_dir=object_detection/ssd_mobilenet_v1_coco_2018_01_28 --pipeline_config_path=object_detection/ssd_mobilenet_v1_coco_2018_01_28/ssd_mobilenet_v1_coco.config

--train_dir是存放这次训练出来的网络的

--model_dir是模型存放预训练模型的

--pipelin_config_path是要用的config文件路径,就是我们上边改的那个配置文件

训练过程中如果遇到OOM(out of memory)问题,多半是因为显存不够,修改config里的batch_size应该能够解决,实在不行就换个显卡吧

通过nvidia-smi可以监控显卡运行状态:

https://blog.csdn.net/qq_24878901/article/details/81660309

https://blog.csdn.net/ytusdc/article/details/85229771

训练过程可以使用tensorboard监控,但是我使用的时候网页打不开,可能是docker的端口设置的不对,之前用jupyter时也出现过类似的问题

tensorboard --logdir=/train_dir=object_detection/ssd_mobilenet_v1_coco_2018_01_28/training

把训练模型转换为pb文件

python object_detection/export_inference_graph.py --input_type image_tensor --pipeline_config_path object_detection/ssd_mobilenet_v1_coco_2018_01_28/ssd_mobilenet_v1_coco.config --trained_checkpoint_prefix object_detection/ssd_mobilenet_v1_coco_2018_01_28/training/model.ckpt-200000 --output_directory object_detection/ssd_mobilenet_v1_coco_2018_01_28/trained_model

这里 --trained_checkpoint_prefix 这个参数要在checkpoint文件里找到一个checkpoint

完成之后trained_model文件夹下会生成如下文件:

Tensorflow1.9训练ssd-mobilenet

pb文件在saved_model里

4.模型测试

使用以下测试代码测试时提示OOM错误

import cv2
import numpy as np
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
 
 
class TOD(object):
    def __init__(self):
        self.PATH_TO_CKPT = '/home/lyf/models/research/object_detection/ssd_model/model/frozen_inference_graph.pb'
        self.PATH_TO_LABELS = '/home/lyf/models/research/object_detection/ssd_model/pascal_label_map.pbtxt'
        self.NUM_CLASSES = 1
        self.detection_graph = self._load_model()
        self.category_index = self._load_label_map()
 
    def _load_model(self):
        detection_graph = tf.Graph()
        with detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')
        return detection_graph
 
    def _load_label_map(self):
        label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
        categories = label_map_util.convert_label_map_to_categories(label_map,
                                                                    max_num_classes=self.NUM_CLASSES,
                                                                    use_display_name=True)
        category_index = label_map_util.create_category_index(categories)
        return category_index
 
    def detect(self, image):
        with self.detection_graph.as_default():
            with tf.Session(graph=self.detection_graph) as sess:
                # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
                image_np_expanded = np.expand_dims(image, axis=0)
                image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
                boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
                scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
                classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
                num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
                # Actual detection.
                (boxes, scores, classes, num_detections) = sess.run(
                    [boxes, scores, classes, num_detections],
                    feed_dict={image_tensor: image_np_expanded})
                # Visualization of the results of a detection.
                vis_util.visualize_boxes_and_labels_on_image_array(
                    image,
                    np.squeeze(boxes),
                    np.squeeze(classes).astype(np.int32),
                    np.squeeze(scores),
                    self.category_index,
                    use_normalized_coordinates=True,
                    line_thickness=8)
 
        cv2.namedWindow("detection", cv2.WINDOW_NORMAL)
        cv2.imshow("detection", image)
        cv2.waitKey(0)
 
if __name__ == '__main__':
    image = cv2.imread('/home/lyf/test/000084.jpg')
    detecotr = TOD()
    detecotr.detect(image)

无奈使用object_detection API进行测试

用jupyter-notebook时,由于我是用的docker,所以要在/object_detection文件夹下打开jupyter,要不然看不到object_detection_tutorial.ipynb

还需要对object_detection_tutorial.ipynb进行一些修改

这里是模型的路径以及自己设置的标签的路径,一定要仔细核对

# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
#MODEL_FILE = MODEL_NAME + '.tar.gz'
#DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/trained_model/frozen_inference_graph.pb'
#这里一定要选择frozen这个,saved_model里那个.pb不行,我也不知道有啥区别

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('ssd_mobilenet_v1_coco_2018_01_28', 'my_label_map.pbtxt') 

donwload部分都注释掉

#opener = urllib.request.URLopener()
#opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
#ar_file = tarfile.open(MODEL_FILE)
#for file in tar_file.getmembers():
#  file_name = os.path.basename(file.name)
#  if 'frozen_inference_graph.pb' in file_name:
#    tar_file.extract(file, os.getcwd())

 自己的测试集

# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'ssd_mobilenet_v1_coco_2018_01_28/images/test'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, '00076.jpg')]#.format(i)) for i in range(73, 83) 

# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)

 然后就一路运行就可以看到结果了

5.模型转换为tflite

因为是在嵌入式设备上运行,把模型转换为tflite

detection API里有现成的转换工具

python export_tflite_ssd_graph.py --pipeline_config_path=ssd_mobilenet_v1_coco_2018_01_28/ssd_mobilenet_v1_coco.config --trained_checkpoint_prefix=ssd_mobilenet_v1_coco_2018_01_28/trained_model/model.ckpt --output_directory=ssd_mobilenet_v1_coco_2018_01_28/tflite_model --add_postprocessing_op=false

这个脚本会生成以下文件:

Tensorflow1.9训练ssd-mobilenet

那个pb文件就是我们熟悉的22.4Mb的网络模型了,但是我们最终想要的是.tflite文件,查看了一些博客,需要安装bazel编译工具,还要编译tensorflow源码,知难而退,看看有没有什么简单的办法,又参考了一片博客:https://blog.csdn.net/HK_Joe/article/details/102730752

import tensorflow as tf
 
in_path=r'D:\tmp_mobilenet_v1_100_224_classification_3\output_graph.pb'
out_path=r'D:\tmp_mobilenet_v1_100_224_classification_3\output_graph.tflite'
 
input_tensor_name=['Placeholder']
input_tensor_shape={'Placeholder':[1,224,224,3]}
 
class_tensor_name=['final_result']
 
 
convertr=tf.lite.TFLiteConverter.from_frozen_graph(in_path,input_arrays=input_tensor_name
                                                   ,output_arrays=class_tensor_name
                                                   ,input_shapes=input_tensor_shape)
 
# convertr=tf.lite.TFLiteConverter.from_saved_model(saved_model_dir=in_path,input_arrays=[input_tensor_name],output_arrays=[class_tensor_name])
tflite_model=convertr.convert()
 
 
with open(out_path,'wb') as f:
    f.write(tflite_model)

结果提示

AttributeError: module 'tensorflow' has no attribute 'lite'

看来是tensorflow版本不对,查找到另外篇博客

https://blog.csdn.net/tiaojingtao1293/article/details/104380284?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control

https://zhuanlan.zhihu.com/p/138738210

先不转格式了,这都是小问题了

参考链接:

https://blog.csdn.net/qq_38593211/article/details/82823255?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

https://blog.csdn.net/csdn_6105/article/details/82933628?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

https://blog.csdn.net/qq_17854471/article/details/89786400?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.control

https://blog.csdn.net/qq_37643960/article/details/98069548

上一篇:目标检测——SSD损失值计算


下一篇:阿里云ECS云服务器租用价格表(2021年最新版)