window搭建TensorFlow Object Detection目标检测框架(超简单)

window搭建TensorFlow Object Detection目标检测框架(超简单)

这个框架十分方面,熟练掌握之后可以训练出很多目标检测的模型,简单易上手,这个教程会讲到车牌检测、行人检测、人脸口罩检测等模型。训练过程十分简单,适合刚入门时用来找信心。

环境:win10,pycharm,anaconda3,tensorflow

  1. 下载Object Detection项目(tensorflow/models)
    模型地址:https://github.com/tensorflow/models
    下载地址:https://codeload.github.com/tensorflow/models/zip/master
    解压后放在项目目录下

  2. 利用anaconda3创建虚拟环境
    (1) 环境名称:tensorflowAPI,python版本:3.6

    conda create -n tensorflowAPI python=3.6

    (2) 激活进入到tensorflowAPI,通过pip install安装
    protobuf(3.4)、Cython、pillow(1.0)、lxml、tensorflow(1.9)

    例如:pip install protobuf==3.4
  3. protobuf安装与配置
    (1) 下载protobuf-3.4.0-win32.zip
    下载地址:http://down-ww3.7down.net/pcdown/soft/P/protoc-3.4.0-win32.rar
    解压出来的文件放在软件目录或其他固定的目录下

    (2) 把protobuf的bin目录的路径加入系统环境变量path

    (3) 通过protoc编译项目文件
    在命令行(cmd)下进入到下模型目录下的research

    protoc object_detection/protos/*.proto --python_out=.

    (4) 添加系统环境变量:PYTHONPATH
    把research的路径和research/bin路径添加进去

    (5) 在命令行(cmd)下进入到下模型目录下的research,输入:

    python setup.py install

    (6) 在命令行(cmd)下进入到下模型目录下的research/slim,tf slim 库的 安装)输入:

    python setup.py install

为了防止路径报错,建议将object_detection文件夹复制到\Lib\site-packages路径下,遇到其他路径问题再手动修改,或者将object_detection路径加入到对应的python环境中。

具体方式:略。。。。。。。。
(还是写一下吧,找到对应python环境。例如前面创建的python是tensorflowAPI ,那就找到anaconda的安装路径,envs文件夹,进入tensorflowAPI\Lib\site-packages,将前面的object_detection文件夹复制进去)

  1. 测试环境
python object_detection/builders/model_builder_test.py

在这里插入图片描述
出现上图,环境正常
我配置好的环境
下载地址:https://pan.baidu.com/s/10hjVHCNUeXVVL5XOfgkZuA
提取码:iyd6

			参考环境(python3.5)
			Package              Version
			-------------------- ------------------------------------
			absl-py              0.9.0
			astor                0.8.1
			atomicwrites         1.3.0
			attrs                19.3.0
			certifi              2018.8.24
			colorama             0.4.3
			cycler               0.10.0
			Cython               0.29.15
			gast                 0.3.3
			google-pasta         0.1.8
			grpcio               1.27.2
			h5py                 2.10.0
			importlib-metadata   1.5.0
			Keras-Applications   1.0.8
			Keras-Preprocessing  1.1.0
			kiwisolver           1.1.0
			lxml                 4.5.0
			Markdown             3.2.1
			matplotlib           2.1.0
			more-itertools       8.2.0
			numpy                1.18.1
			object-detection     0.1
			opencv-python        4.2.0.32
			packaging            20.1
			pathlib2             2.3.5
			Pillow               7.0.0
			pip                  20.0.2
			pluggy               0.13.1
			protobuf             3.6.1
			py                   1.8.1
			pyparsing            2.4.6
			pytest               5.3.5
			python-dateutil      2.8.1
			pytz                 2019.3
			setuptools           45.2.0
			six                  1.14.0
			slim                 0.1
			tensorboard          1.14.0
			tensorflow           1.14.0
			tensorflow-estimator 1.14.0
			termcolor            1.1.0
			wcwidth              0.1.8
			Werkzeug             1.0.0
			wheel                0.31.1
			wincertstore         0.2
			wrapt                1.11.2
			zipp                 1.1.0
  1. 预测
    方式一:pycharm(推荐)
    在research/object_detection文件夹下新建一个python文件,命名为object_detection_tutorial,拷贝下面的代码

下面的代码和注释我是转载的,找不到原创作者大大的链接了,找到了一定补上

# 导入一些需要的包和设置环境
import numpy as np
import tensorflow as tf
import os
import tarfile
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util

# 模型准备,设置需要使用的模型的下载地址
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# frozen_inference_graph.pb文件就是后面需要导入的文件,它保存了网络的结构和数据
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# mscoco_label_map.pbtxt文件中保存了index到类别名的映射,该文件就在object_dection/data文件夹下
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
# 下载预训练模型
opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# 解压该文件
tar_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())  # 将pb文件提取到当前工作目录下
# 下载模型后,将它读取到默认的计算图中(实际读取的是frozen_inference_graph.pb文件)
# 新建一个图
detection_graph = tf.Graph()  # 定义一个图
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()  # 重新定义一个图
    # tf.gfile.GFile(filename, mode)获取文本操作句柄,类似于python提供的文本操作open()函数,
    # filename是要打开的文件名,mode是以何种方式去读写,将会返回一个文本操作句柄。
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
        # 将*.pb文件读入serialized_graph
        serialized_graph = fid.read()
        # 将serialized_graph的内容恢复到图中
        od_graph_def.ParseFromString(serialized_graph)
        # 将od_graph_def导入当前默认图中(加载模型)
        tf.import_graph_def(od_graph_def, name='')

# 载入coco数据集标签文件
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
# print(category_index)

# 在进行检测之前,定义一个帮助函数,该函数的功能是将图片转换为Numpy数组的形式
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 = 'test_images'
TEST_IMAGE_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)]
# 输出图像的大小(单位是in)
IMAGE_SIZE = (12, 8)
with tf.Session(graph=detection_graph) as sess:
    for image_path in TEST_IMAGE_PATHS:
        image = Image.open(image_path)
        # 将图片转换为numpy格式
        image_np = load_image_into_numpy_array(image)
        # 将图片扩展一维,最后进入神经网络的图片格式应该是[1,?,?,3],括号内参数分别为一个batch传入的数量,宽,高,通道数
        image_np_expanded = np.expand_dims(image_np, axis=0)
        # 获取模型中的tensor
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        # boxes变量存放了所有检测框
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        # score表示每个检测结果的confidence
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        # classes表示每个框对应的类别
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        # num_detections表示检测框的个数
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        # 开始检测
        boxes, scores, classes, num_detections = sess.run([boxes, scores, classes, num_detections],
                                                          feed_dict={image_tensor: image_np_expanded})
        # 可视化结果
        # squeeze函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉
        vis_util.visualize_boxes_and_labels_on_image_array(
            image_np,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8)
        plt.figure(figsize=IMAGE_SIZE)
        plt.imshow(image_np)
        plt.show()

如果使用opencv读取图片的话,记得把图片转换成RGB格式,cv2默认读取的是BGR格式,虽然说官方给的模型影响不大,但是自己训练一些比较复杂的模型,再用这个代码预测的时候,不注意图片读取格式会严重影响预测结果
代码第一次运行的时候会下载模型,在第21行的代码有相关注释,如果下载好了,第二次运行记得注释掉下载代码。如果下载太慢,下面是地址

http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb

(如有报错,注意导入py文件的路径)
方式二:jupyter
(略,csdn上有太多使用jupyter预测的教程,我就不写了)

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值