File size: 16,914 Bytes
0924f30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
35
36
37
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
241
242
243
244
245
246
247
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
295
296
297
298
299
300
301
302
303
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B8a_URGiowPn"
      },
      "source": [
        "## Overview\n",
        "This colab demonstrates the steps to run a family of DeepLab models built by the DeepLab2 library to perform dense pixel labeling tasks. The models used in this colab perform panoptic segmentation, where the predicted value encodes both semantic class and instance label for every pixel (including both ‘thing’ and ‘stuff’ pixels).\n",
        "\n",
        "### About DeepLab2\n",
        "DeepLab2 is a TensorFlow library for deep labeling, aiming to facilitate future research on dense pixel labeling tasks by providing state-of-the-art and easy-to-use TensorFlow models. Code is made publicly available at https://github.com/google-research/deeplab2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IGVFjkE2o0K8"
      },
      "source": [
        "### Import and helper methods"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dQNiIp-LoV6f"
      },
      "outputs": [],
      "source": [
        "import collections\n",
        "import os\n",
        "import tempfile\n",
        "\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "import urllib\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "from google.colab import files"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Avk0g2-wo2AO"
      },
      "outputs": [],
      "source": [
        "DatasetInfo = collections.namedtuple(\n",
        "    'DatasetInfo',\n",
        "    'num_classes, label_divisor, thing_list, colormap, class_names')\n",
        "\n",
        "\n",
        "def _cityscapes_label_colormap():\n",
        "  \"\"\"Creates a label colormap used in CITYSCAPES segmentation benchmark.\n",
        "\n",
        "  See more about CITYSCAPES dataset at https://www.cityscapes-dataset.com/\n",
        "  M. Cordts, et al. \"The Cityscapes Dataset for Semantic Urban Scene Understanding.\" CVPR. 2016.\n",
        "\n",
        "  Returns:\n",
        "    A 2-D numpy array with each row being mapped RGB color (in uint8 range).\n",
        "  \"\"\"\n",
        "  colormap = np.zeros((256, 3), dtype=np.uint8)\n",
        "  colormap[0] = [128, 64, 128]\n",
        "  colormap[1] = [244, 35, 232]\n",
        "  colormap[2] = [70, 70, 70]\n",
        "  colormap[3] = [102, 102, 156]\n",
        "  colormap[4] = [190, 153, 153]\n",
        "  colormap[5] = [153, 153, 153]\n",
        "  colormap[6] = [250, 170, 30]\n",
        "  colormap[7] = [220, 220, 0]\n",
        "  colormap[8] = [107, 142, 35]\n",
        "  colormap[9] = [152, 251, 152]\n",
        "  colormap[10] = [70, 130, 180]\n",
        "  colormap[11] = [220, 20, 60]\n",
        "  colormap[12] = [255, 0, 0]\n",
        "  colormap[13] = [0, 0, 142]\n",
        "  colormap[14] = [0, 0, 70]\n",
        "  colormap[15] = [0, 60, 100]\n",
        "  colormap[16] = [0, 80, 100]\n",
        "  colormap[17] = [0, 0, 230]\n",
        "  colormap[18] = [119, 11, 32]\n",
        "  return colormap\n",
        "\n",
        "\n",
        "def _cityscapes_class_names():\n",
        "  return ('road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n",
        "          'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',\n",
        "          'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',\n",
        "          'bicycle')\n",
        "\n",
        "\n",
        "def cityscapes_dataset_information():\n",
        "  return DatasetInfo(\n",
        "      num_classes=19,\n",
        "      label_divisor=1000,\n",
        "      thing_list=tuple(range(11, 19)),\n",
        "      colormap=_cityscapes_label_colormap(),\n",
        "      class_names=_cityscapes_class_names())\n",
        "\n",
        "\n",
        "def perturb_color(color, noise, used_colors, max_trials=50, random_state=None):\n",
        "  \"\"\"Pertrubs the color with some noise.\n",
        "\n",
        "  If `used_colors` is not None, we will return the color that has\n",
        "  not appeared before in it.\n",
        "\n",
        "  Args:\n",
        "    color: A numpy array with three elements [R, G, B].\n",
        "    noise: Integer, specifying the amount of perturbing noise (in uint8 range).\n",
        "    used_colors: A set, used to keep track of used colors.\n",
        "    max_trials: An integer, maximum trials to generate random color.\n",
        "    random_state: An optional np.random.RandomState. If passed, will be used to\n",
        "      generate random numbers.\n",
        "\n",
        "  Returns:\n",
        "    A perturbed color that has not appeared in used_colors.\n",
        "  \"\"\"\n",
        "  if random_state is None:\n",
        "    random_state = np.random\n",
        "\n",
        "  for _ in range(max_trials):\n",
        "    random_color = color + random_state.randint(\n",
        "        low=-noise, high=noise + 1, size=3)\n",
        "    random_color = np.clip(random_color, 0, 255)\n",
        "\n",
        "    if tuple(random_color) not in used_colors:\n",
        "      used_colors.add(tuple(random_color))\n",
        "      return random_color\n",
        "\n",
        "  print('Max trial reached and duplicate color will be used. Please consider '\n",
        "        'increase noise in `perturb_color()`.')\n",
        "  return random_color\n",
        "\n",
        "\n",
        "def color_panoptic_map(panoptic_prediction, dataset_info, perturb_noise):\n",
        "  \"\"\"Helper method to colorize output panoptic map.\n",
        "\n",
        "  Args:\n",
        "    panoptic_prediction: A 2D numpy array, panoptic prediction from deeplab\n",
        "      model.\n",
        "    dataset_info: A DatasetInfo object, dataset associated to the model.\n",
        "    perturb_noise: Integer, the amount of noise (in uint8 range) added to each\n",
        "      instance of the same semantic class.\n",
        "\n",
        "  Returns:\n",
        "    colored_panoptic_map: A 3D numpy array with last dimension of 3, colored\n",
        "      panoptic prediction map.\n",
        "    used_colors: A dictionary mapping semantic_ids to a set of colors used\n",
        "      in `colored_panoptic_map`.\n",
        "  \"\"\"\n",
        "  if panoptic_prediction.ndim != 2:\n",
        "    raise ValueError('Expect 2-D panoptic prediction. Got {}'.format(\n",
        "        panoptic_prediction.shape))\n",
        "\n",
        "  semantic_map = panoptic_prediction // dataset_info.label_divisor\n",
        "  instance_map = panoptic_prediction % dataset_info.label_divisor\n",
        "  height, width = panoptic_prediction.shape\n",
        "  colored_panoptic_map = np.zeros((height, width, 3), dtype=np.uint8)\n",
        "\n",
        "  used_colors = collections.defaultdict(set)\n",
        "  # Use a fixed seed to reproduce the same visualization.\n",
        "  random_state = np.random.RandomState(0)\n",
        "\n",
        "  unique_semantic_ids = np.unique(semantic_map)\n",
        "  for semantic_id in unique_semantic_ids:\n",
        "    semantic_mask = semantic_map == semantic_id\n",
        "    if semantic_id in dataset_info.thing_list:\n",
        "      # For `thing` class, we will add a small amount of random noise to its\n",
        "      # correspondingly predefined semantic segmentation colormap.\n",
        "      unique_instance_ids = np.unique(instance_map[semantic_mask])\n",
        "      for instance_id in unique_instance_ids:\n",
        "        instance_mask = np.logical_and(semantic_mask,\n",
        "                                       instance_map == instance_id)\n",
        "        random_color = perturb_color(\n",
        "            dataset_info.colormap[semantic_id],\n",
        "            perturb_noise,\n",
        "            used_colors[semantic_id],\n",
        "            random_state=random_state)\n",
        "        colored_panoptic_map[instance_mask] = random_color\n",
        "    else:\n",
        "      # For `stuff` class, we use the defined semantic color.\n",
        "      colored_panoptic_map[semantic_mask] = dataset_info.colormap[semantic_id]\n",
        "      used_colors[semantic_id].add(tuple(dataset_info.colormap[semantic_id]))\n",
        "  return colored_panoptic_map, used_colors\n",
        "\n",
        "\n",
        "def vis_segmentation(image,\n",
        "                     panoptic_prediction,\n",
        "                     dataset_info,\n",
        "                     perturb_noise=60):\n",
        "  \"\"\"Visualizes input image, segmentation map and overlay view.\"\"\"\n",
        "  plt.figure(figsize=(30, 20))\n",
        "  grid_spec = gridspec.GridSpec(2, 2)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[0])\n",
        "  plt.imshow(image)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('input image', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[1])\n",
        "  panoptic_map, used_colors = color_panoptic_map(panoptic_prediction,\n",
        "                                                 dataset_info, perturb_noise)\n",
        "  plt.imshow(panoptic_map)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('panoptic map', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[2])\n",
        "  plt.imshow(image)\n",
        "  plt.imshow(panoptic_map, alpha=0.7)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('panoptic overlay', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[3])\n",
        "  max_num_instances = max(len(color) for color in used_colors.values())\n",
        "  # RGBA image as legend.\n",
        "  legend = np.zeros((len(used_colors), max_num_instances, 4), dtype=np.uint8)\n",
        "  class_names = []\n",
        "  for i, semantic_id in enumerate(sorted(used_colors)):\n",
        "    legend[i, :len(used_colors[semantic_id]), :3] = np.array(\n",
        "        list(used_colors[semantic_id]))\n",
        "    legend[i, :len(used_colors[semantic_id]), 3] = 255\n",
        "    if semantic_id \u003c dataset_info.num_classes:\n",
        "      class_names.append(dataset_info.class_names[semantic_id])\n",
        "    else:\n",
        "      class_names.append('ignore')\n",
        "\n",
        "  plt.imshow(legend, interpolation='nearest')\n",
        "  ax.yaxis.tick_left()\n",
        "  plt.yticks(range(len(legend)), class_names, fontsize=15)\n",
        "  plt.xticks([], [])\n",
        "  ax.tick_params(width=0.0, grid_linewidth=0.0)\n",
        "  plt.grid('off')\n",
        "  plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1ly6p6M2o8SF"
      },
      "source": [
        "### Select a pretrained model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "peo7LUTtulpQ"
      },
      "outputs": [],
      "source": [
        "MODEL_NAME = 'max_deeplab_l_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model'  # @param ['resnet50_os32_panoptic_deeplab_cityscapes_crowd_trainfine_saved_model', 'resnet50_beta_os32_panoptic_deeplab_cityscapes_trainfine_saved_model', 'wide_resnet41_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_1_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_3_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_4.5_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_1_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_3_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_4.5_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'max_deeplab_s_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'max_deeplab_l_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model']\n",
        "\n",
        "\n",
        "_MODELS = ('resnet50_os32_panoptic_deeplab_cityscapes_crowd_trainfine_saved_model',\n",
        "           'resnet50_beta_os32_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'wide_resnet41_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_1_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_3_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_4.5_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_1_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_3_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_4.5_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'max_deeplab_s_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'max_deeplab_l_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model')\n",
        "_DOWNLOAD_URL_PATTERN = 'https://storage.googleapis.com/gresearch/tf-deeplab/saved_model/%s.tar.gz'\n",
        "\n",
        "_MODEL_NAME_TO_URL_AND_DATASET = {\n",
        "    model: (_DOWNLOAD_URL_PATTERN % model, cityscapes_dataset_information())\n",
        "    for model in _MODELS\n",
        "}\n",
        "\n",
        "MODEL_URL, DATASET_INFO = _MODEL_NAME_TO_URL_AND_DATASET[MODEL_NAME]\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UjYwP1Sjo4dd"
      },
      "outputs": [],
      "source": [
        "model_dir = tempfile.mkdtemp()\n",
        "\n",
        "download_path = os.path.join(model_dir, MODEL_NAME + '.gz')\n",
        "urllib.request.urlretrieve(MODEL_URL, download_path)\n",
        "\n",
        "!tar -xzvf {download_path} -C {model_dir}\n",
        "\n",
        "LOADED_MODEL = tf.saved_model.load(os.path.join(model_dir, MODEL_NAME))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "umpwnn4etG6z"
      },
      "source": [
        "### Run on sample images"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6552FXlAOHnX"
      },
      "outputs": [],
      "source": [
        "# Optional, upload an image from your local machine.\n",
        "\n",
        "uploaded = files.upload()\n",
        "\n",
        "if not uploaded:\n",
        "  UPLOADED_FILE = ''\n",
        "elif len(uploaded) == 1:\n",
        "  UPLOADED_FILE = list(uploaded.keys())[0]\n",
        "else:\n",
        "  raise AssertionError('Please upload one image at a time')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SF40dAWFPZmN"
      },
      "outputs": [],
      "source": [
        "# Using provided sample image if no file is uploaded.\n",
        "\n",
        "if not UPLOADED_FILE:\n",
        "  # Default image from Mapillary dataset samples (https://www.mapillary.com/dataset/vistas).\n",
        "  # Neuhold, Gerhard, et al. \"The mapillary vistas dataset for semantic understanding of street scenes.\" ICCV. 2017.\n",
        "  image_dir = tempfile.mkdtemp()\n",
        "  download_path = os.path.join(image_dir, 'MVD_research_samples.zip')\n",
        "  urllib.request.urlretrieve(\n",
        "      'https://static.mapillary.com/MVD_research_samples.zip', download_path)\n",
        "\n",
        "  !unzip {download_path} -d {image_dir}\n",
        "  UPLOADED_FILE = os.path.join(image_dir, 'Asia/tlxGlVwxyGUdUBfkjy1UOQ.jpg')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bsQ7Oj7jtHDz"
      },
      "outputs": [],
      "source": [
        "with tf.io.gfile.GFile(UPLOADED_FILE, 'rb') as f:\n",
        "  im = np.array(Image.open(f))\n",
        "\n",
        "output = LOADED_MODEL(tf.cast(im, tf.uint8))\n",
        "vis_segmentation(im, output['panoptic_pred'][0], DATASET_INFO)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "DeepLab_Demo.ipynb",
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "18PFmyE_Tcs97fX892SHgtvxaCa0QXTta",
          "timestamp": 1623189153618
        }
      ]
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}