deeplab_demo.ipynb 11.9 KB
Newer Older
yukun's avatar
yukun committed
1
{
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "KFPcBuVFw61h"
      },
      "source": [
        "# DeepLab Demo\n",
        "\n",
        "This demo will demostrate the steps to run deeplab semantic segmentation model on sample input images."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "kAbdmRmvq0Je"
      },
      "outputs": [],
      "source": [
        "#@title Imports\n",
        "\n",
        "import os\n",
34
        "from io import BytesIO\n",
35
36
        "import tarfile\n",
        "import tempfile\n",
37
        "from six.moves import urllib\n",
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
232
233
234
235
236
237
238
239
240
        "\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"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "cellView": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "vN0kU6NJ1Ye5"
      },
      "outputs": [],
      "source": [
        "#@title Helper methods\n",
        "\n",
        "\n",
        "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": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "c4oXKmnjw6i_"
      },
      "outputs": [],
      "source": [
        "#@title Select and download models {display-mode: \"form\"}\n",
        "\n",
        "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",
241
242
        "print('downloading model, this might take a while...')\n",
        "urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME],\n",
243
        "                   download_path)\n",
244
        "print('download completed! loading DeepLab model...')\n",
245
246
        "\n",
        "MODEL = DeepLabModel(download_path)\n",
247
        "print('model loaded successfully!')"
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
      ]
    },
    {
      "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 we are using single scale inference in the demo for fast computation,\n",
        "so the results may slightly differ from the visualizations in\n",
        "[README](https://github.com/tensorflow/models/blob/master/research/deeplab/README.md),\n",
        "which uses multi-scale and left-right flipped inputs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "edGukUHXyymr"
      },
      "outputs": [],
      "source": [
        "#@title Run on sample images {display-mode: \"form\"}\n",
        "\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",
295
        "    f = urllib.request.urlopen(url)\n",
296
        "    jpeg_str = f.read()\n",
297
        "    original_im = Image.open(BytesIO(jpeg_str))\n",
298
        "  except IOError:\n",
299
        "    print('Cannot retrieve image. Please check url: ' + url)\n",
300
301
        "    return\n",
        "\n",
302
        "  print('running deeplab on image %s...' % url)\n",
303
        "  resized_im, seg_map = MODEL.run(original_im)\n",
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        "\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": "code",
      "execution_count": 0,
      "metadata": {
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "colab_type": "code",
        "id": "7XrFNGsxzSIB"
      },
      "outputs": [],
      "source": [
        ""
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "default_view": {},
      "name": "DeepLab Demo.ipynb",
      "provenance": [],
      "version": "0.3.2",
      "views": {}
    },
    "kernelspec": {
      "display_name": "Python 2",
      "name": "python2"
    }
yukun's avatar
yukun committed
344
  },
345
346
  "nbformat": 4,
  "nbformat_minor": 0
yukun's avatar
yukun committed
347
}
348