|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding: utf-8 |
| 3 | + |
| 4 | +import os |
| 5 | +import glob |
| 6 | +import time |
| 7 | +import numpy as np |
| 8 | +import os |
| 9 | +import six.moves.urllib as urllib |
| 10 | +import sys |
| 11 | +import tarfile |
| 12 | +import tensorflow as tf |
| 13 | +import zipfile |
| 14 | + |
| 15 | +from collections import defaultdict |
| 16 | +from io import StringIO |
| 17 | +from PIL import Image |
| 18 | +from object_detection.utils import ops as utils_ops |
| 19 | + |
| 20 | + |
| 21 | +if __name__ == "__main__": |
| 22 | + import argparse |
| 23 | + |
| 24 | + # python argparse_test.py 5 -v --color RED |
| 25 | + parser = argparse.ArgumentParser( |
| 26 | + description="TensorFlow Inference speed benchmark for object detection model." |
| 27 | + ) |
| 28 | + # parser.add_argument("-v", "--verbose", help="increase output verbosity", |
| 29 | + # action="store_true") |
| 30 | + parser.add_argument( |
| 31 | + "--model", |
| 32 | + help="Path to the frozen graph .pb file.", |
| 33 | + type=str, |
| 34 | + default="./models/frozen_inference_graph.pb", |
| 35 | + ) |
| 36 | + |
| 37 | + parser.add_argument( |
| 38 | + "--cpu", help="Force to use CPU during inference.", action="store_true" |
| 39 | + ) |
| 40 | + parser.add_argument("--img", help="Path to a sample image to inference.", type=str) |
| 41 | + args = parser.parse_args() |
| 42 | + |
| 43 | + # Path to frozen detection graph. This is the actual model that is used for the object detection. |
| 44 | + PATH_TO_CKPT = args.model |
| 45 | + |
| 46 | + image_path = args.img |
| 47 | + |
| 48 | + assert os.path.isfile(PATH_TO_CKPT) |
| 49 | + assert os.path.isfile(image_path) |
| 50 | + |
| 51 | + detection_graph = tf.Graph() |
| 52 | + with detection_graph.as_default(): |
| 53 | + od_graph_def = tf.GraphDef() |
| 54 | + with tf.gfile.GFile(PATH_TO_CKPT, "rb") as fid: |
| 55 | + serialized_graph = fid.read() |
| 56 | + od_graph_def.ParseFromString(serialized_graph) |
| 57 | + tf.import_graph_def(od_graph_def, name="") |
| 58 | + |
| 59 | + def load_image_into_numpy_array(image): |
| 60 | + (im_width, im_height) = image.size |
| 61 | + return ( |
| 62 | + np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8) |
| 63 | + ) |
| 64 | + |
| 65 | + def run_inference_benchmark(image, graph, trial=20, gpu=True): |
| 66 | + """Run TensorFlow inference benchmark. |
| 67 | + |
| 68 | + Arguments: |
| 69 | + image {np.array} -- Input image as an Numpy array. |
| 70 | + graph {tf.Graph} -- TensorFlow graph object. |
| 71 | + |
| 72 | + Keyword Arguments: |
| 73 | + trial {int} -- Number of inference to run for averaging. (default: {20}) |
| 74 | + gpu {bool} -- Use Nvidia GPU when available. (default: {True}) |
| 75 | + |
| 76 | + Returns: |
| 77 | + int -- Frame per seconds benchmark result. |
| 78 | + """ |
| 79 | + |
| 80 | + with graph.as_default(): |
| 81 | + if gpu: |
| 82 | + config = tf.ConfigProto() |
| 83 | + else: |
| 84 | + config = tf.ConfigProto(device_count={"GPU": 0}) |
| 85 | + with tf.Session(config=config) as sess: |
| 86 | + # Get handles to input and output tensors |
| 87 | + ops = tf.get_default_graph().get_operations() |
| 88 | + all_tensor_names = {output.name for op in ops for output in op.outputs} |
| 89 | + tensor_dict = {} |
| 90 | + for key in [ |
| 91 | + "num_detections", |
| 92 | + "detection_boxes", |
| 93 | + "detection_scores", |
| 94 | + "detection_classes", |
| 95 | + "detection_masks", |
| 96 | + ]: |
| 97 | + tensor_name = key + ":0" |
| 98 | + if tensor_name in all_tensor_names: |
| 99 | + tensor_dict[key] = tf.get_default_graph().get_tensor_by_name( |
| 100 | + tensor_name |
| 101 | + ) |
| 102 | + if "detection_masks" in tensor_dict: |
| 103 | + # The following processing is only for single image |
| 104 | + detection_boxes = tf.squeeze(tensor_dict["detection_boxes"], [0]) |
| 105 | + detection_masks = tf.squeeze(tensor_dict["detection_masks"], [0]) |
| 106 | + # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size. |
| 107 | + real_num_detection = tf.cast( |
| 108 | + tensor_dict["num_detections"][0], tf.int32 |
| 109 | + ) |
| 110 | + detection_boxes = tf.slice( |
| 111 | + detection_boxes, [0, 0], [real_num_detection, -1] |
| 112 | + ) |
| 113 | + detection_masks = tf.slice( |
| 114 | + detection_masks, [0, 0, 0], [real_num_detection, -1, -1] |
| 115 | + ) |
| 116 | + detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( |
| 117 | + detection_masks, detection_boxes, image.shape[0], image.shape[1] |
| 118 | + ) |
| 119 | + detection_masks_reframed = tf.cast( |
| 120 | + tf.greater(detection_masks_reframed, 0.5), tf.uint8 |
| 121 | + ) |
| 122 | + # Follow the convention by adding back the batch dimension |
| 123 | + tensor_dict["detection_masks"] = tf.expand_dims( |
| 124 | + detection_masks_reframed, 0 |
| 125 | + ) |
| 126 | + image_tensor = tf.get_default_graph().get_tensor_by_name( |
| 127 | + "image_tensor:0" |
| 128 | + ) |
| 129 | + |
| 130 | + # Run inference |
| 131 | + times = [] |
| 132 | + # Kick start the first inference which takes longer and followings. |
| 133 | + output_dict = sess.run( |
| 134 | + tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)} |
| 135 | + ) |
| 136 | + for i in range(trial): |
| 137 | + start_time = time.time() |
| 138 | + output_dict = sess.run( |
| 139 | + tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)} |
| 140 | + ) |
| 141 | + delta = time.time() - start_time |
| 142 | + times.append(delta) |
| 143 | + mean_delta = np.array(times).mean() |
| 144 | + fps = 1 / mean_delta |
| 145 | + print("average(sec):{:.3f},fps:{:.2f}".format(mean_delta, fps)) |
| 146 | + |
| 147 | + return fps |
| 148 | + |
| 149 | + image = Image.open(image_path) |
| 150 | + # the array based representation of the image will be used later in order to prepare the |
| 151 | + # result image with boxes and labels on it. |
| 152 | + image_np = load_image_into_numpy_array(image) |
| 153 | + # Expand dimensions since the model expects images to have shape: [1, None, None, 3] |
| 154 | + image_np_expanded = np.expand_dims(image_np, axis=0) |
| 155 | + # Actual detection benchmark. |
| 156 | + fps = run_inference_benchmark(image_np, detection_graph, trial=20, gpu=not args.cpu) |
0 commit comments