天天看點

tensorflow Object Detection API 配置

nstallation

官方文檔:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md

需要依賴的庫:

Protobuf 2.6

Pillow 1.0

Lxml

Tf slim(已經包含在tenslorflow/models/research/下)

Jupyter notebook

Matplotlib

Tensorflow

1.下載下傳models(電腦提前安裝好github,并且将安裝路徑下的 bin和git-core添加到環境變量path下 ;我的是C:\Users\18036\AppData\Local\GitHubDesktop\app-1.0.11\resources\app\git\mingw64\libexec\git-core;C:\Users\18036\AppData\Local\GitHubDesktop\app-1.0.11\resources\app\git\mingw64\bin)

git clone http://github.com/tensorflow/models

tensorflow Object Detection API 配置

2.protobuf編譯、

The tensorflow Object Detection API 使用Protobufs 來配置模型(model)和訓練變量(parameters)。在這個架構能夠被使用之前,這個 Protobuf的庫必須被編譯。

首先在https://github.com/google/protobuf/releases下下載下傳protoc-3.5.1-win32.zip,解壓後把bin,incude中的檔案複制到在環境變量下的檔案夾下,我是放在C:\Users\18036\Desktop\digital image\pro目錄下,在系統環境path中加入C:\Users\18036\Desktop\digital image\pro路徑。

然後在C:\Users\18036\Desktop\digital image\models-master\research位址下:

protoc.exe object_detection/protos/*.proto –python_out=.

3.将庫檔案添加到PYTHONPATH路徑下

當在本機運作時,tensorflow/models/research/和slim的目錄應該被粘貼到PYTHONPATH路徑下。這個在tensorflow/models/research/路徑下運作如下指令:

Export PYTHONPATH=$PYTHONPATH:

pwd

:

pwd

/slim

Note:這個指令需要在每次開始終端的時候運作。

為避免每次都輸入,可以直接将research和slim路徑加到環境變量PYTHONPATH中

4.測試安裝

python object_detection/builders/model_builder_test

出現以下的圖檔則成功

tensorflow Object Detection API 配置

以下為快速測試,在object_detection/builders/model/下cmd

輸入jupter-notebook,則會在浏覽器自動打開網頁,選擇object_detection_tutorial.ipynb檔案打開,選擇上方的cell–run all。這是官方的步驟,但是我并沒有成功。官方的文檔要求的tensorflow 1.4版本以上,不過windows沒有1.4以上的?原因等熟悉熟悉在找。

我隻能在網上找以前發的版本,在spyder中打開object_detection_tutorial.py,代碼如下,

# -*- coding: utf-8 -*-
"""
Created on Sun Dec 31 20:11:13 2017

@author: 18036
"""

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

#download model
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.    
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='')
#Loading label map    
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)
#Helper code
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, )).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(, ) ]

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

with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    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=)
      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.
      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.
      scores = detection_graph.get_tensor_by_name('detection_scores:0')
      classes = detection_graph.get_tensor_by_name('detection_classes:0')
      num_detections = 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,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=)
      plt.figure(figsize=IMAGE_SIZE)
      plt.imshow(image_np)
           

我的電腦組態可能不行,運作了30s左右可以出現object detection/test_images下的兩幅圖檔的檢測

tensorflow Object Detection API 配置

換成自己的圖檔可以更改PATH_TO_TEST_IMAGES_DIR = ‘test_images’的路徑,相應的 range(1, 3) 也要更改。

繼續閱讀