TensorFlow Object Detection API使用

谷歌开源的目标检测模型,选了个内存占用小的ssd_mobilenet_v1_coco_2017_11_17模型,网络下载链接:

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

程序:


import os

import numpy as np

import tensorflow as tf

from PIL import Image

from matplotlib import pyplot as plt

import ops as utils_ops

import label_map_util

import visualization_utils as vis_util

# Path to frozen detection graph. This is the actual model that is used for the object detection.

PATH_TO_CKPT = 'frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.

PATH_TO_LABELS = 'pascal_label_map.pbtxt'

NUM_CLASSES = 20

'''

if tf.__version__ < '1.4.0':

    raise ImportError(

        'Please upgrade your tensorflow installation to v1.4.* or later!')

'''

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)

# 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 = 'image\\'

TEST_IMAGE_PATHS = [os.path.join(

    PATH_TO_TEST_IMAGES_DIR, image) for image in os.listdir(PATH_TO_TEST_IMAGES_DIR)]

# Size, in inches, of the output images.

IMAGE_SIZE = (12, 8)

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

                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: np.expand_dims(image, 0)})

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

            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, 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://pan.baidu.com/s/1VTaMnAYrDY8rNrie_dsLQg

d1420180908_172237.gif

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,884评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,347评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,435评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,509评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,611评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,837评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,987评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,730评论 0 267
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,194评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,525评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,664评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,334评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,944评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,764评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,997评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,389评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,554评论 2 349

推荐阅读更多精彩内容