Spaces:
Runtime error
Runtime error
File size: 22,952 Bytes
db5855f |
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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Live Object Detection with OpenVINO™\n",
"\n",
"This notebook demonstrates live object detection with OpenVINO, using the [SSDLite MobileNetV2](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/ssdlite_mobilenet_v2) from [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). Final part of this notebook shows live inference results from a webcam. Additionally, you can also upload a video file.\n",
"\n",
"> **NOTE**: To use this notebook with a webcam, you need to run the notebook on a computer with a webcam. If you run the notebook on a server, the webcam will not work. However, you can still do inference on a video.\n",
"\n",
"\n",
"#### Table of contents:\n",
"\n",
"- [Preparation](#Preparation)\n",
" - [Install requirements](#Install-requirements)\n",
" - [Imports](#Imports)\n",
"- [The Model](#The-Model)\n",
" - [Download the Model](#Download-the-Model)\n",
" - [Convert the Model](#Convert-the-Model)\n",
" - [Load the Model](#Load-the-Model)\n",
"- [Processing](#Processing)\n",
" - [Process Results](#Process-Results)\n",
" - [Main Processing Function](#Main-Processing-Function)\n",
"- [Run](#Run)\n",
" - [Run Live Object Detection](#Run-Live-Object-Detection)\n",
"- [References](#References)\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preparation\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"### Install requirements\n",
"[back to top ⬆️](#Table-of-contents:)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install -q \"openvino-dev>=2024.0.0\"\n",
"%pip install -q tensorflow\n",
"%pip install -q opencv-python requests tqdm\n",
"\n",
"# Fetch `notebook_utils` module\n",
"import requests\n",
"\n",
"r = requests.get(\n",
" url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
")\n",
"\n",
"open(\"notebook_utils.py\", \"w\").write(r.text)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Imports\n",
"[back to top ⬆️](#Table-of-contents:)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import collections\n",
"import tarfile\n",
"import time\n",
"from pathlib import Path\n",
"\n",
"import cv2\n",
"import numpy as np\n",
"from IPython import display\n",
"import openvino as ov\n",
"from openvino.tools.mo.front import tf as ov_tf_front\n",
"from openvino.tools import mo\n",
"\n",
"import notebook_utils as utils"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"### Download the Model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Use the `download_file`, a function from the `notebook_utils` file. It automatically creates a directory structure and downloads the selected model. This step is skipped if the package is already downloaded and unpacked. The chosen model comes from the public directory, which means it must be converted into OpenVINO Intermediate Representation (OpenVINO IR).\n",
"\n",
"> **NOTE**: Using a model other than `ssdlite_mobilenet_v2` may require different conversion parameters as well as pre- and post-processing."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A directory where the model will be downloaded.\n",
"base_model_dir = Path(\"model\")\n",
"\n",
"# The name of the model from Open Model Zoo\n",
"model_name = \"ssdlite_mobilenet_v2\"\n",
"\n",
"archive_name = Path(f\"{model_name}_coco_2018_05_09.tar.gz\")\n",
"model_url = f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/public/2022.1/{model_name}/{archive_name}\"\n",
"\n",
"# Download the archive\n",
"downloaded_model_path = base_model_dir / archive_name\n",
"if not downloaded_model_path.exists():\n",
" utils.download_file(model_url, downloaded_model_path.name, downloaded_model_path.parent)\n",
"\n",
"# Unpack the model\n",
"tf_model_path = base_model_dir / archive_name.with_suffix(\"\").stem / \"frozen_inference_graph.pb\"\n",
"if not tf_model_path.exists():\n",
" with tarfile.open(downloaded_model_path) as file:\n",
" file.extractall(base_model_dir)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Convert the Model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"The pre-trained model is in TensorFlow format. To use it with OpenVINO, convert it to OpenVINO IR format, using [Model Conversion API](https://docs.openvino.ai/2024/openvino-workflow/model-preparation.html) (`mo.convert_model` function). If the model has been already converted, this step is skipped."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [],
"source": [
"precision = \"FP16\"\n",
"# The output path for the conversion.\n",
"converted_model_path = Path(\"model\") / f\"{model_name}_{precision.lower()}.xml\"\n",
"\n",
"# Convert it to IR if not previously converted\n",
"trans_config_path = Path(ov_tf_front.__file__).parent / \"ssd_v2_support.json\"\n",
"if not converted_model_path.exists():\n",
" ov_model = mo.convert_model(\n",
" tf_model_path,\n",
" compress_to_fp16=(precision == \"FP16\"),\n",
" transformations_config=trans_config_path,\n",
" tensorflow_object_detection_api_pipeline_config=tf_model_path.parent / \"pipeline.config\",\n",
" reverse_input_channels=True,\n",
" )\n",
" ov.save_model(ov_model, converted_model_path)\n",
" del ov_model"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load the Model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Only a few lines of code are required to run the model. First, initialize OpenVINO Runtime. Then, read the network architecture and model weights from the `.bin` and `.xml` files to compile for the desired device. If you choose `GPU` you need to wait for a while, as the startup time is much longer than in the case of `CPU`.\n",
"\n",
"There is a possibility to let OpenVINO decide which hardware offers the best performance. For that purpose, just use `AUTO`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import ipywidgets as widgets\n",
"\n",
"core = ov.Core()\n",
"\n",
"device = widgets.Dropdown(\n",
" options=core.available_devices + [\"AUTO\"],\n",
" value=\"AUTO\",\n",
" description=\"Device:\",\n",
" disabled=False,\n",
")\n",
"\n",
"device"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Read the network and corresponding weights from a file.\n",
"model = core.read_model(model=converted_model_path)\n",
"# Compile the model for CPU (you can choose manually CPU, GPU etc.)\n",
"# or let the engine choose the best available device (AUTO).\n",
"compiled_model = core.compile_model(model=model, device_name=device.value)\n",
"\n",
"# Get the input and output nodes.\n",
"input_layer = compiled_model.input(0)\n",
"output_layer = compiled_model.output(0)\n",
"\n",
"# Get the input size.\n",
"height, width = list(input_layer.shape)[1:3]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Input and output layers have the names of the input node and output node respectively. In the case of SSDLite MobileNetV2, there is 1 input and 1 output."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input_layer.any_name, output_layer.any_name"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Processing\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"### Process Results\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"First, list all available classes and create colors for them. Then, in the post-process stage, transform boxes with normalized coordinates `[0, 1]` into boxes with pixel coordinates `[0, image_size_in_px]`. Afterward, use [non-maximum suppression](https://paperswithcode.com/method/non-maximum-suppression) to reject overlapping detections and those below the probability threshold (0.5). Finally, draw boxes and labels inside them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n",
"classes = [\n",
" \"background\",\n",
" \"person\",\n",
" \"bicycle\",\n",
" \"car\",\n",
" \"motorcycle\",\n",
" \"airplane\",\n",
" \"bus\",\n",
" \"train\",\n",
" \"truck\",\n",
" \"boat\",\n",
" \"traffic light\",\n",
" \"fire hydrant\",\n",
" \"street sign\",\n",
" \"stop sign\",\n",
" \"parking meter\",\n",
" \"bench\",\n",
" \"bird\",\n",
" \"cat\",\n",
" \"dog\",\n",
" \"horse\",\n",
" \"sheep\",\n",
" \"cow\",\n",
" \"elephant\",\n",
" \"bear\",\n",
" \"zebra\",\n",
" \"giraffe\",\n",
" \"hat\",\n",
" \"backpack\",\n",
" \"umbrella\",\n",
" \"shoe\",\n",
" \"eye glasses\",\n",
" \"handbag\",\n",
" \"tie\",\n",
" \"suitcase\",\n",
" \"frisbee\",\n",
" \"skis\",\n",
" \"snowboard\",\n",
" \"sports ball\",\n",
" \"kite\",\n",
" \"baseball bat\",\n",
" \"baseball glove\",\n",
" \"skateboard\",\n",
" \"surfboard\",\n",
" \"tennis racket\",\n",
" \"bottle\",\n",
" \"plate\",\n",
" \"wine glass\",\n",
" \"cup\",\n",
" \"fork\",\n",
" \"knife\",\n",
" \"spoon\",\n",
" \"bowl\",\n",
" \"banana\",\n",
" \"apple\",\n",
" \"sandwich\",\n",
" \"orange\",\n",
" \"broccoli\",\n",
" \"carrot\",\n",
" \"hot dog\",\n",
" \"pizza\",\n",
" \"donut\",\n",
" \"cake\",\n",
" \"chair\",\n",
" \"couch\",\n",
" \"potted plant\",\n",
" \"bed\",\n",
" \"mirror\",\n",
" \"dining table\",\n",
" \"window\",\n",
" \"desk\",\n",
" \"toilet\",\n",
" \"door\",\n",
" \"tv\",\n",
" \"laptop\",\n",
" \"mouse\",\n",
" \"remote\",\n",
" \"keyboard\",\n",
" \"cell phone\",\n",
" \"microwave\",\n",
" \"oven\",\n",
" \"toaster\",\n",
" \"sink\",\n",
" \"refrigerator\",\n",
" \"blender\",\n",
" \"book\",\n",
" \"clock\",\n",
" \"vase\",\n",
" \"scissors\",\n",
" \"teddy bear\",\n",
" \"hair drier\",\n",
" \"toothbrush\",\n",
" \"hair brush\",\n",
"]\n",
"\n",
"# Colors for the classes above (Rainbow Color Map).\n",
"colors = cv2.applyColorMap(\n",
" src=np.arange(0, 255, 255 / len(classes), dtype=np.float32).astype(np.uint8),\n",
" colormap=cv2.COLORMAP_RAINBOW,\n",
").squeeze()\n",
"\n",
"\n",
"def process_results(frame, results, thresh=0.6):\n",
" # The size of the original frame.\n",
" h, w = frame.shape[:2]\n",
" # The 'results' variable is a [1, 1, 100, 7] tensor.\n",
" results = results.squeeze()\n",
" boxes = []\n",
" labels = []\n",
" scores = []\n",
" for _, label, score, xmin, ymin, xmax, ymax in results:\n",
" # Create a box with pixels coordinates from the box with normalized coordinates [0,1].\n",
" boxes.append(tuple(map(int, (xmin * w, ymin * h, (xmax - xmin) * w, (ymax - ymin) * h))))\n",
" labels.append(int(label))\n",
" scores.append(float(score))\n",
"\n",
" # Apply non-maximum suppression to get rid of many overlapping entities.\n",
" # See https://paperswithcode.com/method/non-maximum-suppression\n",
" # This algorithm returns indices of objects to keep.\n",
" indices = cv2.dnn.NMSBoxes(bboxes=boxes, scores=scores, score_threshold=thresh, nms_threshold=0.6)\n",
"\n",
" # If there are no boxes.\n",
" if len(indices) == 0:\n",
" return []\n",
"\n",
" # Filter detected objects.\n",
" return [(labels[idx], scores[idx], boxes[idx]) for idx in indices.flatten()]\n",
"\n",
"\n",
"def draw_boxes(frame, boxes):\n",
" for label, score, box in boxes:\n",
" # Choose color for the label.\n",
" color = tuple(map(int, colors[label]))\n",
" # Draw a box.\n",
" x2 = box[0] + box[2]\n",
" y2 = box[1] + box[3]\n",
" cv2.rectangle(img=frame, pt1=box[:2], pt2=(x2, y2), color=color, thickness=3)\n",
"\n",
" # Draw a label name inside the box.\n",
" cv2.putText(\n",
" img=frame,\n",
" text=f\"{classes[label]} {score:.2f}\",\n",
" org=(box[0] + 10, box[1] + 30),\n",
" fontFace=cv2.FONT_HERSHEY_COMPLEX,\n",
" fontScale=frame.shape[1] / 1000,\n",
" color=color,\n",
" thickness=1,\n",
" lineType=cv2.LINE_AA,\n",
" )\n",
"\n",
" return frame"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Main Processing Function\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Run object detection on the specified source. Either a webcam or a video file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Main processing function to run object detection.\n",
"def run_object_detection(source=0, flip=False, use_popup=False, skip_first_frames=0):\n",
" player = None\n",
" try:\n",
" # Create a video player to play with target fps.\n",
" player = utils.VideoPlayer(source=source, flip=flip, fps=30, skip_first_frames=skip_first_frames)\n",
" # Start capturing.\n",
" player.start()\n",
" if use_popup:\n",
" title = \"Press ESC to Exit\"\n",
" cv2.namedWindow(winname=title, flags=cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)\n",
"\n",
" processing_times = collections.deque()\n",
" while True:\n",
" # Grab the frame.\n",
" frame = player.next()\n",
" if frame is None:\n",
" print(\"Source ended\")\n",
" break\n",
" # If the frame is larger than full HD, reduce size to improve the performance.\n",
" scale = 1280 / max(frame.shape)\n",
" if scale < 1:\n",
" frame = cv2.resize(\n",
" src=frame,\n",
" dsize=None,\n",
" fx=scale,\n",
" fy=scale,\n",
" interpolation=cv2.INTER_AREA,\n",
" )\n",
"\n",
" # Resize the image and change dims to fit neural network input.\n",
" input_img = cv2.resize(src=frame, dsize=(width, height), interpolation=cv2.INTER_AREA)\n",
" # Create a batch of images (size = 1).\n",
" input_img = input_img[np.newaxis, ...]\n",
"\n",
" # Measure processing time.\n",
"\n",
" start_time = time.time()\n",
" # Get the results.\n",
" results = compiled_model([input_img])[output_layer]\n",
" stop_time = time.time()\n",
" # Get poses from network results.\n",
" boxes = process_results(frame=frame, results=results)\n",
"\n",
" # Draw boxes on a frame.\n",
" frame = draw_boxes(frame=frame, boxes=boxes)\n",
"\n",
" processing_times.append(stop_time - start_time)\n",
" # Use processing times from last 200 frames.\n",
" if len(processing_times) > 200:\n",
" processing_times.popleft()\n",
"\n",
" _, f_width = frame.shape[:2]\n",
" # Mean processing time [ms].\n",
" processing_time = np.mean(processing_times) * 1000\n",
" fps = 1000 / processing_time\n",
" cv2.putText(\n",
" img=frame,\n",
" text=f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n",
" org=(20, 40),\n",
" fontFace=cv2.FONT_HERSHEY_COMPLEX,\n",
" fontScale=f_width / 1000,\n",
" color=(0, 0, 255),\n",
" thickness=1,\n",
" lineType=cv2.LINE_AA,\n",
" )\n",
"\n",
" # Use this workaround if there is flickering.\n",
" if use_popup:\n",
" cv2.imshow(winname=title, mat=frame)\n",
" key = cv2.waitKey(1)\n",
" # escape = 27\n",
" if key == 27:\n",
" break\n",
" else:\n",
" # Encode numpy array to jpg.\n",
" _, encoded_img = cv2.imencode(ext=\".jpg\", img=frame, params=[cv2.IMWRITE_JPEG_QUALITY, 100])\n",
" # Create an IPython image.\n",
" i = display.Image(data=encoded_img)\n",
" # Display the image in this notebook.\n",
" display.clear_output(wait=True)\n",
" display.display(i)\n",
" # ctrl-c\n",
" except KeyboardInterrupt:\n",
" print(\"Interrupted\")\n",
" # any different error\n",
" except RuntimeError as e:\n",
" print(e)\n",
" finally:\n",
" if player is not None:\n",
" # Stop capturing.\n",
" player.stop()\n",
" if use_popup:\n",
" cv2.destroyAllWindows()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Run\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"### Run Live Object Detection\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Use a webcam as the video input. By default, the primary webcam is set with `source=0`. If you have multiple webcams, each one will be assigned a consecutive number starting at 0. Set `flip=True` when using a front-facing camera. Some web browsers, especially Mozilla Firefox, may cause flickering. If you experience flickering, set `use_popup=True`.\n",
"\n",
"> **NOTE**: To use this notebook with a webcam, you need to run the notebook on a computer with a webcam. If you run the notebook on a server (for example, Binder), the webcam will not work. Popup mode may not work if you run this notebook on a remote computer (for example, Binder).\n",
"\n",
"If you do not have a webcam, you can still run this demo with a video file. Any [format supported by OpenCV](https://docs.opencv.org/4.5.1/dd/d43/tutorial_py_video_display.html) will work.\n",
"\n",
"Run the object detection:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"USE_WEBCAM = False\n",
"\n",
"video_file = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/video/Coco%20Walking%20in%20Berkeley.mp4\"\n",
"cam_id = 0\n",
"\n",
"source = cam_id if USE_WEBCAM else video_file\n",
"\n",
"run_object_detection(source=source, flip=isinstance(source, int), use_popup=False)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## References\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"1. [SSDLite MobileNetV2](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/ssdlite_mobilenet_v2)\n",
"2. [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/)\n",
"3. [Non-Maximum Suppression](https://paperswithcode.com/method/non-maximum-suppression)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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",
"version": "3.8.10"
},
"openvino_notebooks": {
"imageUrl": "https://user-images.githubusercontent.com/4547501/141471665-82b28c86-cf64-4bfe-98b3-c314658f2d96.gif",
"tags": {
"categories": [
"Live Demos"
],
"libraries": [],
"other": [],
"tasks": [
"Object Detection"
]
}
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|