unet_inference.ipynb 6.36 KB
Newer Older
1
2
{
 "cells": [
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
	{
		"cell_type": "code",
		"metadata": {},
		"source": [
			"#  The MIT License (MIT)",
			"#",
			"#  Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.",
			"#",
			"#  Permission is hereby granted, free of charge, to any person obtaining a copy",
			"#  of this software and associated documentation files (the 'Software'), to deal",
			"#  in the Software without restriction, including without limitation the rights",
			"#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
			"#  copies of the Software, and to permit persons to whom the Software is",
			"#  furnished to do so, subject to the following conditions:",
			"#",
			"#  The above copyright notice and this permission notice shall be included in",
			"#  all copies or substantial portions of the Software.",
			"#",
			"#  THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
			"#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
			"#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE",
			"#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
			"#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
			"#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
			"#  THE SOFTWARE."
		]
	},

31
32
  {
   "cell_type": "markdown",
33
   "id": "cd7a3990",
34
35
36
37
38
39
40
   "metadata": {},
   "source": [
    "## Import MIGraphX Python Library"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
41
   "execution_count": null,
42
   "id": "3930d7b8",
43
44
45
   "metadata": {},
   "outputs": [],
   "source": [
46
47
48
    "import migraphx\n",
    "from PIL import Image\n",
    "import numpy as np\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
49
    "import matplotlib.pyplot as plt"
50
51
52
53
   ]
  },
  {
   "cell_type": "markdown",
54
   "id": "b350c333",
55
56
57
58
59
60
61
   "metadata": {},
   "source": [
    "## Fetch U-NET ONNX Model"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
62
   "execution_count": null,
63
64
   "id": "02a7b7de",
   "metadata": {},
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
65
   "outputs": [],
66
   "source": [
67
    "!wget -nc https://www.dropbox.com/s/3ntkhyk30x05uuv/unet_13_256.onnx"
68
69
70
71
72
73
74
75
76
77
78
79
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6cfe6e9",
   "metadata": {},
   "source": [
    "## Load ONNX Model"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
80
   "execution_count": null,
81
82
83
84
   "id": "e05a13dc",
   "metadata": {},
   "outputs": [],
   "source": [
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
85
86
87
88
89
    "model = migraphx.parse_onnx(\"unet_13_256.onnx\")"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
90
   "execution_count": null,
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
91
92
93
94
   "id": "52c67023",
   "metadata": {},
   "outputs": [],
   "source": [
95
96
97
98
99
100
101
102
103
104
105
106
107
    "model.compile(migraphx.get_target(\"gpu\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80edb6f1",
   "metadata": {},
   "source": [
    "## Print model parameters"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
108
   "execution_count": null,
109
110
   "id": "fd5c3269",
   "metadata": {},
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
111
   "outputs": [],
112
113
114
115
116
117
118
   "source": [
    "print(model.get_parameter_names())\n",
    "print(model.get_parameter_shapes())"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
119
   "execution_count": null,
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
120
   "id": "47f956c7",
121
122
123
   "metadata": {},
   "outputs": [],
   "source": [
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    "def preprocess(pil_img, newW, newH):\n",
    "    w, h = pil_img.size\n",
    "    assert newW > 0 and newH > 0, 'Scale is too small'\n",
    "    pil_img = pil_img.resize((newW, newH))\n",
    "\n",
    "    img_nd = np.array(pil_img)\n",
    "\n",
    "    if len(img_nd.shape) == 2:\n",
    "        img_nd = np.expand_dims(img_nd, axis=2)\n",
    "\n",
    "    # HWC to CHW\n",
    "    img_print = pil_img\n",
    "    img_trans = img_nd.transpose((2, 0, 1))\n",
    "    if img_trans.max() > 1:\n",
    "        img_trans = img_trans / 255\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
139
140
    "        \n",
    "    img_trans = np.expand_dims(img_trans, 0)\n",
141
142
143
144
    "\n",
    "    return img_trans, img_print\n",
    "\n",
    "def plot_img_and_mask(img, mask):\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
145
146
    "    classes = mask.shape[0] if len(mask.shape) > 3 else 1\n",
    "    print(classes)\n",
147
148
149
150
151
152
153
154
155
    "    fig, ax = plt.subplots(1, classes + 1)\n",
    "    ax[0].set_title('Input image')\n",
    "    ax[0].imshow(img)\n",
    "    if classes > 1:\n",
    "        for i in range(classes):\n",
    "            ax[i+1].set_title(f'Output mask (class {i+1})')\n",
    "            ax[i+1].imshow(mask[:, :, i])\n",
    "    else:\n",
    "        ax[1].set_title(f'Output mask')\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
156
    "        ax[1].imshow(mask[0,0])\n",
157
158
159
160
161
162
    "    plt.xticks([]), plt.yticks([])\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
163
   "execution_count": null,
164
165
   "id": "389ddc4d",
   "metadata": {},
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
166
   "outputs": [],
167
   "source": [
168
    "img = Image.open(\"./car1.jpeg\")\n",
169
    "img, imPrint = preprocess(img, 256, 256)\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
170
171
172
173
    "input_im = np.zeros((1,3,256,256),dtype='float32') \n",
    "np.lib.stride_tricks.as_strided(input_im, shape=img.shape, strides=input_im.strides)[:] = img #getting correct stride\n",
    "print(input_im.strides)\n",
    "print(input_im.shape)\n",
174
    "imPrint.show()"
175
176
   ]
  },
177
178
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
179
   "execution_count": null,
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
180
   "id": "9de6f2a7",
181
   "metadata": {},
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
182
   "outputs": [],
183
   "source": [
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
184
185
    "mask = model.run({'inputs':input_im}) # Your first inference would take longer than the following ones.\n",
    "output_mask = np.array(mask[0])\n",
186
    "print(output_mask.shape)"
187
188
   ]
  },
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
189
190
191
192
193
194
195
196
197
198
199
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acbd68e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sigmoid(x):\n",
    "  return 1 / (1 + np.exp(-x))"
   ]
  },
200
201
  {
   "cell_type": "code",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
202
   "execution_count": null,
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
203
   "id": "58e3062c",
204
   "metadata": {},
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
205
   "outputs": [],
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
206
   "source": [
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
207
    "probs = sigmoid(output_mask)\n",
208
    "full_mask = probs > 0.996\n",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
209
    "plot_img_and_mask(imPrint, full_mask)"
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
210
   ]
211
  },
212
213
214
215
216
217
218
  {
   "cell_type": "markdown",
   "id": "6126df0b",
   "metadata": {},
   "source": [
    "<b>NOTE:</b> The model weights utilized here are trained by using car images with plain backgrounds. The imperfect result on a \"real-world\" image as shown above is expected. To get a better result fine-tuning the model on a dataset of real-world examples is recommended. "
   ]
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
Cagri Eryilmaz's avatar
Cagri Eryilmaz committed
236
   "pygments_lexer": "ipython3"
237
238
239
240
241
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}