Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JamesDBartlett3/ce9175299a11d08bf06b4c1267959cdf to your computer and use it in GitHub Desktop.
Save JamesDBartlett3/ce9175299a11d08bf06b4c1267959cdf to your computer and use it in GitHub Desktop.
TensorFlow vs. OpenVINO: Performance Benchmark.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "TensorFlow vs. OpenVINO: Performance Benchmark.ipynb",
"provenance": [],
"collapsed_sections": [
"JXOlOORNKgLQ",
"egYYP7sYK6em",
"V8-yl-s-WKMG",
"GwzUiO3zL49U",
"1UN_xgeVWexw",
"fV6oG3sTO4ZN",
"662rwWCoDQzV",
"fTICAE5UFEOl",
"Bp4CyJ__ELpB",
"p3UGXxUii5Ym",
"cfn_tRFOWKMO",
"H0_1AGhrWKMc",
"yTvKLSYPTIjX"
],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/JamesDBartlett/ce9175299a11d08bf06b4c1267959cdf/tensorflow-vs-openvino-performance-benchmark.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RbcjVmRcyATi",
"colab_type": "text"
},
"source": [
"# TODO: \n",
"\n",
"1. Replace OpenVINO's app.py with one that can handle TensorFlow object detection models\n",
"2. Write code to compare OpenVINO IR vs. original TensorFlow model: Accuracy \n",
"3. Write code to compare OpenVINO IR vs. original TensorFlow model: Performance"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JXOlOORNKgLQ",
"colab_type": "text"
},
"source": [
"# Sources / Credits"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "egYYP7sYK6em",
"colab_type": "text"
},
"source": [
"### OpenVINO OpenDevLibrary Demo\n",
"\n",
"<table align=\"left\"><td>\n",
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/alihussainia/OpenDevLibrary/blob/master/demo.ipynb\">\n",
" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab\n",
" </a>\n",
"</td><td>\n",
" <a target=\"_blank\" href=\"https://github.com/alihussainia/OpenDevLibrary/blob/master/demo.ipynb\">\n",
" <img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
"</td></table>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tp-98DBsN_Fz",
"colab_type": "text"
},
"source": [
"#### OpenDevLibrary\n",
"\n",
"> **Open Source OpenVINO Edge developement and deployment on Google Colab using Colab Notebooks**\n",
"\n",
"USAGE STEPS:\n",
"\n",
"1. Open the demo.ipynb file (available in this repository) and click on open in colab button.\n",
"2. Run all the cells and Congrats! You will deploy your first edge app on Google Colab.\n",
"\n",
"Project Members:\n",
"\n",
"* MUHAMMAD ALI\n",
" * SLACK USERNAME: Muhammad.Ali\n",
" * EMAIL: malirashid1994@gmail.com\n",
"\n",
"* ABHIK BANERJEE\n",
" * SLACK USERNAME: Abhik Banerjee"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "V8-yl-s-WKMG"
},
"source": [
"### TensorFlow Object Detection API Demo\n",
"\n",
"<table align=\"left\"><td>\n",
" <a target=\"_blank\" href=\"https://colab.sandbox.google.com/github/tensorflow/models/blob/master/research/object_detection/colab_tutorials/colab_tutorials/object_detection_tutorial.ipynb\">\n",
" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab\n",
" </a>\n",
"</td><td>\n",
" <a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/research/object_detection/colab_tutorials/colab_tutorials/object_detection_tutorial.ipynb\">\n",
" <img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
"</td></table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "3cIrseUv6WKz"
},
"source": [
"Welcome to the [Object Detection API](https://github.com/tensorflow/models/tree/master/research/object_detection). This notebook will walk you step by step through the process of using a pre-trained model to detect objects in an image."
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "VrJaG0cYN9yh"
},
"source": [
"> **Important**: This tutorial is to help you through the first step towards using [Object Detection API](https://github.com/tensorflow/models/tree/master/research/object_detection) to build models. If you just just need an off the shelf model that does the job, see the [TFHub object detection example](https://colab.sandbox.google.com/github/tensorflow/hub/blob/master/examples/colab/object_detection.ipynb)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GwzUiO3zL49U",
"colab_type": "text"
},
"source": [
"# Google Drive (Persistent Data Storage)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PNGGuierpjzC",
"colab_type": "text"
},
"source": [
"You probably won't need this, but if you really want persistent storage, un-comment the lines below."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "YEDdjgikf1rT",
"colab": {}
},
"source": [
"# from google.colab import drive\n",
"# drive.mount('/content/drive')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "1UN_xgeVWexw",
"colab_type": "text"
},
"source": [
"# Global Setup"
]
},
{
"cell_type": "code",
"metadata": {
"id": "wXCyCm-rkMXh",
"colab_type": "code",
"colab": {}
},
"source": [
"%%bash\n",
"# Clean up any previous installations\n",
"rm -rf /content/OpenDevLibrary/\n",
"rm -rf /content/models/\n",
"rm -rf /content/l_openvino_toolkit_p*\n",
"\n",
"# Clone repos\n",
"git clone --depth 1 'https://github.com/tensorflow/models.git' /content/models/ > /dev/null 2>&1\n",
"git clone 'https://github.com/alihussainia/OpenDevLibrary.git' /content/OpenDevLibrary/ > /dev/null 2>&1"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "4vbnzddlqCpI",
"colab_type": "code",
"colab": {}
},
"source": [
"import os\n",
"import pathlib\n",
"\n",
"# Change these to match whatever model you're testing\n",
"model_name = 'ssd_mobilenet_v2_coco'\n",
"model_date = '_2018_03_29'\n",
"tf_api_support = 'ssd_v2_support'\n",
"\n",
"image_path ='/content/models/research/object_detection/test_images/'\n",
"TEST_IMAGE_PATHS = sorted(list(pathlib.Path(image_path).glob(\"*.jpg\")))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "TmlgsYhxEkTW"
},
"source": [
"# OpenVINO"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fV6oG3sTO4ZN",
"colab_type": "text"
},
"source": [
"## Installation"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "P1UL6ZJ1nOs5",
"colab": {}
},
"source": [
"# Install OpenVINO\n",
"!python /content/OpenDevLibrary/openvino_initialization_script.py > /dev/null 2>&1"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "YkwgKjE8tcdA",
"colab": {}
},
"source": [
"install_dir = '/opt/intel/openvino/'\n",
"deployment_tools = install_dir + 'deployment_tools/'\n",
"model_optimizer = deployment_tools + 'model_optimizer/'\n",
"model_zoo = deployment_tools + 'open_model_zoo/'"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "662rwWCoDQzV"
},
"source": [
"## Model"
]
},
{
"cell_type": "code",
"metadata": {
"id": "v_e_4RXob_qe",
"colab_type": "code",
"colab": {}
},
"source": [
"model_path = \"/content/OpenDevLibrary/demo_files/models/public/\" + model_name + \"/\" + model_name + model_date + \"/\"\n",
"IR_path = model_path + '../IR/'\n",
"demo_files = '/content/OpenDevLibrary/demo_files/'"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "dvcXlgVn6xCc",
"colab": {}
},
"source": [
"!python $model_zoo'tools/downloader/'downloader.py --name $model_name \\\n",
" -o /content/OpenDevLibrary/demo_files/models > /dev/null 2>&1\n",
"\n",
"!python $model_optimizer'mo_tf.py' \\\n",
" --input_model $model_path'frozen_inference_graph.pb' \\\n",
" --tensorflow_object_detection_api_pipeline_config $model_path'pipeline.config' \\\n",
" --reverse_input_channels --transformations_config \\\n",
" $deployment_tools'model_optimizer/extensions/front/tf/'$tf_api_support'.json' \\\n",
" -o $IR_path \\\n",
" > /dev/null 2>&1"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "VL_aFsi2VD2e",
"colab_type": "code",
"colab": {}
},
"source": [
"# Compare sizes of pre- and post-conversion models\n",
"o_size = !du -hs $model_path | cut -f1\n",
"c_size = !du -hs $IR_path | cut -f1\n",
"print('Original Model Size: ' + o_size[0])\n",
"print('Converted Model Size: ' + c_size[0])"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "fTICAE5UFEOl"
},
"source": [
"## Inference"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "vrLkzIKv3e4_",
"colab": {}
},
"source": [
"img = image_path + 'image1.jpg'\n",
"\n",
"!source /opt/intel/openvino/bin/setupvars.sh && \\\n",
" python $demo_files'app.py' \\\n",
" -m $IR_path'frozen_inference_graph.xml' \\\n",
" -i $img"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "Bp4CyJ__ELpB"
},
"source": [
"## Output"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "Cl17ioro_6E6",
"colab": {}
},
"source": [
"from google.colab.patches import cv2_imshow\n",
"import cv2\n",
"output_file = demo_files + 'outputs/image1-output.png'\n",
"\n",
"img = cv2.imread(output_file, cv2.IMREAD_UNCHANGED)\n",
"cv2_imshow(img)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "wsCVz3khQ0eT",
"colab_type": "text"
},
"source": [
"# TensorFlow"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "p3UGXxUii5Ym"
},
"source": [
"## Installation"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "hGL97-GXjSUw",
"colab": {}
},
"source": [
"%%bash\n",
"pip install -U --pre tensorflow==\"2.*\"\n",
"pip install tf_slim pycocotools"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "-vsOL3QR6kqs"
},
"source": [
"Get `tensorflow/models` or `cd` to parent directory of the repository."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "ykA0c-om51s1",
"colab": {}
},
"source": [
"import os\n",
"import pathlib\n",
"\n",
"\n",
"if \"models\" in pathlib.Path.cwd().parts:\n",
" while \"models\" in pathlib.Path.cwd().parts:\n",
" os.chdir('..')\n",
"elif not pathlib.Path('models').exists():\n",
" !git clone --depth 1 https://github.com/tensorflow/models"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "O219m6yWAj9l"
},
"source": [
"Compile protobufs and install the object_detection package"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "PY41vdYYNlXc",
"colab": {}
},
"source": [
"%%bash\n",
"cd models/research/\n",
"protoc object_detection/protos/*.proto --python_out=."
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "s62yJyQUcYbp",
"colab": {}
},
"source": [
"%%bash \n",
"cd models/research\n",
"pip install ."
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "hV4P5gyTWKMI",
"colab": {}
},
"source": [
"import numpy as np\n",
"import os\n",
"import six.moves.urllib as urllib\n",
"import sys\n",
"import tarfile\n",
"import tensorflow as tf\n",
"import zipfile\n",
"\n",
"from collections import defaultdict\n",
"from io import StringIO\n",
"from matplotlib import pyplot as plt\n",
"from PIL import Image\n",
"from IPython.display import display"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "r5FNuiRPWKMN"
},
"source": [
"Import the object detection module."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "4-IMl4b6BdGO",
"colab": {}
},
"source": [
"from object_detection.utils import ops as utils_ops\n",
"from object_detection.utils import label_map_util\n",
"from object_detection.utils import visualization_utils as vis_util"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "TUOFCmpvn7ZI",
"colab_type": "code",
"colab": {}
},
"source": [
"PATH_TO_LABELS = 'models/research/object_detection/data/mscoco_label_map.pbtxt'\n",
"category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "RYPCiag2iz_q"
},
"source": [
"Patches:"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "mF-YlMl8c_bM",
"colab": {}
},
"source": [
"# patch tf1 into `utils.ops`\n",
"utils_ops.tf = tf.compat.v1\n",
"\n",
"# Patch the location of gfile\n",
"tf.gfile = tf.io.gfile"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "cfn_tRFOWKMO"
},
"source": [
"## Model"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "X_sEBLpVWKMQ"
},
"source": [
"**Variables**\n",
"\n",
"Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing the path.\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "zm8xp-0eoItE",
"colab": {}
},
"source": [
"# Loader\n",
"\n",
"def load_model(model_name):\n",
" base_url = 'http://download.tensorflow.org/models/object_detection/'\n",
" model_file = model_name + '.tar.gz'\n",
" model_dir = tf.keras.utils.get_file(\n",
" fname=model_name, \n",
" origin=base_url + model_file,\n",
" untar=True)\n",
"\n",
" model_dir = pathlib.Path(model_dir)/\"saved_model\"\n",
"\n",
" model = tf.saved_model.load(str(model_dir))\n",
" model = model.signatures['serving_default']\n",
"\n",
" return model"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "H0_1AGhrWKMc"
},
"source": [
"## Inference"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "f7aOtOlebK7h"
},
"source": [
"Load an object detection model:"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "1XNT0wxybKR6",
"colab": {}
},
"source": [
"detection_model = load_model(model_name + model_date)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "yN1AYfAEJIGp"
},
"source": [
"Check the model's input signature, it expects a batch of 3-color images of type uint8: "
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "CK4cnry6wsHY",
"colab": {}
},
"source": [
"print(detection_model.inputs)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "Q8u3BjpMJXZF"
},
"source": [
"And returns several outputs:"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "oLSZpfaYwuSk",
"colab": {}
},
"source": [
"detection_model.output_dtypes"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "FZyKUJeuxvpT",
"colab": {}
},
"source": [
"detection_model.output_shapes"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "JP5qZ7sXJpwG"
},
"source": [
"Add a wrapper function to call the model, and cleanup the outputs:"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "ajmR_exWyN76",
"colab": {}
},
"source": [
"def run_inference_for_single_image(model, image):\n",
" image = np.asarray(image)\n",
" # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.\n",
" input_tensor = tf.convert_to_tensor(image)\n",
" # The model expects a batch of images, so add an axis with `tf.newaxis`.\n",
" input_tensor = input_tensor[tf.newaxis,...]\n",
"\n",
" # Run inference\n",
" output_dict = model(input_tensor)\n",
"\n",
" # All outputs are batches tensors.\n",
" # Convert to numpy arrays, and take index [0] to remove the batch dimension.\n",
" # We're only interested in the first num_detections.\n",
" num_detections = int(output_dict.pop('num_detections'))\n",
" output_dict = {key:value[0, :num_detections].numpy() \n",
" for key,value in output_dict.items()}\n",
" output_dict['num_detections'] = num_detections\n",
"\n",
" # detection_classes should be ints.\n",
" output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)\n",
" \n",
" # Handle models with masks:\n",
" if 'detection_masks' in output_dict:\n",
" # Reframe the the bbox mask to the image size.\n",
" detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n",
" output_dict['detection_masks'], output_dict['detection_boxes'],\n",
" image.shape[0], image.shape[1]) \n",
" detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,\n",
" tf.uint8)\n",
" output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()\n",
" \n",
" return output_dict"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "z1wq0LVyMRR_"
},
"source": [
"Run it on each test image and show the results:"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "DWh_1zz6aqxs",
"colab": {}
},
"source": [
"def show_inference(model, image_path):\n",
" # the array based representation of the image will be used later in order to prepare the\n",
" # result image with boxes and labels on it.\n",
" image_np = np.array(Image.open(image_path))\n",
" # Actual detection.\n",
" output_dict = run_inference_for_single_image(model, image_np)\n",
" # Visualization of the results of a detection.\n",
" vis_util.visualize_boxes_and_labels_on_image_array(\n",
" image_np,\n",
" output_dict['detection_boxes'],\n",
" output_dict['detection_classes'],\n",
" output_dict['detection_scores'],\n",
" category_index,\n",
" instance_masks=output_dict.get('detection_masks_reframed', None),\n",
" use_normalized_coordinates=True,\n",
" line_thickness=8)\n",
"\n",
" display(Image.fromarray(image_np))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "yTvKLSYPTIjX",
"colab_type": "text"
},
"source": [
"## Output"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "3a5wMHN8WKMh",
"colab": {}
},
"source": [
"import time\n",
"\n",
"for image_path in TEST_IMAGE_PATHS:\n",
" start = 0\n",
" end = 0\n",
" start = time.time()\n",
" show_inference(detection_model, image_path)\n",
" end = time.time()\n",
" print(end - start)"
],
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment