{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "V8-yl-s-WKMG"
      },
      "source": [
        "# Object Detection API Demo\n",
        "\n",
        "\u003ctable align=\"left\"\u003e\u003ctd\u003e\n",
        "  \u003ca target=\"_blank\"  href=\"https://colab.sandbox.google.com/github/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb\"\u003e\n",
        "    \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\n",
        "  \u003c/a\u003e\n",
        "\u003c/td\u003e\u003ctd\u003e\n",
        "  \u003ca target=\"_blank\"  href=\"https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb\"\u003e\n",
        "    \u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "\u003c/td\u003e\u003c/table\u003e"
      ]
    },
    {
      "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": [
        "\u003e **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": {
        "colab_type": "text",
        "id": "kFSqkTCdWKMI"
      },
      "source": [
        "# Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "awjrpqy-6MaQ"
      },
      "source": [
        "Important: If you're running on a local machine, be sure to follow the [installation instructions](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md). This notebook includes only what's necessary to run in Colab."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "p3UGXxUii5Ym"
      },
      "source": [
        "### Install"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "hGL97-GXjSUw"
      },
      "outputs": [],
      "source": [
        "!pip install -U --pre tensorflow==\"2.*\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "n_ap_s9ajTHH"
      },
      "source": [
        "Make sure you have `pycocotools` installed"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "Bg8ZyA47i3pY"
      },
      "outputs": [],
      "source": [
        "!pip install pycocotools"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-vsOL3QR6kqs"
      },
      "source": [
        "Get `tensorflow/models` or `cd` to parent directory of the repository."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "ykA0c-om51s1"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "O219m6yWAj9l"
      },
      "source": [
        "Compile protobufs and install the object_detection package"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "PY41vdYYNlXc"
      },
      "outputs": [],
      "source": [
        "%%bash\n",
        "cd models/research/\n",
        "protoc object_detection/protos/*.proto --python_out=."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "s62yJyQUcYbp"
      },
      "outputs": [],
      "source": [
        "%%bash \n",
        "cd models/research\n",
        "pip install ."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LBdjK2G5ywuc"
      },
      "source": [
        "### Imports"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "hV4P5gyTWKMI"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "r5FNuiRPWKMN"
      },
      "source": [
        "Import the object detection module."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "4-IMl4b6BdGO"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "RYPCiag2iz_q"
      },
      "source": [
        "Patches:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "mF-YlMl8c_bM"
      },
      "outputs": [],
      "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cfn_tRFOWKMO"
      },
      "source": [
        "# Model preparation "
      ]
    },
    {
      "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": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7ai8pLZZWKMS"
      },
      "source": [
        "## Loader"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "zm8xp-0eoItE"
      },
      "outputs": [],
      "source": [
        "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"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "_1MVVTcLWKMW"
      },
      "source": [
        "## Loading label map\n",
        "Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "hDbpHkiWWKMX"
      },
      "outputs": [],
      "source": [
        "# List of the strings that is used to add correct label for each box.\n",
        "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)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "oVU3U_J6IJVb"
      },
      "source": [
        "For the sake of simplicity we will test on 2 images:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "jG-zn5ykWKMd"
      },
      "outputs": [],
      "source": [
        "# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.\n",
        "PATH_TO_TEST_IMAGES_DIR = pathlib.Path('models/research/object_detection/test_images')\n",
        "TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob(\"*.jpg\")))\n",
        "TEST_IMAGE_PATHS"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "H0_1AGhrWKMc"
      },
      "source": [
        "# Detection"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "f7aOtOlebK7h"
      },
      "source": [
        "Load an object detection model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "1XNT0wxybKR6"
      },
      "outputs": [],
      "source": [
        "model_name = 'ssd_mobilenet_v1_coco_2017_11_17'\n",
        "detection_model = load_model(model_name)"
      ]
    },
    {
      "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",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "CK4cnry6wsHY"
      },
      "outputs": [],
      "source": [
        "print(detection_model.inputs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Q8u3BjpMJXZF"
      },
      "source": [
        "And returns several outputs:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "oLSZpfaYwuSk"
      },
      "outputs": [],
      "source": [
        "detection_model.output_dtypes"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "FZyKUJeuxvpT"
      },
      "outputs": [],
      "source": [
        "detection_model.output_shapes"
      ]
    },
    {
      "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",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "ajmR_exWyN76"
      },
      "outputs": [],
      "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 \u003e 0.5,\n",
        "                                       tf.uint8)\n",
        "    output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()\n",
        "    \n",
        "  return output_dict"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "z1wq0LVyMRR_"
      },
      "source": [
        "Run it on each test image and show the results:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "DWh_1zz6aqxs"
      },
      "outputs": [],
      "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))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "3a5wMHN8WKMh"
      },
      "outputs": [],
      "source": [
        "for image_path in TEST_IMAGE_PATHS:\n",
        "  show_inference(detection_model, image_path)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DsspMPX3Cssg"
      },
      "source": [
        "## Instance Segmentation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "CzkVv_n2MxKC"
      },
      "outputs": [],
      "source": [
        "model_name = \"mask_rcnn_inception_resnet_v2_atrous_coco_2018_01_28\"\n",
        "masking_model = load_model(model_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0S7aZi8ZOhVV"
      },
      "source": [
        "The instance segmentation model includes a `detection_masks` output:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "vQ2Sj2VIOZLA"
      },
      "outputs": [],
      "source": [
        "masking_model.output_shapes"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "AS57rZlnNL7W"
      },
      "outputs": [],
      "source": [
        "for image_path in TEST_IMAGE_PATHS:\n",
        "  show_inference(masking_model, image_path)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "nLlmm9JojEKm"
      },
      "outputs": [],
      "source": [
        ""
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "last_runtime": {
        "build_target": "//learning/brain/python/client:colab_notebook",
        "kind": "private"
      },
      "name": "object_detection_tutorial.ipynb",
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "1LNYL6Zsn9Xlil2CVNOTsgDZQSBKeOjCh",
          "timestamp": 1566498233247
        },
        {
          "file_id": "/piper/depot/google3/third_party/tensorflow_models/object_detection/object_detection_tutorial.ipynb?workspaceId=markdaoust:copybara_AFABFE845DCD573AD3D43A6BAFBE77D4_0::citc",
          "timestamp": 1566488313397
        },
        {
          "file_id": "/piper/depot/google3/third_party/py/tensorflow_docs/g3doc/en/r2/tutorials/generative/object_detection_tutorial.ipynb?workspaceId=markdaoust:copybara_AFABFE845DCD573AD3D43A6BAFBE77D4_0::citc",
          "timestamp": 1566145894046
        },
        {
          "file_id": "1nBPoWynOV0auSIy40eQcBIk9C6YRSkI8",
          "timestamp": 1566145841085
        },
        {
          "file_id": "/piper/depot/google3/third_party/tensorflow_models/object_detection/object_detection_tutorial.ipynb?workspaceId=markdaoust:copybara_AFABFE845DCD573AD3D43A6BAFBE77D4_0::citc",
          "timestamp": 1556295408037
        },
        {
          "file_id": "1layerger-51XwWOwYMY_5zHaCavCeQkO",
          "timestamp": 1556214267924
        },
        {
          "file_id": "/piper/depot/google3/third_party/tensorflow_models/object_detection/object_detection_tutorial.ipynb?workspaceId=markdaoust:copybara_AFABFE845DCD573AD3D43A6BAFBE77D4_0::citc",
          "timestamp": 1556207836484
        },
        {
          "file_id": "1w6mqQiNV3liPIX70NOgitOlDF1_4sRMw",
          "timestamp": 1556154824101
        },
        {
          "file_id": "https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb",
          "timestamp": 1556150293326
        }
      ],
      "version": "0.3.2"
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
