resnet50_inference.ipynb 10.6 KB
Newer Older
turneram's avatar
turneram committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Resnet50 Inference\n",
    "\n",
    "## Description\n",
    "This example performs inference on a short wildlife video using a Resnet50 V2 model that has been pre-trained on imagenet data. The labels used for each class are simplified for readability, but still reflect the correct index-label pairs in official use. "
   ]
  },
  {
   "cell_type": "code",
15
   "execution_count": null,
turneram's avatar
turneram committed
16
17
18
   "metadata": {},
   "outputs": [],
   "source": [
19
20
21
    "!pip install --upgrade pip\n",
    "!pip install opencv-python==4.1.2.30\n",
    "!pip install matplotlib\n",
turneram's avatar
turneram committed
22
    "import numpy as np\n",
23
    "from matplotlib import pyplot as plt \n",
turneram's avatar
turneram committed
24
25
26
27
28
29
30
31
32
33
34
35
36
    "import cv2\n",
    "import json\n",
    "import time\n",
    "import os.path\n",
    "from os import path \n",
    "import sys"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Importing MIGraphX Library\n",
37
38
    "Sometimes the PYTHONPATH variable is not set during installation of MIGraphX. \n",
    "If your receive a \"Module Not Found\" error when trying to `import migraphx` in your own application, try running:\n",
turneram's avatar
turneram committed
39
40
41
    "```\n",
    "$ export PYTHONPATH=/opt/rocm/lib:$PYTHONPATH\n",
    "```\n",
42
43
44
45
46
47
    "For this example, the library will be added to the kernel's sys.path.\n",
    "\n",
    "If you receive \"cannot open shared object file: No such file or directory\" , please make sure `/opt/rocm/lib` is included in $LD_LIBRARY_PATH\n",
    "```\n",
    " cannot open shared object file: No such file or directory\n",
    "```"
turneram's avatar
turneram committed
48
49
50
51
   ]
  },
  {
   "cell_type": "code",
52
   "execution_count": null,
turneram's avatar
turneram committed
53
54
55
56
57
58
59
60
61
62
   "metadata": {},
   "outputs": [],
   "source": [
    "migx_lib_path = \"/opt/rocm/lib\"\n",
    "if migx_lib_path not in sys.path:\n",
    "    sys.path.append(migx_lib_path)"
   ]
  },
  {
   "cell_type": "code",
63
   "execution_count": null,
turneram's avatar
turneram committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
   "metadata": {},
   "outputs": [],
   "source": [
    "import migraphx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If this is your first time running this example, you will need to dowload the model and sample video.\n",
    "\n",
    "The following cell will ask you for your sudo password and then install/update the package `youtube-dl` if necessary. It will then use that tool to download the sample video."
   ]
  },
  {
   "cell_type": "code",
81
   "execution_count": null,
turneram's avatar
turneram committed
82
   "metadata": {},
83
   "outputs": [],
turneram's avatar
turneram committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
   "source": [
    "if not path.exists(\"./sample_vid.mp4\"):\n",
    "    import getpass\n",
    "    import os\n",
    "    password = getpass.getpass()\n",
    "    command = \"sudo -H -S pip install --upgrade youtube-dl\"\n",
    "    os.system('echo %s | %s' % (password, command))\n",
    "    !youtube-dl https://youtu.be/TkqYmvH_XVs \n",
    "    !mv sample_vid-TkqYmvH_XVs.mp4 sample_vid.mp4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following will download the resnet50 v2 model from ONNX's model zoo."
   ]
  },
  {
   "cell_type": "code",
104
   "execution_count": null,
turneram's avatar
turneram committed
105
   "metadata": {},
106
   "outputs": [],
turneram's avatar
turneram committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
   "source": [
    "if not path.exists(\"./resnet50.onnx\"):\n",
    "    !wget https://github.com/onnx/models/blob/master/vision/classification/resnet/model/resnet50-v2-7.onnx?raw=true\n",
    "    !mv 'resnet50-v2-7.onnx?raw=true' resnet50.onnx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load the simplified imagenet labels."
   ]
  },
  {
   "cell_type": "code",
122
   "execution_count": null,
turneram's avatar
turneram committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('imagenet_simple_labels.json') as json_data:\n",
    "    labels = json.load(json_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model and Video Capture Setup\n",
    "\n",
    "The ONNX graph that is loaded by `parse_onnx()` is a generalized representation that must be compiled for a specific target before it can be executed. For this example, using the target \"gpu\" is recommended. "
   ]
  },
  {
   "cell_type": "code",
141
   "execution_count": null,
turneram's avatar
turneram committed
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
   "metadata": {},
   "outputs": [],
   "source": [
    "model = migraphx.parse_onnx(\"resnet50.onnx\")\n",
    "model.compile(migraphx.get_target(\"gpu\"))\n",
    "model.print()     # Printed in terminal \n",
    "cap = cv2.VideoCapture(\"sample_vid.mp4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pre-Processing Video Frames\n",
    "Resnet50 requires some preprocessing of video frames before it can run inference. \n",
    "\n",
    "The model will expect an NCHW tensor with the shape {1, 3, 224, 224} and the values loaded into a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first step is to square up the dimensions of the original image by cropping the longer of the two to the size of the shorter dimension. This will help to avoid any stretching or compressing of the input image.\n",
    "Then the image can be scaled up or down to the desired resolution of 224x224."
   ]
  },
  {
   "cell_type": "code",
171
   "execution_count": null,
turneram's avatar
turneram committed
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
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_nxn(image, n):\n",
    "    width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n",
    "    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n",
    "    if height > width:\n",
    "        dif = height - width\n",
    "        bar = dif // 2 \n",
    "        square = image[(bar + (dif % 2)):(height - bar),:]\n",
    "        return cv2.resize(square, (n, n))\n",
    "    elif width > height:\n",
    "        dif = width - height\n",
    "        bar = dif // 2\n",
    "        square = image[:,(bar + (dif % 2)):(width - bar)]\n",
    "        return cv2.resize(square, (n, n))\n",
    "    else:\n",
    "        return cv2.resize(image, (n, n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that the image data has the correct dimensions, the values can be normalized as described above."
   ]
  },
  {
   "cell_type": "code",
201
   "execution_count": null,
turneram's avatar
turneram committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(img_data):\n",
    "    mean_vec = np.array([0.485, 0.456, 0.406])\n",
    "    stddev_vec = np.array([0.229, 0.224, 0.225])\n",
    "    norm_img_data = np.zeros(img_data.shape).astype('float32')\n",
    "    for i in range(img_data.shape[0]):  \n",
    "        norm_img_data[i,:,:] = (img_data[i,:,:]/255 - mean_vec[i]) / stddev_vec[i]\n",
    "    return norm_img_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run Inference on Single Frame\n",
    "\n",
    "The above pre-processing functions can now be applied to individual video frames and the data can be passed to the model for evaluation. "
   ]
  },
  {
   "cell_type": "code",
225
   "execution_count": null,
turneram's avatar
turneram committed
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
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict_class(frame) -> int:\n",
    "    # Crop and resize original image\n",
    "    cropped = make_nxn(frame, 224)\n",
    "    # Convert from HWC to CHW\n",
    "    chw = cropped.transpose(2,0,1)\n",
    "    # Apply normalization\n",
    "    pp = preprocess(chw)\n",
    "    # Add singleton dimension (CHW to NCHW)\n",
    "    data = np.expand_dims(pp.astype('float32'),0)\n",
    "    # Run the model\n",
    "    results = model.run({'data':data})\n",
    "    # Extract the index of the top prediction\n",
    "    res_npa = np.array(results[0])\n",
    "    return np.argmax(res_npa)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Inference Loop over Full Video\n",
    "\n",
251
    "Now everything is in place so that we can run inference on each frame of the input video. The video will be played and the predicted label will be displayed on top of each frame. If you are working on headless server, please execute the following cell."
turneram's avatar
turneram committed
252
253
254
255
   ]
  },
  {
   "cell_type": "code",
256
   "execution_count": null,
turneram's avatar
turneram committed
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
   "metadata": {},
   "outputs": [],
   "source": [
    "while (cap.isOpened()):\n",
    "    start = time.perf_counter()\n",
    "    ret, frame = cap.read()\n",
    "    if not ret: break\n",
    "    \n",
    "    top_prediction = predict_class(frame)\n",
    "    \n",
    "    end = time.perf_counter()\n",
    "    fps = 1 / (end - start)\n",
    "    fps_str = f\"Frames per second: {fps:0.1f}\"\n",
    "    label_str = \"Top prediction: {}\".format(labels[top_prediction])\n",
    "\n",
    "    labeled = cv2.putText(frame, \n",
    "                          label_str, \n",
    "                          (50, 50), \n",
    "                          cv2.FONT_HERSHEY_SIMPLEX, \n",
    "                          2, \n",
    "                          (255, 255, 255), \n",
    "                          3, \n",
    "                          cv2.LINE_AA)\n",
    "    labeled = cv2.putText(labeled, \n",
    "                          fps_str, \n",
    "                          (50, 1060), \n",
    "                          cv2.FONT_HERSHEY_SIMPLEX, \n",
    "                          2, \n",
    "                          (255, 255, 255), \n",
    "                          3, \n",
    "                          cv2.LINE_AA)\n",
    "    cv2.imshow(\"Resnet50 Inference\", labeled)\n",
    "\n",
    "    if cv2.waitKey(1) & 0xFF == ord('q'): # 'q' to quit\n",
    "        break\n",
    "\n",
    "cap.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
297
298
299
300
301
302
303
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If script is run on a headless server where .imshow() experiences problems, the following cell for histogram can be run to verify functionalty:"
   ]
  },
turneram's avatar
turneram committed
304
305
306
307
308
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
   "source": [
    "output_labels = []\n",
    "while (cap.isOpened()):\n",
    "    start = time.perf_counter()\n",
    "    ret, frame = cap.read()\n",
    "    if not ret: break\n",
    "    \n",
    "    top_prediction = predict_class(frame)\n",
    "    output_labels.append(labels[top_prediction])\n",
    "\n",
    "cap.release()\n",
    "output_labels = np.array(output_labels)\n",
    "plt.hist(output_labels) \n",
    "plt.xticks(rotation = 90)\n",
    "plt.show()"
   ]
turneram's avatar
turneram committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
  }
 ],
 "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",
   "pygments_lexer": "ipython3",
343
   "version": "3.6.9"
turneram's avatar
turneram committed
344
345
346
347
348
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}