前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ubunu16.04 TensorFlow object detection API 应用配置

ubunu16.04 TensorFlow object detection API 应用配置

作者头像
用户1148525
发布2019-05-26 11:49:08
5080
发布2019-05-26 11:49:08
举报
文章被收录于专栏:机器学习、深度学习

TensorFlow object detection API应用–配置 主要参考 : https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md https://www.cnblogs.com/zongfa/p/9662832.html

1) 首先下载 TensorFlow object detection API 官网下载地址 https://github.com/tensorflow/models

代码语言:javascript
复制
git clone --recurse-submodules https://github.com/tensorflow/models

官网下载太慢了 https://download.csdn.net/download/qq_36661831/10489285 下载完后解压,放在哪里是一个问题,推荐地址: /home/zhangjun/miniconda3/envs/tensorflow 下面。我一开始在 /home/zhangjun/ 目录下建立了一个文件夹 Tensorflow ,放在这个文件夹下面了

  1. Tensorflow Object Detection API 以来以下库文件 Tensorflow Object Detection API depends on the following libraries: Protobuf 3.0.0 Python-tk Pillow 1.0 lxml tf Slim (which is included in the “tensorflow/models/research/” checkout) Jupyter notebook Matplotlib Tensorflow (>=1.9.0) Cython contextlib2 cocoapi

The remaining libraries can be installed on Ubuntu 16.04 using via apt-get:

代码语言:javascript
复制
sudo apt-get install protobuf-compiler python-pil python-lxml python-tk
pip install --user Cython
pip install --user contextlib2
pip install --user jupyter
pip install --user matplotlib

3)手动安装 protobuf, protobuf 3.6 可能有问题,我后来又用了 protobuf3.0.0 If you are on linux:

Download and install the 3.0 release of protoc, then unzip the file.

代码语言:javascript
复制
# From tensorflow/models/research/
wget -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.0.0/protoc-3.0.0-linux-x86_64.zip
unzip protobuf.zip

Run the compilation process again, but use the downloaded version of protoc

代码语言:javascript
复制
# From tensorflow/models/research/
./bin/protoc object_detection/protos/*.proto --python_out=.
  1. Add Libraries to PYTHONPATH From tensorflow/models/research/
代码语言:javascript
复制
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim

5) python object_detection/builders/model_builder_test.py 报错 ubuntu16.04 ‘No module named ‘object_detection’’ https://blog.csdn.net/weixin_41683218/article/details/81214785

/home/zhangjun/miniconda3/envs/tensorflow/lib/python3.6/site-packages 建立文件 tensorflow_model.pth 文件内容如下: /home/zhangjun/Tensorflow/models/research /home/zhangjun/Tensorflow/models/research/slim

再运行 python object_detection/builders/model_builder_test.py 没有问题了

代码语言:javascript
复制
Ran 7 tests in 0.024s

OK

6)接下来,跑一个demo,你可以在这个路径下运行jupyter notebook 报错: jupyter: command not found 路径问题 ~/.local/bin/jupyter-notebook

找不到 /object_detection/object_detection_tutorial.ipynb

在 /home/zhangjun/Tensorflow/models/research/object_detection 下面运行 ~/.local/bin/jupyter-notebook 就可以看到了 /object_detection/object_detection_tutorial.ipynb

https://blog.csdn.net/darkeyers/article/details/80245119

最后将 object_detection_tutorial.ipynb 里面的内容转为 python 程序 ssd_test.py, 直接运行: python ssd_test.py 即可

代码语言:javascript
复制
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2

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

# This is needed to display the images.
#%matplotlib inline

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

from utils import label_map_util

from utils import visualization_utils as vis_util

# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
MODEL_FILE = MODEL_NAME + '.tar.gz'


# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 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')

NUM_CLASSES = 90

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, '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)



# 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, 4) ]

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

output_path = ('/home/zhangjun/Tensorflow/models-master/research/object_detection/test_images/result/')
 

with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    # Definite input and output Tensors for detection_graph
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
    # Each box represents a part of the image where a particular object was detected.
    detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
    detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')
    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.
      (boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_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,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)

      cv2.imwrite(output_path+image_path.split('/')[-1],image_np)
    #  plt.figure(figsize=IMAGE_SIZE)
    #  plt.imshow(image_np)
    #  plt.pause(5)

其中模型 ssd_mobilenet_v1_coco_11_06_2017 是一个文件夹,这个是直接从 https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md 上面下载后解压得到的一个文件夹,放在 models-master/research/object_detection 文件夹里面,

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年11月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档