{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "KFPcBuVFw61h"
      },
      "source": [
        "# Overview\n",
        "\n",
        "This colab demonstrates the steps to use the DeepLab model to perform semantic segmentation on a sample input image. Expected outputs are semantic labels overlayed on the sample image.\n",
        "\n",
        "### About DeepLab\n",
        "The models used in this colab perform semantic segmentation. Semantic segmentation models focus on assigning semantic labels, such as sky, person, or car, to multiple objects and stuff in a single image."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "t3ozFsEEP-u_"
      },
      "source": [
        "# Instructions\n",
        "\u003ch3\u003e\u003ca href=\"https://cloud.google.com/tpu/\"\u003e\u003cimg valign=\"middle\" src=\"https://raw.githubusercontent.com/GoogleCloudPlatform/tensorflow-without-a-phd/master/tensorflow-rl-pong/images/tpu-hexagon.png\" width=\"50\"\u003e\u003c/a\u003e  \u0026nbsp;\u0026nbsp;Use a free TPU device\u003c/h3\u003e\n",
        "\n",
        "   1. On the main menu, click Runtime and select **Change runtime type**. Set \"TPU\" as the hardware accelerator.\n",
        "   1. Click Runtime again and select **Runtime \u003e Run All**. You can also run the cells manually with Shift-ENTER."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7cRiapZ1P3wy"
      },
      "source": [
        "## Import Libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
        "colab": {},
        "colab_type": "code",
        "id": "kAbdmRmvq0Je"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from io import BytesIO\n",
        "import tarfile\n",
        "import tempfile\n",
        "from six.moves import urllib\n",
        "\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "\n",
        "%tensorflow_version 1.x\n",
        "import tensorflow as tf"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "p47cYGGOQE1W"
      },
      "source": [
        "## Import helper methods\n",
        "These methods help us perform the following tasks:\n",
        "* Load the latest version of the pretrained DeepLab model\n",
        "* Load the colormap from the PASCAL VOC dataset\n",
        "* Adds colors to various labels, such as \"pink\" for people, \"green\" for bicycle and more\n",
        "* Visualize an image, and add an overlay of colors on various regions"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
        "colab": {},
        "colab_type": "code",
        "id": "vN0kU6NJ1Ye5"
      },
      "outputs": [],
      "source": [
        "class DeepLabModel(object):\n",
        "  \"\"\"Class to load deeplab model and run inference.\"\"\"\n",
        "\n",
        "  INPUT_TENSOR_NAME = 'ImageTensor:0'\n",
        "  OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'\n",
        "  INPUT_SIZE = 513\n",
        "  FROZEN_GRAPH_NAME = 'frozen_inference_graph'\n",
        "\n",
        "  def __init__(self, tarball_path):\n",
        "    \"\"\"Creates and loads pretrained deeplab model.\"\"\"\n",
        "    self.graph = tf.Graph()\n",
        "\n",
        "    graph_def = None\n",
        "    # Extract frozen graph from tar archive.\n",
        "    tar_file = tarfile.open(tarball_path)\n",
        "    for tar_info in tar_file.getmembers():\n",
        "      if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):\n",
        "        file_handle = tar_file.extractfile(tar_info)\n",
        "        graph_def = tf.GraphDef.FromString(file_handle.read())\n",
        "        break\n",
        "\n",
        "    tar_file.close()\n",
        "\n",
        "    if graph_def is None:\n",
        "      raise RuntimeError('Cannot find inference graph in tar archive.')\n",
        "\n",
        "    with self.graph.as_default():\n",
        "      tf.import_graph_def(graph_def, name='')\n",
        "\n",
        "    self.sess = tf.Session(graph=self.graph)\n",
        "\n",
        "  def run(self, image):\n",
        "    \"\"\"Runs inference on a single image.\n",
        "\n",
        "    Args:\n",
        "      image: A PIL.Image object, raw input image.\n",
        "\n",
        "    Returns:\n",
        "      resized_image: RGB image resized from original input image.\n",
        "      seg_map: Segmentation map of `resized_image`.\n",
        "    \"\"\"\n",
        "    width, height = image.size\n",
        "    resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)\n",
        "    target_size = (int(resize_ratio * width), int(resize_ratio * height))\n",
        "    resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)\n",
        "    batch_seg_map = self.sess.run(\n",
        "        self.OUTPUT_TENSOR_NAME,\n",
        "        feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})\n",
        "    seg_map = batch_seg_map[0]\n",
        "    return resized_image, seg_map\n",
        "\n",
        "\n",
        "def create_pascal_label_colormap():\n",
        "  \"\"\"Creates a label colormap used in PASCAL VOC segmentation benchmark.\n",
        "\n",
        "  Returns:\n",
        "    A Colormap for visualizing segmentation results.\n",
        "  \"\"\"\n",
        "  colormap = np.zeros((256, 3), dtype=int)\n",
        "  ind = np.arange(256, dtype=int)\n",
        "\n",
        "  for shift in reversed(range(8)):\n",
        "    for channel in range(3):\n",
        "      colormap[:, channel] |= ((ind \u003e\u003e channel) \u0026 1) \u003c\u003c shift\n",
        "    ind \u003e\u003e= 3\n",
        "\n",
        "  return colormap\n",
        "\n",
        "\n",
        "def label_to_color_image(label):\n",
        "  \"\"\"Adds color defined by the dataset colormap to the label.\n",
        "\n",
        "  Args:\n",
        "    label: A 2D array with integer type, storing the segmentation label.\n",
        "\n",
        "  Returns:\n",
        "    result: A 2D array with floating type. The element of the array\n",
        "      is the color indexed by the corresponding element in the input label\n",
        "      to the PASCAL color map.\n",
        "\n",
        "  Raises:\n",
        "    ValueError: If label is not of rank 2 or its value is larger than color\n",
        "      map maximum entry.\n",
        "  \"\"\"\n",
        "  if label.ndim != 2:\n",
        "    raise ValueError('Expect 2-D input label')\n",
        "\n",
        "  colormap = create_pascal_label_colormap()\n",
        "\n",
        "  if np.max(label) \u003e= len(colormap):\n",
        "    raise ValueError('label value too large.')\n",
        "\n",
        "  return colormap[label]\n",
        "\n",
        "\n",
        "def vis_segmentation(image, seg_map):\n",
        "  \"\"\"Visualizes input image, segmentation map and overlay view.\"\"\"\n",
        "  plt.figure(figsize=(15, 5))\n",
        "  grid_spec = gridspec.GridSpec(1, 4, width_ratios=[6, 6, 6, 1])\n",
        "\n",
        "  plt.subplot(grid_spec[0])\n",
        "  plt.imshow(image)\n",
        "  plt.axis('off')\n",
        "  plt.title('input image')\n",
        "\n",
        "  plt.subplot(grid_spec[1])\n",
        "  seg_image = label_to_color_image(seg_map).astype(np.uint8)\n",
        "  plt.imshow(seg_image)\n",
        "  plt.axis('off')\n",
        "  plt.title('segmentation map')\n",
        "\n",
        "  plt.subplot(grid_spec[2])\n",
        "  plt.imshow(image)\n",
        "  plt.imshow(seg_image, alpha=0.7)\n",
        "  plt.axis('off')\n",
        "  plt.title('segmentation overlay')\n",
        "\n",
        "  unique_labels = np.unique(seg_map)\n",
        "  ax = plt.subplot(grid_spec[3])\n",
        "  plt.imshow(\n",
        "      FULL_COLOR_MAP[unique_labels].astype(np.uint8), interpolation='nearest')\n",
        "  ax.yaxis.tick_right()\n",
        "  plt.yticks(range(len(unique_labels)), LABEL_NAMES[unique_labels])\n",
        "  plt.xticks([], [])\n",
        "  ax.tick_params(width=0.0)\n",
        "  plt.grid('off')\n",
        "  plt.show()\n",
        "\n",
        "\n",
        "LABEL_NAMES = np.asarray([\n",
        "    'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',\n",
        "    'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',\n",
        "    'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tv'\n",
        "])\n",
        "\n",
        "FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)\n",
        "FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "nGcZzNkASG9A"
      },
      "source": [
        "## Select a pretrained model\n",
        "We have trained the DeepLab model using various backbone networks. Select one from the MODEL_NAME list."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {},
        "colab_type": "code",
        "id": "c4oXKmnjw6i_"
      },
      "outputs": [],
      "source": [
        "MODEL_NAME = 'mobilenetv2_coco_voctrainaug'  # @param ['mobilenetv2_coco_voctrainaug', 'mobilenetv2_coco_voctrainval', 'xception_coco_voctrainaug', 'xception_coco_voctrainval']\n",
        "\n",
        "_DOWNLOAD_URL_PREFIX = 'http://download.tensorflow.org/models/'\n",
        "_MODEL_URLS = {\n",
        "    'mobilenetv2_coco_voctrainaug':\n",
        "        'deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz',\n",
        "    'mobilenetv2_coco_voctrainval':\n",
        "        'deeplabv3_mnv2_pascal_trainval_2018_01_29.tar.gz',\n",
        "    'xception_coco_voctrainaug':\n",
        "        'deeplabv3_pascal_train_aug_2018_01_04.tar.gz',\n",
        "    'xception_coco_voctrainval':\n",
        "        'deeplabv3_pascal_trainval_2018_01_04.tar.gz',\n",
        "}\n",
        "_TARBALL_NAME = 'deeplab_model.tar.gz'\n",
        "\n",
        "model_dir = tempfile.mkdtemp()\n",
        "tf.gfile.MakeDirs(model_dir)\n",
        "\n",
        "download_path = os.path.join(model_dir, _TARBALL_NAME)\n",
        "print('downloading model, this might take a while...')\n",
        "urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],\n",
        "                   download_path)\n",
        "print('download completed! loading DeepLab model...')\n",
        "\n",
        "MODEL = DeepLabModel(download_path)\n",
        "print('model loaded successfully!')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "SZst78N-4OKO"
      },
      "source": [
        "## Run on sample images\n",
        "\n",
        "Select one of sample images (leave `IMAGE_URL` empty) or feed any internet image\n",
        "url for inference.\n",
        "\n",
        "Note that this colab uses single scale inference for fast computation,\n",
        "so the results may slightly differ from the visualizations in the\n",
        "[README](https://github.com/tensorflow/models/blob/master/research/deeplab/README.md) file,\n",
        "which uses multi-scale and left-right flipped inputs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "form",
        "colab": {},
        "colab_type": "code",
        "id": "edGukUHXyymr"
      },
      "outputs": [],
      "source": [
        "\n",
        "SAMPLE_IMAGE = 'image1'  # @param ['image1', 'image2', 'image3']\n",
        "IMAGE_URL = ''  #@param {type:\"string\"}\n",
        "\n",
        "_SAMPLE_URL = ('https://github.com/tensorflow/models/blob/master/research/'\n",
        "               'deeplab/g3doc/img/%s.jpg?raw=true')\n",
        "\n",
        "\n",
        "def run_visualization(url):\n",
        "  \"\"\"Inferences DeepLab model and visualizes result.\"\"\"\n",
        "  try:\n",
        "    f = urllib.request.urlopen(url)\n",
        "    jpeg_str = f.read()\n",
        "    original_im = Image.open(BytesIO(jpeg_str))\n",
        "  except IOError:\n",
        "    print('Cannot retrieve image. Please check url: ' + url)\n",
        "    return\n",
        "\n",
        "  print('running deeplab on image %s...' % url)\n",
        "  resized_im, seg_map = MODEL.run(original_im)\n",
        "\n",
        "  vis_segmentation(resized_im, seg_map)\n",
        "\n",
        "\n",
        "image_url = IMAGE_URL or _SAMPLE_URL % SAMPLE_IMAGE\n",
        "run_visualization(image_url)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "aUbVoHScTJYe"
      },
      "source": [
        "## What's next\n",
        "\n",
        "* Learn about [Cloud TPUs](https://cloud.google.com/tpu/docs) that Google designed and optimized specifically to speed up and scale up ML workloads for training and inference and to enable ML engineers and researchers to iterate more quickly.\n",
        "* Explore the range of [Cloud TPU tutorials and Colabs](https://cloud.google.com/tpu/docs/tutorials) to find other examples that can be used when implementing your ML project.\n",
        "* For more information on running the DeepLab model on Cloud TPUs, see the [DeepLab tutorial](https://cloud.google.com/tpu/docs/tutorials/deeplab).\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "DeepLab Demo.ipynb",
      "provenance": [],
      "toc_visible": true,
      "version": "0.3.2"
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
