deeplab_demo.ipynb 13.8 KB
Newer Older
yukun's avatar
yukun committed
1
{
2
3
4
5
6
7
8
9
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "KFPcBuVFw61h"
      },
      "source": [
Yukun Zhu's avatar
Yukun Zhu committed
10
        "# Overview\n",
11
        "\n",
Yukun Zhu's avatar
Yukun Zhu committed
12
        "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",
Yukun Zhu's avatar
Yukun Zhu committed
13
        "\n",
Yukun Zhu's avatar
Yukun Zhu committed
14
15
        "### 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."
Yukun Zhu's avatar
Yukun Zhu committed
16
17
18
19
20
21
22
23
24
25
26
27
28
      ]
    },
    {
      "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",
Yukun Zhu's avatar
Yukun Zhu committed
29
        "   1. Click Runtime again and select **Runtime \u003e Run All**. You can also run the cells manually with Shift-ENTER."
Yukun Zhu's avatar
Yukun Zhu committed
30
31
32
33
34
35
36
37
38
39
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7cRiapZ1P3wy"
      },
      "source": [
        "## Import Libraries"
40
41
42
43
44
45
46
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
Yukun Zhu's avatar
Yukun Zhu committed
47
        "colab": {},
48
49
50
51
52
53
        "colab_type": "code",
        "id": "kAbdmRmvq0Je"
      },
      "outputs": [],
      "source": [
        "import os\n",
54
        "from io import BytesIO\n",
55
56
        "import tarfile\n",
        "import tempfile\n",
57
        "from six.moves import urllib\n",
58
59
60
61
62
63
64
65
66
        "\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "\n",
        "import tensorflow as tf"
      ]
    },
Yukun Zhu's avatar
Yukun Zhu committed
67
68
69
70
71
72
73
74
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "p47cYGGOQE1W"
      },
      "source": [
        "## Import helper methods\n",
Yukun Zhu's avatar
Yukun Zhu committed
75
        "These methods help us perform the following tasks:\n",
Yukun Zhu's avatar
Yukun Zhu committed
76
77
        "* Load the latest version of the pretrained DeepLab model\n",
        "* Load the colormap from the PASCAL VOC dataset\n",
Yukun Zhu's avatar
Yukun Zhu committed
78
79
        "* 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"
Yukun Zhu's avatar
Yukun Zhu committed
80
81
      ]
    },
82
83
84
85
86
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
Yukun Zhu's avatar
Yukun Zhu committed
87
        "colab": {},
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        "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)"
      ]
    },
Yukun Zhu's avatar
Yukun Zhu committed
232
233
234
235
236
237
238
239
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "nGcZzNkASG9A"
      },
      "source": [
        "## Select a pretrained model\n",
Yukun Zhu's avatar
Yukun Zhu committed
240
        "We have trained the DeepLab model using various backbone networks. Select one from the MODEL_NAME list."
Yukun Zhu's avatar
Yukun Zhu committed
241
242
      ]
    },
243
244
245
246
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
Yukun Zhu's avatar
Yukun Zhu committed
247
        "colab": {},
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        "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",
272
273
        "print('downloading model, this might take a while...')\n",
        "urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],\n",
274
        "                   download_path)\n",
275
        "print('download completed! loading DeepLab model...')\n",
276
277
        "\n",
        "MODEL = DeepLabModel(download_path)\n",
278
        "print('model loaded successfully!')"
279
280
281
282
283
284
285
286
287
288
289
290
291
292
      ]
    },
    {
      "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",
Yukun Zhu's avatar
Yukun Zhu committed
293
        "Note that this colab uses single scale inference for fast computation,\n",
294
        "so the results may slightly differ from the visualizations in the\n",
Yukun Zhu's avatar
Yukun Zhu committed
295
        "[README](https://github.com/tensorflow/models/blob/master/research/deeplab/README.md) file,\n",
296
297
298
299
300
301
302
        "which uses multi-scale and left-right flipped inputs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
Yukun Zhu's avatar
Yukun Zhu committed
303
304
        "cellView": "form",
        "colab": {},
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
        "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",
321
        "    f = urllib.request.urlopen(url)\n",
322
        "    jpeg_str = f.read()\n",
323
        "    original_im = Image.open(BytesIO(jpeg_str))\n",
324
        "  except IOError:\n",
325
        "    print('Cannot retrieve image. Please check url: ' + url)\n",
326
327
        "    return\n",
        "\n",
328
        "  print('running deeplab on image %s...' % url)\n",
329
        "  resized_im, seg_map = MODEL.run(original_im)\n",
330
331
332
333
334
335
336
337
338
        "\n",
        "  vis_segmentation(resized_im, seg_map)\n",
        "\n",
        "\n",
        "image_url = IMAGE_URL or _SAMPLE_URL % SAMPLE_IMAGE\n",
        "run_visualization(image_url)"
      ]
    },
    {
Yukun Zhu's avatar
Yukun Zhu committed
339
      "cell_type": "markdown",
340
      "metadata": {
Yukun Zhu's avatar
Yukun Zhu committed
341
342
        "colab_type": "text",
        "id": "aUbVoHScTJYe"
343
344
      },
      "source": [
Yukun Zhu's avatar
Yukun Zhu committed
345
346
347
348
        "## 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",
Yukun Zhu's avatar
Yukun Zhu committed
349
        "* For more information on running the DeepLab model on Cloud TPUs, see the [DeepLab tutorial](https://cloud.google.com/tpu/docs/tutorials/deeplab).\n"
350
351
352
353
354
355
356
357
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "DeepLab Demo.ipynb",
      "provenance": [],
Yukun Zhu's avatar
Yukun Zhu committed
358
359
      "toc_visible": true,
      "version": "0.3.2"
360
361
362
363
364
    },
    "kernelspec": {
      "display_name": "Python 2",
      "name": "python2"
    }
yukun's avatar
yukun committed
365
  },
366
367
  "nbformat": 4,
  "nbformat_minor": 0
yukun's avatar
yukun committed
368
}