File size: 32,028 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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Person Tracking with OpenVINO™\n",
    "\n",
    "This notebook demonstrates live person tracking with OpenVINO: it reads frames from an input video sequence, detects people in the frames, uniquely identifies each one of them and tracks all of them until they leave the frame. We will use the [Deep SORT](https://arxiv.org/abs/1703.07402) algorithm to perform object tracking, an extension to SORT (Simple Online and Realtime Tracking).\n",
    "\n",
    "## Detection vs Tracking\n",
    "- In object detection, we detect an object in a frame, put a bounding box or a mask around it, and classify the object. Note that, the job of the detector ends here. It processes each frame independently and identifies numerous objects in that particular frame. \n",
    "- An object tracker on the other hand needs to track a particular object across the entire video. If the detector detects three cars in the frame, the object tracker has to identify the three separate detections and needs to track it across the subsequent frames (with the help of a unique ID).\n",
    "\n",
    "## Deep SORT\n",
    "[Deep SORT](https://arxiv.org/abs/1703.07402) can be defined as the tracking algorithm which tracks objects not only based on the velocity and motion of the object but also the appearance of the object.\n",
    "It is made of three key components which are as follows:\n",
    "![deepsort](https://user-images.githubusercontent.com/91237924/221744683-0042eff8-2c41-43b8-b3ad-b5929bafb60b.png)\n",
    "\n",
    "1. **Detection**\n",
    "\n",
    "   This is the first step in the tracking module. In this step, a deep learning model will be used to detect the objects in the frame that are to be tracked. These detections are then passed on to the next step.\n",
    "\n",
    "2. **Prediction**\n",
    "   \n",
    "   In this step, we use Kalman filter \\[1\\] framework to predict a target bounding box of each tracking object in the next frame. There are two states of prediction output: ```confirmed``` and ```unconfirmed```. A new track comes with a state of ```unconfirmed``` by default, and it can be turned into ```confirmed``` when a certain number of consecutive detections are matched with this new track. Meanwhile, if a matched track is missed over a specific time, it will be deleted as well.\n",
    "\n",
    "3. **Data association and update**\n",
    "   \n",
    "   Now, we have to match the target bounding box with the detected bounding box, and update track identities. A conventional way to solve the association between the predicted Kalman states and newly arrived measurements is to build an assignment problem with the Hungarian algorithm \\[2\\]. In this problem formulation, we integrate motion and appearance information through a combination of two appropriate metrics. The cost used for the first matching step is set as a combination of the Mahalanobis and the cosine distances. The [Mahalanobis distance](https://en.wikipedia.org/wiki/Mahalanobis_distance) is used to incorporate motion information and the cosine distance is used to calculate similarity between two objects. Cosine distance is a metric that helps the tracker recover identities in case of long-term occlusion and motion estimation also fails. For this purposes, a reidentification model will be implemented to produce a vector in high-dimensional space that represents the appearance of the object. Using these simple things can make the tracker even more powerful and accurate.\n",
    "\n",
    "   In the second matching stage, we will run intersection over union(IOU) association as proposed in the original SORT algorithm \\[3\\] on the set of unconfirmed and unmatched tracks from the previous step. If the IOU of detection and target is less than a certain threshold value called `IOUmin` then that assignment is rejected. This helps to account for sudden appearance changes, for example, due to partial occlusion with static scene geometry, and to increase robustness against erroneous.\n",
    "   \n",
    "   When detection result is associated with a target, the detected bounding box is used to update the target state.\n",
    "\n",
    "---\n",
    "\n",
    "\\[1\\] R. Kalman, \"A New Approach to Linear Filtering and Prediction Problems\", Journal of Basic Engineering, vol. 82, no. Series D, pp. 35-45, 1960.\n",
    "\n",
    "\\[2\\] H. W. Kuhn, \"The Hungarian method for the assignment problem\", Naval Research Logistics Quarterly, vol. 2, pp. 83-97, 1955.\n",
    "\n",
    "\\[3\\] A. Bewley, G. Zongyuan, F. Ramos, and B. Upcroft, “Simple online and realtime tracking,” in ICIP, 2016, pp. 3464–3468."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Imports](#Imports)\n",
    "- [Download the Model](#Download-the-Model)\n",
    "- [Load model](#Load-model)\n",
    "    - [Select inference device](#Select-inference-device)\n",
    "- [Data Processing](#Data-Processing)\n",
    "- [Test person reidentification model](#Test-person-reidentification-model)\n",
    "    - [Visualize data](#Visualize-data)\n",
    "    - [Compare two persons](#Compare-two-persons)\n",
    "- [Main Processing Function](#Main-Processing-Function)\n",
    "- [Run](#Run)\n",
    "    - [Initialize tracker](#Initialize-tracker)\n",
    "    - [Run Live Person Tracking](#Run-Live-Person-Tracking)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import platform\n",
    "\n",
    "%pip install -q \"openvino-dev>=2024.0.0\"\n",
    "%pip install -q opencv-python requests scipy tqdm\n",
    "\n",
    "if platform.system() != \"Windows\":\n",
    "    %pip install -q \"matplotlib>=3.4\"\n",
    "else:\n",
    "    %pip install -q \"matplotlib>=3.4,<3.7\""
   ]
  },
  {
   "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",
    "from pathlib import Path\n",
    "import time\n",
    "\n",
    "import numpy as np\n",
    "import cv2\n",
    "from IPython import display\n",
    "import matplotlib.pyplot as plt\n",
    "import openvino as ov"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import local modules\n",
    "\n",
    "if not Path(\"./notebook_utils.py\").exists():\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)\n",
    "\n",
    "import notebook_utils as utils\n",
    "from deepsort_utils.tracker import Tracker\n",
    "from deepsort_utils.nn_matching import NearestNeighborDistanceMetric\n",
    "from deepsort_utils.detection import (\n",
    "    Detection,\n",
    "    compute_color_for_labels,\n",
    "    xywh_to_xyxy,\n",
    "    xywh_to_tlwh,\n",
    "    tlwh_to_xyxy,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download the Model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "We will use pre-trained models from OpenVINO's [Open Model Zoo](https://docs.openvino.ai/2024/documentation/legacy-features/model-zoo.html) to start the test.\n",
    "\n",
    "Use `omz_downloader`, which is a command-line tool from the `openvino-dev` package. It automatically creates a directory structure and downloads the selected model. This step is skipped if the model is already downloaded. The selected model comes from the public directory, which means it must be converted into OpenVINO Intermediate Representation (OpenVINO IR).\n",
    "\n",
    "> **NOTE**: Using a model outside the list can require different pre- and post-processing.\n",
    "\n",
    "In this case, [person detection model]( https://docs.openvino.ai/2024/omz_models_model_person_detection_0202.html) is deployed to detect the person in each frame of the video, and [reidentification model]( https://docs.openvino.ai/2024/omz_models_model_person_reidentification_retail_0287.html) is used to output embedding vector to match a pair of images of a person by the cosine distance.\n",
    "\n",
    "\n",
    "If you want to download another model (`person-detection-xxx` from [Object Detection Models list](https://docs.openvino.ai/2024/omz_models_group_intel.html#object-detection-models), `person-reidentification-retail-xxx` from [Reidentification Models list](https://docs.openvino.ai/2024/omz_models_group_intel.html#reidentification-models)), replace the name of the model in the code below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# A directory where the model will be downloaded.\n",
    "base_model_dir = \"model\"\n",
    "precision = \"FP16\"\n",
    "# The name of the model from Open Model Zoo\n",
    "detection_model_name = \"person-detection-0202\"\n",
    "\n",
    "download_command = (\n",
    "    f\"omz_downloader \" f\"--name {detection_model_name} \" f\"--precisions {precision} \" f\"--output_dir {base_model_dir} \" f\"--cache_dir {base_model_dir}\"\n",
    ")\n",
    "! $download_command\n",
    "\n",
    "detection_model_path = f\"model/intel/{detection_model_name}/{precision}/{detection_model_name}.xml\"\n",
    "\n",
    "\n",
    "reidentification_model_name = \"person-reidentification-retail-0287\"\n",
    "\n",
    "download_command = (\n",
    "    f\"omz_downloader \" f\"--name {reidentification_model_name} \" f\"--precisions {precision} \" f\"--output_dir {base_model_dir} \" f\"--cache_dir {base_model_dir}\"\n",
    ")\n",
    "! $download_command\n",
    "\n",
    "reidentification_model_path = f\"model/intel/{reidentification_model_name}/{precision}/{reidentification_model_name}.xml\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Define a common class for model loading and predicting.\n",
    "\n",
    "There are four main steps for OpenVINO model initialization, and they are required to run for only once before inference loop.\n",
    " 1. Initialize OpenVINO Runtime.\n",
    " 2. Read the network from `*.bin` and `*.xml` files (weights and architecture).\n",
    " 3. Compile the model for device.\n",
    " 4. Get input and output names of nodes.\n",
    "\n",
    "In this case, we can put them all in a class constructor function.\n",
    "\n",
    "To let OpenVINO automatically select the best device for inference just use `AUTO`. In most cases, the best device to use is `GPU` (better performance, but slightly longer startup time)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "core = ov.Core()\n",
    "\n",
    "\n",
    "class Model:\n",
    "    \"\"\"\n",

    "    This class represents a OpenVINO model object.\n",

    "\n",

    "    \"\"\"\n",
    "\n",
    "    def __init__(self, model_path, batchsize=1, device=\"AUTO\"):\n",
    "        \"\"\"\n",

    "        Initialize the model object\n",

    "\n",

    "        Parameters\n",

    "        ----------\n",

    "        model_path: path of inference model\n",

    "        batchsize: batch size of input data\n",

    "        device: device used to run inference\n",

    "        \"\"\"\n",
    "        self.model = core.read_model(model=model_path)\n",
    "        self.input_layer = self.model.input(0)\n",
    "        self.input_shape = self.input_layer.shape\n",
    "        self.height = self.input_shape[2]\n",
    "        self.width = self.input_shape[3]\n",
    "\n",
    "        for layer in self.model.inputs:\n",
    "            input_shape = layer.partial_shape\n",
    "            input_shape[0] = batchsize\n",
    "            self.model.reshape({layer: input_shape})\n",
    "        self.compiled_model = core.compile_model(model=self.model, device_name=device)\n",
    "        self.output_layer = self.compiled_model.output(0)\n",
    "\n",
    "    def predict(self, input):\n",
    "        \"\"\"\n",

    "        Run inference\n",

    "\n",

    "        Parameters\n",

    "        ----------\n",

    "        input: array of input data\n",

    "        \"\"\"\n",
    "        result = self.compiled_model(input)[self.output_layer]\n",
    "        return result"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select inference device\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "select device from dropdown list for running inference using OpenVINO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\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": [
    "detector = Model(detection_model_path, device=device.value)\n",
    "# since the number of detection object is uncertain, the input batch size of reid model should be dynamic\n",
    "extractor = Model(reidentification_model_path, -1, device.value)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Processing\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Data Processing includes data preprocess and postprocess functions.\n",
    "- Data preprocess function is used to change the layout and shape of input data, according to requirement of the network input format.\n",
    "- Data postprocess function is used to extract the useful information from network's original output and visualize it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(frame, height, width):\n",
    "    \"\"\"\n",

    "    Preprocess a single image\n",

    "\n",

    "    Parameters\n",

    "    ----------\n",

    "    frame: input frame\n",

    "    height: height of model input data\n",

    "    width: width of model input data\n",

    "    \"\"\"\n",
    "    resized_image = cv2.resize(frame, (width, height))\n",
    "    resized_image = resized_image.transpose((2, 0, 1))\n",
    "    input_image = np.expand_dims(resized_image, axis=0).astype(np.float32)\n",
    "    return input_image\n",
    "\n",
    "\n",
    "def batch_preprocess(img_crops, height, width):\n",
    "    \"\"\"\n",

    "    Preprocess batched images\n",

    "\n",

    "    Parameters\n",

    "    ----------\n",

    "    img_crops: batched input images\n",

    "    height: height of model input data\n",

    "    width: width of model input data\n",

    "    \"\"\"\n",
    "    img_batch = np.concatenate([preprocess(img, height, width) for img in img_crops], axis=0)\n",
    "    return img_batch\n",
    "\n",
    "\n",
    "def process_results(h, w, results, thresh=0.5):\n",
    "    \"\"\"\n",

    "    postprocess detection results\n",

    "\n",

    "    Parameters\n",

    "    ----------\n",

    "    h, w: original height and width of input image\n",

    "    results: raw detection network output\n",

    "    thresh: threshold for low confidence filtering\n",

    "    \"\"\"\n",
    "    # The 'results' variable is a [1, 1, N, 7] tensor.\n",
    "    detections = results.reshape(-1, 7)\n",
    "    boxes = []\n",
    "    labels = []\n",
    "    scores = []\n",
    "    for i, detection in enumerate(detections):\n",
    "        _, label, score, xmin, ymin, xmax, ymax = detection\n",
    "        # Filter detected objects.\n",
    "        if score > thresh:\n",
    "            # Create a box with pixels coordinates from the box with normalized coordinates [0,1].\n",
    "            boxes.append(\n",
    "                [\n",
    "                    (xmin + xmax) / 2 * w,\n",
    "                    (ymin + ymax) / 2 * h,\n",
    "                    (xmax - xmin) * w,\n",
    "                    (ymax - ymin) * h,\n",
    "                ]\n",
    "            )\n",
    "            labels.append(int(label))\n",
    "            scores.append(float(score))\n",
    "\n",
    "    if len(boxes) == 0:\n",
    "        boxes = np.array([]).reshape(0, 4)\n",
    "        scores = np.array([])\n",
    "        labels = np.array([])\n",
    "    return np.array(boxes), np.array(scores), np.array(labels)\n",
    "\n",
    "\n",
    "def draw_boxes(img, bbox, identities=None):\n",
    "    \"\"\"\n",

    "    Draw bounding box in original image\n",

    "\n",

    "    Parameters\n",

    "    ----------\n",

    "    img: original image\n",

    "    bbox: coordinate of bounding box\n",

    "    identities: identities IDs\n",

    "    \"\"\"\n",
    "    for i, box in enumerate(bbox):\n",
    "        x1, y1, x2, y2 = [int(i) for i in box]\n",
    "        # box text and bar\n",
    "        id = int(identities[i]) if identities is not None else 0\n",
    "        color = compute_color_for_labels(id)\n",
    "        label = \"{}{:d}\".format(\"\", id)\n",
    "        t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]\n",
    "        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)\n",
    "        cv2.rectangle(img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1)\n",
    "        cv2.putText(\n",
    "            img,\n",
    "            label,\n",
    "            (x1, y1 + t_size[1] + 4),\n",
    "            cv2.FONT_HERSHEY_PLAIN,\n",
    "            1.6,\n",
    "            [255, 255, 255],\n",
    "            2,\n",
    "        )\n",
    "    return img\n",
    "\n",
    "\n",
    "def cosin_metric(x1, x2):\n",
    "    \"\"\"\n",

    "    Calculate the consin distance of two vector\n",

    "\n",

    "    Parameters\n",

    "    ----------\n",

    "    x1, x2: input vectors\n",

    "    \"\"\"\n",
    "    return np.dot(x1, x2) / (np.linalg.norm(x1) * np.linalg.norm(x2))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test person reidentification model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The reidentification network outputs a blob with the `(1, 256)` shape named `reid_embedding`, which can be compared with other descriptors using the cosine distance."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualize data\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "base_file_link = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/image/person_\"\n",
    "image_indices = [\"1_1.png\", \"1_2.png\", \"2_1.png\"]\n",
    "image_paths = [utils.download_file(base_file_link + image_index, directory=\"data\") for image_index in image_indices]\n",
    "image1, image2, image3 = [cv2.cvtColor(cv2.imread(str(image_path)), cv2.COLOR_BGR2RGB) for image_path in image_paths]\n",
    "\n",
    "# Define titles with images.\n",
    "data = {\"Person 1\": image1, \"Person 2\": image2, \"Person 3\": image3}\n",
    "\n",
    "# Create a subplot to visualize images.\n",
    "fig, axs = plt.subplots(1, len(data.items()), figsize=(5, 5))\n",
    "\n",
    "# Fill the subplot.\n",
    "for ax, (name, image) in zip(axs, data.items()):\n",
    "    ax.axis(\"off\")\n",
    "    ax.set_title(name)\n",
    "    ax.imshow(image)\n",
    "\n",
    "# Display an image.\n",
    "plt.show(fig)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compare two persons\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Metric parameters\n",
    "MAX_COSINE_DISTANCE = 0.6  # threshold of matching object\n",
    "input_data = [image2, image3]\n",
    "img_batch = batch_preprocess(input_data, extractor.height, extractor.width)\n",
    "features = extractor.predict(img_batch)\n",
    "sim = cosin_metric(features[0], features[1])\n",
    "if sim >= 1 - MAX_COSINE_DISTANCE:\n",
    "    print(f\"Same person (confidence: {sim})\")\n",
    "else:\n",
    "    print(f\"Different person (confidence: {sim})\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Main Processing Function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run person tracking on the specified source. Either a webcam feed or a video file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main processing function to run person tracking.\n",
    "def run_person_tracking(source=0, flip=False, use_popup=False, skip_first_frames=0):\n",
    "    \"\"\"\n",

    "    Main function to run the person tracking:\n",

    "    1. Create a video player to play with target fps (utils.VideoPlayer).\n",

    "    2. Prepare a set of frames for person tracking.\n",

    "    3. Run AI inference for person tracking.\n",

    "    4. Visualize the results.\n",

    "\n",

    "    Parameters:\n",

    "    ----------\n",

    "        source: The webcam number to feed the video stream with primary webcam set to \"0\", or the video path.\n",

    "        flip: To be used by VideoPlayer function for flipping capture image.\n",

    "        use_popup: False for showing encoded frames over this notebook, True for creating a popup window.\n",

    "        skip_first_frames: Number of frames to skip at the beginning of the video.\n",

    "    \"\"\"\n",
    "    player = None\n",
    "    try:\n",
    "        # Create a video player to play with target fps.\n",
    "        player = utils.VideoPlayer(\n",
    "            source=source,\n",
    "            size=(700, 450),\n",
    "            flip=flip,\n",
    "            fps=24,\n",
    "            skip_first_frames=skip_first_frames,\n",
    "        )\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",
    "\n",
    "            # Resize the image and change dims to fit neural network input.\n",
    "            h, w = frame.shape[:2]\n",
    "            input_image = preprocess(frame, detector.height, detector.width)\n",
    "\n",
    "            # Measure processing time.\n",
    "            start_time = time.time()\n",
    "            # Get the results.\n",
    "            output = detector.predict(input_image)\n",
    "            stop_time = time.time()\n",
    "            processing_times.append(stop_time - start_time)\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) * 1100\n",
    "            fps = 1000 / processing_time\n",
    "\n",
    "            # Get poses from detection results.\n",
    "            bbox_xywh, score, label = process_results(h, w, results=output)\n",
    "\n",
    "            img_crops = []\n",
    "            for box in bbox_xywh:\n",
    "                x1, y1, x2, y2 = xywh_to_xyxy(box, h, w)\n",
    "                img = frame[y1:y2, x1:x2]\n",
    "                img_crops.append(img)\n",
    "\n",
    "            # Get reidentification feature of each person.\n",
    "            if img_crops:\n",
    "                # preprocess\n",
    "                img_batch = batch_preprocess(img_crops, extractor.height, extractor.width)\n",
    "                features = extractor.predict(img_batch)\n",
    "            else:\n",
    "                features = np.array([])\n",
    "\n",
    "            # Wrap the detection and reidentification results together\n",
    "            bbox_tlwh = xywh_to_tlwh(bbox_xywh)\n",
    "            detections = [Detection(bbox_tlwh[i], features[i]) for i in range(features.shape[0])]\n",
    "\n",
    "            # predict the position of tracking target\n",
    "            tracker.predict()\n",
    "\n",
    "            # update tracker\n",
    "            tracker.update(detections)\n",
    "\n",
    "            # update bbox identities\n",
    "            outputs = []\n",
    "            for track in tracker.tracks:\n",
    "                if not track.is_confirmed() or track.time_since_update > 1:\n",
    "                    continue\n",
    "                box = track.to_tlwh()\n",
    "                x1, y1, x2, y2 = tlwh_to_xyxy(box, h, w)\n",
    "                track_id = track.track_id\n",
    "                outputs.append(np.array([x1, y1, x2, y2, track_id], dtype=np.int32))\n",
    "            if len(outputs) > 0:\n",
    "                outputs = np.stack(outputs, axis=0)\n",
    "\n",
    "            # draw box for visualization\n",
    "            if len(outputs) > 0:\n",
    "                bbox_tlwh = []\n",
    "                bbox_xyxy = outputs[:, :4]\n",
    "                identities = outputs[:, -1]\n",
    "                frame = draw_boxes(frame, bbox_xyxy, identities)\n",
    "\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",
    "            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",
    "\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",
    "### Initialize tracker\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Before running a new tracking task, we have to reinitialize a Tracker object\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NN_BUDGET = 100\n",
    "MAX_COSINE_DISTANCE = 0.6  # threshold of matching object\n",
    "metric = NearestNeighborDistanceMetric(\"cosine\", MAX_COSINE_DISTANCE, NN_BUDGET)\n",
    "tracker = Tracker(metric, max_iou_distance=0.7, max_age=70, n_init=3)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run Live Person Tracking\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",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "USE_WEBCAM = False\n",
    "\n",
    "cam_id = 0\n",
    "video_file = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/video/people.mp4\"\n",
    "source = cam_id if USE_WEBCAM else video_file\n",
    "\n",
    "run_person_tracking(source=source, flip=USE_WEBCAM, use_popup=False)"
   ]
  }
 ],
 "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://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/person-tracking-webcam/person-tracking.gif?raw=true",
   "tags": {
    "categories": [
     "Live Demos"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Object Detection"
    ]
   }
  },
  "vscode": {
   "interpreter": {
    "hash": "1c707170576399eaaed0c4f2e01a2d1b61ba791ba1842c47e5b3e4f6f79b82ab"
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}