File size: 37,524 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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Live Human Pose Estimation with OpenVINO™\n",
    "\n",
    "This notebook demonstrates live pose estimation with OpenVINO, using the OpenPose [human-pose-estimation-0001](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001) model 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 a webcam, you must run this Jupyter notebook on a computer with a webcam. If you run on a server, the webcam will not work. However, you can still do inference on a video in the final step.\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Imports](#Imports)\n",
    "- [The model](#The-model)\n",
    "    - [Download the model](#Download-the-model)\n",
    "    - [Load the model](#Load-the-model)\n",
    "- [Processing](#Processing)\n",
    "    - [OpenPose Decoder](#OpenPose-Decoder)\n",
    "    - [Process Results](#Process-Results)\n",
    "    - [Draw Pose Overlays](#Draw-Pose-Overlays)\n",
    "    - [Main Processing Function](#Main-Processing-Function)\n",
    "- [Run](#Run)\n",
    "    - [Run Live Pose Estimation](#Run-Live-Pose-Estimation)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"openvino>=2023.1.0\" opencv-python tqdm"
   ]
  },
  {
   "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 time\n",
    "from pathlib import Path\n",
    "\n",
    "import cv2\n",
    "import numpy as np\n",
    "from IPython import display\n",
    "from numpy.lib.stride_tricks import as_strided\n",
    "import openvino as ov\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)\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.\n",
    "\n",
    "If you want to download another model, replace the name of the model and precision in the code below. \n",
    "\n",
    "> **NOTE**: This may require a different pose decoder."
   ]
  },
  {
   "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 = \"human-pose-estimation-0001\"\n",
    "# Selected precision (FP32, FP16, FP16-INT8).\n",
    "precision = \"FP16-INT8\"\n",
    "\n",
    "model_path = base_model_dir / \"intel\" / model_name / precision / f\"{model_name}.xml\"\n",
    "\n",
    "if not model_path.exists():\n",
    "    model_url_dir = f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2022.1/models_bin/3/{model_name}/{precision}/\"\n",
    "    utils.download_file(model_url_dir + model_name + \".xml\", model_path.name, model_path.parent)\n",
    "    utils.download_file(\n",
    "        model_url_dir + model_name + \".bin\",\n",
    "        model_path.with_suffix(\".bin\").name,\n",
    "        model_path.parent,\n",
    "    )"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Downloaded models are located in a fixed structure, which indicates a vendor, the name of the model and a precision.\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 it for the desired device. 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",
    "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": [
    "# Initialize OpenVINO Runtime\n",
    "core = ov.Core()\n",
    "# Read the network from a file.\n",
    "model = core.read_model(model_path)\n",
    "# Let the AUTO device decide where to load the model (you can use CPU, GPU as well).\n",
    "compiled_model = core.compile_model(model=model, device_name=device.value, config={\"PERFORMANCE_HINT\": \"LATENCY\"})\n",
    "\n",
    "# Get the input and output names of nodes.\n",
    "input_layer = compiled_model.input(0)\n",
    "output_layers = compiled_model.outputs\n",
    "\n",
    "# Get the input size.\n",
    "height, width = list(input_layer.shape)[2:]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Input layer has the name of the input node and output layers contain names of output nodes of the network. In the case of OpenPose Model, there is 1 input and 2 outputs: PAFs and keypoints heatmap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_layer.any_name, [o.any_name for o in output_layers]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "### OpenPose Decoder\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "To transform the raw results from the neural network into pose estimations, you need OpenPose Decoder. It is provided in the [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/openvino/model_zoo/model_api/models/open_pose.py) and compatible with the `human-pose-estimation-0001` model.\n",
    "\n",
    "If you choose a model other than `human-pose-estimation-0001` you will need another decoder (for example, `AssociativeEmbeddingDecoder`), which is available in the [demos section](https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/openvino/model_zoo/model_api/models/hpe_associative_embedding.py) of Open Model Zoo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# code from https://github.com/openvinotoolkit/open_model_zoo/blob/9296a3712069e688fe64ea02367466122c8e8a3b/demos/common/python/models/open_pose.py#L135\n",
    "class OpenPoseDecoder:\n",
    "    BODY_PARTS_KPT_IDS = (\n",
    "        (1, 2),\n",
    "        (1, 5),\n",
    "        (2, 3),\n",
    "        (3, 4),\n",
    "        (5, 6),\n",
    "        (6, 7),\n",
    "        (1, 8),\n",
    "        (8, 9),\n",
    "        (9, 10),\n",
    "        (1, 11),\n",
    "        (11, 12),\n",
    "        (12, 13),\n",
    "        (1, 0),\n",
    "        (0, 14),\n",
    "        (14, 16),\n",
    "        (0, 15),\n",
    "        (15, 17),\n",
    "        (2, 16),\n",
    "        (5, 17),\n",
    "    )\n",
    "    BODY_PARTS_PAF_IDS = (\n",
    "        12,\n",
    "        20,\n",
    "        14,\n",
    "        16,\n",
    "        22,\n",
    "        24,\n",
    "        0,\n",
    "        2,\n",
    "        4,\n",
    "        6,\n",
    "        8,\n",
    "        10,\n",
    "        28,\n",
    "        30,\n",
    "        34,\n",
    "        32,\n",
    "        36,\n",
    "        18,\n",
    "        26,\n",
    "    )\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_joints=18,\n",
    "        skeleton=BODY_PARTS_KPT_IDS,\n",
    "        paf_indices=BODY_PARTS_PAF_IDS,\n",
    "        max_points=100,\n",
    "        score_threshold=0.1,\n",
    "        min_paf_alignment_score=0.05,\n",
    "        delta=0.5,\n",
    "    ):\n",
    "        self.num_joints = num_joints\n",
    "        self.skeleton = skeleton\n",
    "        self.paf_indices = paf_indices\n",
    "        self.max_points = max_points\n",
    "        self.score_threshold = score_threshold\n",
    "        self.min_paf_alignment_score = min_paf_alignment_score\n",
    "        self.delta = delta\n",
    "\n",
    "        self.points_per_limb = 10\n",
    "        self.grid = np.arange(self.points_per_limb, dtype=np.float32).reshape(1, -1, 1)\n",
    "\n",
    "    def __call__(self, heatmaps, nms_heatmaps, pafs):\n",
    "        batch_size, _, h, w = heatmaps.shape\n",
    "        assert batch_size == 1, \"Batch size of 1 only supported\"\n",
    "\n",
    "        keypoints = self.extract_points(heatmaps, nms_heatmaps)\n",
    "        pafs = np.transpose(pafs, (0, 2, 3, 1))\n",
    "\n",
    "        if self.delta > 0:\n",
    "            for kpts in keypoints:\n",
    "                kpts[:, :2] += self.delta\n",
    "                np.clip(kpts[:, 0], 0, w - 1, out=kpts[:, 0])\n",
    "                np.clip(kpts[:, 1], 0, h - 1, out=kpts[:, 1])\n",
    "\n",
    "        pose_entries, keypoints = self.group_keypoints(keypoints, pafs, pose_entry_size=self.num_joints + 2)\n",
    "        poses, scores = self.convert_to_coco_format(pose_entries, keypoints)\n",
    "        if len(poses) > 0:\n",
    "            poses = np.asarray(poses, dtype=np.float32)\n",
    "            poses = poses.reshape((poses.shape[0], -1, 3))\n",
    "        else:\n",
    "            poses = np.empty((0, 17, 3), dtype=np.float32)\n",
    "            scores = np.empty(0, dtype=np.float32)\n",
    "\n",
    "        return poses, scores\n",
    "\n",
    "    def extract_points(self, heatmaps, nms_heatmaps):\n",
    "        batch_size, channels_num, h, w = heatmaps.shape\n",
    "        assert batch_size == 1, \"Batch size of 1 only supported\"\n",
    "        assert channels_num >= self.num_joints\n",
    "\n",
    "        xs, ys, scores = self.top_k(nms_heatmaps)\n",
    "        masks = scores > self.score_threshold\n",
    "        all_keypoints = []\n",
    "        keypoint_id = 0\n",
    "        for k in range(self.num_joints):\n",
    "            # Filter low-score points.\n",
    "            mask = masks[0, k]\n",
    "            x = xs[0, k][mask].ravel()\n",
    "            y = ys[0, k][mask].ravel()\n",
    "            score = scores[0, k][mask].ravel()\n",
    "            n = len(x)\n",
    "            if n == 0:\n",
    "                all_keypoints.append(np.empty((0, 4), dtype=np.float32))\n",
    "                continue\n",
    "            # Apply quarter offset to improve localization accuracy.\n",
    "            x, y = self.refine(heatmaps[0, k], x, y)\n",
    "            np.clip(x, 0, w - 1, out=x)\n",
    "            np.clip(y, 0, h - 1, out=y)\n",
    "            # Pack resulting points.\n",
    "            keypoints = np.empty((n, 4), dtype=np.float32)\n",
    "            keypoints[:, 0] = x\n",
    "            keypoints[:, 1] = y\n",
    "            keypoints[:, 2] = score\n",
    "            keypoints[:, 3] = np.arange(keypoint_id, keypoint_id + n)\n",
    "            keypoint_id += n\n",
    "            all_keypoints.append(keypoints)\n",
    "        return all_keypoints\n",
    "\n",
    "    def top_k(self, heatmaps):\n",
    "        N, K, _, W = heatmaps.shape\n",
    "        heatmaps = heatmaps.reshape(N, K, -1)\n",
    "        # Get positions with top scores.\n",
    "        ind = heatmaps.argpartition(-self.max_points, axis=2)[:, :, -self.max_points :]\n",
    "        scores = np.take_along_axis(heatmaps, ind, axis=2)\n",
    "        # Keep top scores sorted.\n",
    "        subind = np.argsort(-scores, axis=2)\n",
    "        ind = np.take_along_axis(ind, subind, axis=2)\n",
    "        scores = np.take_along_axis(scores, subind, axis=2)\n",
    "        y, x = np.divmod(ind, W)\n",
    "        return x, y, scores\n",
    "\n",
    "    @staticmethod\n",
    "    def refine(heatmap, x, y):\n",
    "        h, w = heatmap.shape[-2:]\n",
    "        valid = np.logical_and(np.logical_and(x > 0, x < w - 1), np.logical_and(y > 0, y < h - 1))\n",
    "        xx = x[valid]\n",
    "        yy = y[valid]\n",
    "        dx = np.sign(heatmap[yy, xx + 1] - heatmap[yy, xx - 1], dtype=np.float32) * 0.25\n",
    "        dy = np.sign(heatmap[yy + 1, xx] - heatmap[yy - 1, xx], dtype=np.float32) * 0.25\n",
    "        x = x.astype(np.float32)\n",
    "        y = y.astype(np.float32)\n",
    "        x[valid] += dx\n",
    "        y[valid] += dy\n",
    "        return x, y\n",
    "\n",
    "    @staticmethod\n",
    "    def is_disjoint(pose_a, pose_b):\n",
    "        pose_a = pose_a[:-2]\n",
    "        pose_b = pose_b[:-2]\n",
    "        return np.all(np.logical_or.reduce((pose_a == pose_b, pose_a < 0, pose_b < 0)))\n",
    "\n",
    "    def update_poses(\n",
    "        self,\n",
    "        kpt_a_id,\n",
    "        kpt_b_id,\n",
    "        all_keypoints,\n",
    "        connections,\n",
    "        pose_entries,\n",
    "        pose_entry_size,\n",
    "    ):\n",
    "        for connection in connections:\n",
    "            pose_a_idx = -1\n",
    "            pose_b_idx = -1\n",
    "            for j, pose in enumerate(pose_entries):\n",
    "                if pose[kpt_a_id] == connection[0]:\n",
    "                    pose_a_idx = j\n",
    "                if pose[kpt_b_id] == connection[1]:\n",
    "                    pose_b_idx = j\n",
    "            if pose_a_idx < 0 and pose_b_idx < 0:\n",
    "                # Create new pose entry.\n",
    "                pose_entry = np.full(pose_entry_size, -1, dtype=np.float32)\n",
    "                pose_entry[kpt_a_id] = connection[0]\n",
    "                pose_entry[kpt_b_id] = connection[1]\n",
    "                pose_entry[-1] = 2\n",
    "                pose_entry[-2] = np.sum(all_keypoints[connection[0:2], 2]) + connection[2]\n",
    "                pose_entries.append(pose_entry)\n",
    "            elif pose_a_idx >= 0 and pose_b_idx >= 0 and pose_a_idx != pose_b_idx:\n",
    "                # Merge two poses are disjoint merge them, otherwise ignore connection.\n",
    "                pose_a = pose_entries[pose_a_idx]\n",
    "                pose_b = pose_entries[pose_b_idx]\n",
    "                if self.is_disjoint(pose_a, pose_b):\n",
    "                    pose_a += pose_b\n",
    "                    pose_a[:-2] += 1\n",
    "                    pose_a[-2] += connection[2]\n",
    "                    del pose_entries[pose_b_idx]\n",
    "            elif pose_a_idx >= 0 and pose_b_idx >= 0:\n",
    "                # Adjust score of a pose.\n",
    "                pose_entries[pose_a_idx][-2] += connection[2]\n",
    "            elif pose_a_idx >= 0:\n",
    "                # Add a new limb into pose.\n",
    "                pose = pose_entries[pose_a_idx]\n",
    "                if pose[kpt_b_id] < 0:\n",
    "                    pose[-2] += all_keypoints[connection[1], 2]\n",
    "                pose[kpt_b_id] = connection[1]\n",
    "                pose[-2] += connection[2]\n",
    "                pose[-1] += 1\n",
    "            elif pose_b_idx >= 0:\n",
    "                # Add a new limb into pose.\n",
    "                pose = pose_entries[pose_b_idx]\n",
    "                if pose[kpt_a_id] < 0:\n",
    "                    pose[-2] += all_keypoints[connection[0], 2]\n",
    "                pose[kpt_a_id] = connection[0]\n",
    "                pose[-2] += connection[2]\n",
    "                pose[-1] += 1\n",
    "        return pose_entries\n",
    "\n",
    "    @staticmethod\n",
    "    def connections_nms(a_idx, b_idx, affinity_scores):\n",
    "        # From all retrieved connections that share starting/ending keypoints leave only the top-scoring ones.\n",
    "        order = affinity_scores.argsort()[::-1]\n",
    "        affinity_scores = affinity_scores[order]\n",
    "        a_idx = a_idx[order]\n",
    "        b_idx = b_idx[order]\n",
    "        idx = []\n",
    "        has_kpt_a = set()\n",
    "        has_kpt_b = set()\n",
    "        for t, (i, j) in enumerate(zip(a_idx, b_idx)):\n",
    "            if i not in has_kpt_a and j not in has_kpt_b:\n",
    "                idx.append(t)\n",
    "                has_kpt_a.add(i)\n",
    "                has_kpt_b.add(j)\n",
    "        idx = np.asarray(idx, dtype=np.int32)\n",
    "        return a_idx[idx], b_idx[idx], affinity_scores[idx]\n",
    "\n",
    "    def group_keypoints(self, all_keypoints_by_type, pafs, pose_entry_size=20):\n",
    "        all_keypoints = np.concatenate(all_keypoints_by_type, axis=0)\n",
    "        pose_entries = []\n",
    "        # For every limb.\n",
    "        for part_id, paf_channel in enumerate(self.paf_indices):\n",
    "            kpt_a_id, kpt_b_id = self.skeleton[part_id]\n",
    "            kpts_a = all_keypoints_by_type[kpt_a_id]\n",
    "            kpts_b = all_keypoints_by_type[kpt_b_id]\n",
    "            n = len(kpts_a)\n",
    "            m = len(kpts_b)\n",
    "            if n == 0 or m == 0:\n",
    "                continue\n",
    "\n",
    "            # Get vectors between all pairs of keypoints, i.e. candidate limb vectors.\n",
    "            a = kpts_a[:, :2]\n",
    "            a = np.broadcast_to(a[None], (m, n, 2))\n",
    "            b = kpts_b[:, :2]\n",
    "            vec_raw = (b[:, None, :] - a).reshape(-1, 1, 2)\n",
    "\n",
    "            # Sample points along every candidate limb vector.\n",
    "            steps = 1 / (self.points_per_limb - 1) * vec_raw\n",
    "            points = steps * self.grid + a.reshape(-1, 1, 2)\n",
    "            points = points.round().astype(dtype=np.int32)\n",
    "            x = points[..., 0].ravel()\n",
    "            y = points[..., 1].ravel()\n",
    "\n",
    "            # Compute affinity score between candidate limb vectors and part affinity field.\n",
    "            part_pafs = pafs[0, :, :, paf_channel : paf_channel + 2]\n",
    "            field = part_pafs[y, x].reshape(-1, self.points_per_limb, 2)\n",
    "            vec_norm = np.linalg.norm(vec_raw, ord=2, axis=-1, keepdims=True)\n",
    "            vec = vec_raw / (vec_norm + 1e-6)\n",
    "            affinity_scores = (field * vec).sum(-1).reshape(-1, self.points_per_limb)\n",
    "            valid_affinity_scores = affinity_scores > self.min_paf_alignment_score\n",
    "            valid_num = valid_affinity_scores.sum(1)\n",
    "            affinity_scores = (affinity_scores * valid_affinity_scores).sum(1) / (valid_num + 1e-6)\n",
    "            success_ratio = valid_num / self.points_per_limb\n",
    "\n",
    "            # Get a list of limbs according to the obtained affinity score.\n",
    "            valid_limbs = np.where(np.logical_and(affinity_scores > 0, success_ratio > 0.8))[0]\n",
    "            if len(valid_limbs) == 0:\n",
    "                continue\n",
    "            b_idx, a_idx = np.divmod(valid_limbs, n)\n",
    "            affinity_scores = affinity_scores[valid_limbs]\n",
    "\n",
    "            # Suppress incompatible connections.\n",
    "            a_idx, b_idx, affinity_scores = self.connections_nms(a_idx, b_idx, affinity_scores)\n",
    "            connections = list(\n",
    "                zip(\n",
    "                    kpts_a[a_idx, 3].astype(np.int32),\n",
    "                    kpts_b[b_idx, 3].astype(np.int32),\n",
    "                    affinity_scores,\n",
    "                )\n",
    "            )\n",
    "            if len(connections) == 0:\n",
    "                continue\n",
    "\n",
    "            # Update poses with new connections.\n",
    "            pose_entries = self.update_poses(\n",
    "                kpt_a_id,\n",
    "                kpt_b_id,\n",
    "                all_keypoints,\n",
    "                connections,\n",
    "                pose_entries,\n",
    "                pose_entry_size,\n",
    "            )\n",
    "\n",
    "        # Remove poses with not enough points.\n",
    "        pose_entries = np.asarray(pose_entries, dtype=np.float32).reshape(-1, pose_entry_size)\n",
    "        pose_entries = pose_entries[pose_entries[:, -1] >= 3]\n",
    "        return pose_entries, all_keypoints\n",
    "\n",
    "    @staticmethod\n",
    "    def convert_to_coco_format(pose_entries, all_keypoints):\n",
    "        num_joints = 17\n",
    "        coco_keypoints = []\n",
    "        scores = []\n",
    "        for pose in pose_entries:\n",
    "            if len(pose) == 0:\n",
    "                continue\n",
    "            keypoints = np.zeros(num_joints * 3)\n",
    "            reorder_map = [0, -1, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3]\n",
    "            person_score = pose[-2]\n",
    "            for keypoint_id, target_id in zip(pose[:-2], reorder_map):\n",
    "                if target_id < 0:\n",
    "                    continue\n",
    "                cx, cy, score = 0, 0, 0  # keypoint not found\n",
    "                if keypoint_id != -1:\n",
    "                    cx, cy, score = all_keypoints[int(keypoint_id), 0:3]\n",
    "                keypoints[target_id * 3 + 0] = cx\n",
    "                keypoints[target_id * 3 + 1] = cy\n",
    "                keypoints[target_id * 3 + 2] = score\n",
    "            coco_keypoints.append(keypoints)\n",
    "            scores.append(person_score * max(0, (pose[-1] - 1)))  # -1 for 'neck'\n",
    "        return np.asarray(coco_keypoints), np.asarray(scores)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Processing\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "decoder = OpenPoseDecoder()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Process Results\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "A bunch of useful functions to transform results into poses.\n",
    "\n",
    "First, pool the heatmap. Since pooling is not available in numpy, use a simple method to do it directly with numpy. Then, use non-maximum suppression to get the keypoints from the heatmap. After that, decode poses by using the decoder. Since the input image is bigger than the network outputs, you need to multiply all pose coordinates by a scaling factor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2D pooling in numpy (from: https://stackoverflow.com/a/54966908/1624463)\n",
    "def pool2d(A, kernel_size, stride, padding, pool_mode=\"max\"):\n",
    "    \"\"\"\n",
    "    2D Pooling\n",
    "\n",
    "    Parameters:\n",
    "        A: input 2D array\n",
    "        kernel_size: int, the size of the window\n",
    "        stride: int, the stride of the window\n",
    "        padding: int, implicit zero paddings on both sides of the input\n",
    "        pool_mode: string, 'max' or 'avg'\n",
    "    \"\"\"\n",
    "    # Padding\n",
    "    A = np.pad(A, padding, mode=\"constant\")\n",
    "\n",
    "    # Window view of A\n",
    "    output_shape = (\n",
    "        (A.shape[0] - kernel_size) // stride + 1,\n",
    "        (A.shape[1] - kernel_size) // stride + 1,\n",
    "    )\n",
    "    kernel_size = (kernel_size, kernel_size)\n",
    "    A_w = as_strided(\n",
    "        A,\n",
    "        shape=output_shape + kernel_size,\n",
    "        strides=(stride * A.strides[0], stride * A.strides[1]) + A.strides,\n",
    "    )\n",
    "    A_w = A_w.reshape(-1, *kernel_size)\n",
    "\n",
    "    # Return the result of pooling.\n",
    "    if pool_mode == \"max\":\n",
    "        return A_w.max(axis=(1, 2)).reshape(output_shape)\n",
    "    elif pool_mode == \"avg\":\n",
    "        return A_w.mean(axis=(1, 2)).reshape(output_shape)\n",
    "\n",
    "\n",
    "# non maximum suppression\n",
    "def heatmap_nms(heatmaps, pooled_heatmaps):\n",
    "    return heatmaps * (heatmaps == pooled_heatmaps)\n",
    "\n",
    "\n",
    "# Get poses from results.\n",
    "def process_results(img, pafs, heatmaps):\n",
    "    # This processing comes from\n",
    "    # https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/models/open_pose.py\n",
    "    pooled_heatmaps = np.array([[pool2d(h, kernel_size=3, stride=1, padding=1, pool_mode=\"max\") for h in heatmaps[0]]])\n",
    "    nms_heatmaps = heatmap_nms(heatmaps, pooled_heatmaps)\n",
    "\n",
    "    # Decode poses.\n",
    "    poses, scores = decoder(heatmaps, nms_heatmaps, pafs)\n",
    "    output_shape = list(compiled_model.output(index=0).partial_shape)\n",
    "    output_scale = (\n",
    "        img.shape[1] / output_shape[3].get_length(),\n",
    "        img.shape[0] / output_shape[2].get_length(),\n",
    "    )\n",
    "    # Multiply coordinates by a scaling factor.\n",
    "    poses[:, :, :2] *= output_scale\n",
    "    return poses, scores"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Draw Pose Overlays\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Draw pose overlays on the image to visualize estimated poses. Joints are drawn as circles and limbs are drawn as lines. The code is based on the [Human Pose Estimation Demo](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos/human_pose_estimation_demo/python) from Open Model Zoo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "colors = (\n",
    "    (255, 0, 0),\n",
    "    (255, 0, 255),\n",
    "    (170, 0, 255),\n",
    "    (255, 0, 85),\n",
    "    (255, 0, 170),\n",
    "    (85, 255, 0),\n",
    "    (255, 170, 0),\n",
    "    (0, 255, 0),\n",
    "    (255, 255, 0),\n",
    "    (0, 255, 85),\n",
    "    (170, 255, 0),\n",
    "    (0, 85, 255),\n",
    "    (0, 255, 170),\n",
    "    (0, 0, 255),\n",
    "    (0, 255, 255),\n",
    "    (85, 0, 255),\n",
    "    (0, 170, 255),\n",
    ")\n",
    "\n",
    "default_skeleton = (\n",
    "    (15, 13),\n",
    "    (13, 11),\n",
    "    (16, 14),\n",
    "    (14, 12),\n",
    "    (11, 12),\n",
    "    (5, 11),\n",
    "    (6, 12),\n",
    "    (5, 6),\n",
    "    (5, 7),\n",
    "    (6, 8),\n",
    "    (7, 9),\n",
    "    (8, 10),\n",
    "    (1, 2),\n",
    "    (0, 1),\n",
    "    (0, 2),\n",
    "    (1, 3),\n",
    "    (2, 4),\n",
    "    (3, 5),\n",
    "    (4, 6),\n",
    ")\n",
    "\n",
    "\n",
    "def draw_poses(img, poses, point_score_threshold, skeleton=default_skeleton):\n",
    "    if poses.size == 0:\n",
    "        return img\n",
    "\n",
    "    img_limbs = np.copy(img)\n",
    "    for pose in poses:\n",
    "        points = pose[:, :2].astype(np.int32)\n",
    "        points_scores = pose[:, 2]\n",
    "        # Draw joints.\n",
    "        for i, (p, v) in enumerate(zip(points, points_scores)):\n",
    "            if v > point_score_threshold:\n",
    "                cv2.circle(img, tuple(p), 1, colors[i], 2)\n",
    "        # Draw limbs.\n",
    "        for i, j in skeleton:\n",
    "            if points_scores[i] > point_score_threshold and points_scores[j] > point_score_threshold:\n",
    "                cv2.line(\n",
    "                    img_limbs,\n",
    "                    tuple(points[i]),\n",
    "                    tuple(points[j]),\n",
    "                    color=colors[j],\n",
    "                    thickness=4,\n",
    "                )\n",
    "    cv2.addWeighted(img, 0.4, img_limbs, 0.6, 0, dst=img)\n",
    "    return img"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Main Processing Function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run pose estimation 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 pose estimation.\n",
    "def run_pose_estimation(source=0, flip=False, use_popup=False, skip_first_frames=0):\n",
    "    pafs_output_key = compiled_model.output(\"Mconv7_stage2_L1\")\n",
    "    heatmaps_output_key = compiled_model.output(\"Mconv7_stage2_L2\")\n",
    "    player = None\n",
    "    try:\n",
    "        # Create a video player to play with target fps.\n",
    "        player = utils.VideoPlayer(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(title, cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)\n",
    "\n",
    "        processing_times = collections.deque()\n",
    "\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(frame, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)\n",
    "\n",
    "            # Resize the image and change dims to fit neural network input.\n",
    "            # (see https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001)\n",
    "            input_img = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)\n",
    "            # Create a batch of images (size = 1).\n",
    "            input_img = input_img.transpose((2, 0, 1))[np.newaxis, ...]\n",
    "\n",
    "            # Measure processing time.\n",
    "            start_time = time.time()\n",
    "            # Get results.\n",
    "            results = compiled_model([input_img])\n",
    "            stop_time = time.time()\n",
    "\n",
    "            pafs = results[pafs_output_key]\n",
    "            heatmaps = results[heatmaps_output_key]\n",
    "            # Get poses from network results.\n",
    "            poses, scores = process_results(frame, pafs, heatmaps)\n",
    "\n",
    "            # Draw poses on a frame.\n",
    "            frame = draw_poses(frame, poses, 0.1)\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",
    "                frame,\n",
    "                f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n",
    "                (20, 40),\n",
    "                cv2.FONT_HERSHEY_COMPLEX,\n",
    "                f_width / 1000,\n",
    "                (0, 0, 255),\n",
    "                1,\n",
    "                cv2.LINE_AA,\n",
    "            )\n",
    "\n",
    "            # Use this workaround if there is flickering.\n",
    "            if use_popup:\n",
    "                cv2.imshow(title, 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(\".jpg\", frame, params=[cv2.IMWRITE_JPEG_QUALITY, 90])\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 Pose Estimation\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. You can skip first `N` frames to fast forward video.\n",
    "\n",
    "Run the pose estimation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "USE_WEBCAM = False\n",
    "cam_id = 0\n",
    "video_file = \"https://github.com/intel-iot-devkit/sample-videos/blob/master/store-aisle-detection.mp4?raw=true\"\n",
    "source = cam_id if USE_WEBCAM else video_file\n",
    "\n",
    "additional_options = {\"skip_first_frames\": 500} if not USE_WEBCAM else {}\n",
    "run_pose_estimation(source=source, flip=isinstance(source, int), use_popup=False, **additional_options)"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit 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.11.8"
  },
  "openvino_notebooks": {
   "imageUrl": "https://user-images.githubusercontent.com/4547501/138267961-41d754e7-59db-49f6-b700-63c3a636fad7.gif",
   "tags": {
    "categories": [
     "Live Demos"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Pose Estimation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}