Tensorflow 的 Object Detection API 配置

首先说明下自己的环境:

Ubuntu18
显卡 RTX2080Ti
Tensorflow 1.13.1
CUDA 10.0
CUDNN 7.4 

因为自己的显卡是RTX2080Ti,所以我的 Tensorflow 1.13.1 、CUDA 和 CUDNN 必须是当前的版本或者更高版本。具体对应关系参考另一篇文章:https://blog.csdn.net/ytusdc/article/details/89882400

安装前更新系统软件包,和安装各种依赖库,这没的说,然后配置好CUDA和CUDNN

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y build-essential cmake git pkg-config
sudo apt-get install -y libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler
sudo apt-get install -y libatlas-base-dev
sudo apt-get install -y --no-install-recommends libboost-all-dev
sudo apt-get install -y libgflags-dev libgoogle-glog-dev liblmdb-dev
sudo apt-get install -y python-pip
sudo apt-get install -y python-dev
sudo apt-get install -y python-numpy python-scipy
sudo apt-get install -y libopencv-dev
sudo apt-get install build-essential
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff5-dev libdc1394-22-dev         # 处理图像所需的包
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev liblapacke-dev
sudo apt-get install libxvidcore-dev libx264-dev         # 处理视频所需的包
sudo apt-get install libatlas-base-dev gfortran          # 优化opencv功能
sudo apt-get install ffmpeg

一、安装制定版本的Tensorflow

TensorFlow 官方参考:http://www.tensorfly.cn/tfdoc/get_started/os_setup.html

pip install tensorflow-gpu=1.13.1

直接安装可能会很慢,或者使用国内清华提供了一个镜像网站https://pypi.tuna.tsinghua.edu.cn,下载文件会更快 

python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow-gpu==1.13.1

注意:此处必须制定1.13.1 可能这个是最新版本吧,其他版本例如1.12版本的 tensorflow-gpu=1.12 就可以安装。

Tensorflow 安装版本及路径查看

import tensorflow as tf
tf.__version__ #两个下划线
tf.__path__

测试Tensorflow,出现下图说明安装成功.

cd models/tutorials/image/mnist
python convolutional.py

 

二、object detection API 配置

TensorFlow Object Detection API安装官方参考:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md

1、下载TensorFlow object detection API

 去  https://github.com/tensorflow/models 上下载整个models到本地目录(避免中文),解压。

安装依赖库:

Protobuf 3.0.0
Python-tk
Pillow 1.0
lxml
tf Slim (已经包含在了"models/research/"中)
Jupyter notebook
Matplotlib
Tensorflow (>=1.9.0)
Cython
contextlib2
cocoapi

COCO API安装

git clone https://github.com/cocodataset/cocoapi.git
cd cocoapi/PythonAPI
make
cp -r pycocotools */tensorflow/models/research/     #将编译好的pycocotools文件夹复制到tensorflow/models/research/

2、protobuf安装与配置

 (a)首先看看电脑是否安装了protobuf,可在终端试下:表明已经安装成功了,一般来说前面的依赖库已经安装了

$ protoc --version
libprotoc 3.0.0 #输出

因为我protobuf已经安装成功了,所以没有用编译的方法进行安装,如果需要编译安装可以看一下参考的文章,在此就不写了。

验证是否安装成功

#protoc --version
版本号
#python 
>>>import google.protobuf

没有报错,说明安装成功

(b)下面进行protobuf的配置,终端进入models\research\目录,输入:

cd tensorflow/models/research 
research $ protoc object_detection/protos/*.proto --python_out=.

会将protos下所有的proto文件转换为一个对应的Python文件。

(c)将库加到环境变量PYTHONPATH

两种方法:

方法一:

将 tensorflow/models/research/ tensorflow/models/research/slim添加到PYTHONPATH变量中。

sudo vi ~/.bashrc

在文件末尾添加

export PYTHONPATH=$PYTHONPATH:*/tensorflow/models/research/:*/tensorflow/models/research/slim

以上只是示例,请根据实际情况将指tensorflow/models/research/和tensorflow/models/research/slim目录添加到PYTHONPATH。source ~/.bashrc生效。

方法二:

tensorflow/models/research/ 和 slim 目录 需要添加到PYTHONPATH环境变量中. 从终端中,切换到tensorflow/models/research/目录,执行:

# From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim

注意: 这条命令在新打开的终端中需要重新执行一次才会在新终端中生效,如果不想那么麻烦,就在 ~/.bashrc或者~/.zshrc (具体 看用的是bash还是zsh)文件上把上面的语句添加到末尾,注意把pwd改成绝对路径。

3、测试 Tensorflow Object Detection API

在 */models/research/下执行下面的命令,如下图得到OK,说明安装成功

python object_detection/builders/model_builder_test.py

(4)接下来,跑一个demo,你可以在research 路径下运行jupyter notebook,然后打         开/object_detection/object_detection_tutorial.ipynb

注意下面图片中的模块从网络中下载预训练模型文件,若执行的时候速度很慢,可以单独去下载这个下载地址,

代码中用到的是下面的模型,“ssd_mobilenet_v1_coco_11_06_2017”,下载地址如下

http://download.tensorflow.org/models/object_detection/ssd_inception_v2_coco_2017_11_17.tar.gz

压缩包里面包括以下文件:

  • 放置权重数据的检查点文件(ckpt)
  • 可用于变量载入内存的图frozen文件。该文件与检查点文件可以实现"开箱即用"的使用理念,即不需要再一次引入网络模型源码。

然后解压到相应目录,确保存在object_detection/ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb 文件(注意:这只是为了保证当前代码的可运行),然后屏蔽到代码中下载指令,如图所示,把Download Model代码块设置MarkDown或直接注释掉也可以。

当然你可以自己训练模型,也可以下载更多的预训练模型,这个可以到TensoFlow下载,下载地址是:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

如下图所示:

 

(5)接下就一步步执行里面的代码,看看最后的结果是否能检测出图片中的object,如下图

object_detection_tutorial.ipynb 文件在jupyter notebook 转换成py文件,稍微修改把下载代码的部分注释掉就可以了,就可以直接运行。把py文件放在object_detection目录下,运行,代码如下:

#!/usr/bin/env python
# coding: utf-8

# # Object Detection Demo

# # Imports

# In[1]:

#import matplotlib
#matplotlib.use('TkAgg')
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 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 StrictVersion(tf.__version__) < StrictVersion('1.12.0'):
#  raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')


# ## Env setup

# In[2]:


# This is needed to display the images.
#get_ipython().magic(u'matplotlib inline')


# ## Object detection imports
# Here are the imports from the object detection module.

# In[4]:


from utils import label_map_util

from utils import visualization_utils as vis_util


# # Model preparation 

# ## Variables
# 
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_FROZEN_GRAPH` to point to a new .pb file.  
# 
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# In[5]:


# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
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 + '/frozen_inference_graph.pb'

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


# ## Download Model

# In[9]:

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

'''
# ## Load a (frozen) Tensorflow model into memory.

# In[10]:


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='')


# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

# In[11]:


category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)


# ## Helper code

# In[12]:


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)


# # Detection

# In[13]:


# 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 = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]

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


# In[14]:


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[1], image.shape[2])
        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: image})

      # 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.int64)
      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



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_expanded, 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.imshow(image_np)
  plt.show()

 

参考文章:https://www.cnblogs.com/zongfa/p/9662832.html

              https://blog.csdn.net/Arvin_liang/article/details/84581537#TensorFlow_4

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值