{ "cells": [ { "cell_type": "markdown", "id": "9de9a93e-9247-4799-a5bb-2ec1575ae8c2", "metadata": {}, "source": [ "# Live 3D Human Pose Estimation with OpenVINO\n", "\n", "This notebook demonstrates live 3D Human Pose Estimation with OpenVINO via a webcam. We utilize the model [human-pose-estimation-3d-0001](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/human-pose-estimation-3d-0001) from [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). At the end of this notebook, you will see live inference results from your webcam (if available). Alternatively, you can also upload a video file to test out the algorithms.\n", "**Make sure you have properly installed the [Jupyter extension](https://github.com/jupyter-widgets/pythreejs#jupyterlab) and been using JupyterLab to run the demo as suggested in the `README.md`**\n", "\n", "> **NOTE**: _To use a webcam, you must run this Jupyter notebook on a computer with a webcam. If you run on a remote server, the webcam will not work. However, you can still do inference on a video file in the final step. This demo utilizes the Python interface in `Three.js` integrated with WebGL to process data from the model inference. These results are processed and displayed in the notebook._\n", "\n", "_To ensure that the results are displayed correctly, run the code in a recommended browser on one of the following operating systems:_\n", "_Ubuntu, Windows: Chrome_\n", "_macOS: Safari_\n", "\n", "\n", "#### Table of contents:\n", "\n", "- [Prerequisites](#Prerequisites)\n", "- [Imports](#Imports)\n", "- [The model](#The-model)\n", " - [Download the model](#Download-the-model)\n", " - [Convert Model to OpenVINO IR format](#Convert-Model-to-OpenVINO-IR-format)\n", " - [Select inference device](#Select-inference-device)\n", " - [Load the model](#Load-the-model)\n", "- [Processing](#Processing)\n", " - [Model Inference](#Model-Inference)\n", " - [Draw 2D Pose Overlays](#Draw-2D-Pose-Overlays)\n", " - [Main Processing Function](#Main-Processing-Function)\n", "- [Run](#Run)\n", "\n" ] }, { "cell_type": "markdown", "id": "7925a51b-26ec-43c5-9660-0705c03d724d", "metadata": {}, "source": [ "## Prerequisites\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "**The `pythreejs` extension may not display properly when using a Jupyter Notebook release. Therefore, it is recommended to use Jupyter Lab instead.**" ] }, { "cell_type": "code", "execution_count": null, "id": "b84c1f5e-502b-4037-b871-9f84b4e8cef0", "metadata": {}, "outputs": [], "source": [ "%pip install pythreejs \"openvino-dev>=2024.0.0\" \"opencv-python\" \"torch\" \"onnx\" --extra-index-url https://download.pytorch.org/whl/cpu" ] }, { "cell_type": "markdown", "id": "5a9332fb-1cee-4faa-9555-731ddf0e0df7", "metadata": {}, "source": [ "## Imports\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "316ad889-8514-430f-baf4-4f32abd43356", "metadata": {}, "outputs": [], "source": [ "import collections\n", "import time\n", "from pathlib import Path\n", "\n", "import cv2\n", "import ipywidgets as widgets\n", "import numpy as np\n", "from IPython.display import clear_output, display\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", "with open(\"notebook_utils.py\", \"w\") as f:\n", " f.write(r.text)\n", "\n", "r = requests.get(\n", " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/engine3js.py\",\n", ")\n", "with open(\"engine3js.py\", \"w\") as f:\n", " f.write(r.text)\n", "\n", "import notebook_utils as utils\n", "import engine3js as engine" ] }, { "cell_type": "markdown", "id": "c96ad61a-59ff-4873-b2f3-3994d6826f51", "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", "We use `omz_downloader`, which is a command line tool from the `openvino-dev` package. `omz_downloader` automatically creates a directory structure and downloads the selected model." ] }, { "cell_type": "code", "execution_count": null, "id": "31bd89c7-be8a-4b03-ba38-c19d328e332d", "metadata": {}, "outputs": [], "source": [ "# directory where model will be downloaded\n", "base_model_dir = \"model\"\n", "\n", "# model name as named in Open Model Zoo\n", "model_name = \"human-pose-estimation-3d-0001\"\n", "# selected precision (FP32, FP16)\n", "precision = \"FP32\"\n", "\n", "BASE_MODEL_NAME = f\"{base_model_dir}/public/{model_name}/{model_name}\"\n", "model_path = Path(BASE_MODEL_NAME).with_suffix(\".pth\")\n", "onnx_path = Path(BASE_MODEL_NAME).with_suffix(\".onnx\")\n", "\n", "ir_model_path = f\"model/public/{model_name}/{precision}/{model_name}.xml\"\n", "model_weights_path = f\"model/public/{model_name}/{precision}/{model_name}.bin\"\n", "\n", "if not model_path.exists():\n", " download_command = f\"omz_downloader \" f\"--name {model_name} \" f\"--output_dir {base_model_dir}\"\n", " ! $download_command" ] }, { "cell_type": "markdown", "id": "88f39f76-2f81-4c18-9fda-98ea6a944220", "metadata": {}, "source": [ "### Convert Model to OpenVINO IR format\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "The selected model comes from the public directory, which means it must be converted into OpenVINO Intermediate Representation (OpenVINO IR). We use `omz_converter` to convert the ONNX format model to the OpenVINO IR format." ] }, { "cell_type": "code", "execution_count": null, "id": "c9bdfdee-c2ef-4710-96c1-8a6a896a8cba", "metadata": {}, "outputs": [], "source": [ "if not onnx_path.exists():\n", " convert_command = (\n", " f\"omz_converter \" f\"--name {model_name} \" f\"--precisions {precision} \" f\"--download_dir {base_model_dir} \" f\"--output_dir {base_model_dir}\"\n", " )\n", " ! $convert_command" ] }, { "cell_type": "markdown", "id": "6458fe97-6e93-4357-bc9a-16394d962e56", "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, "id": "ae27d9b7-95ae-4b1c-acb7-c911ec7f698c", "metadata": {}, "outputs": [], "source": [ "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": "markdown", "id": "986a07ac-d092-4254-848a-dd48f4934fb5", "metadata": {}, "source": [ "### Load the model\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Converted models are located in a fixed structure, which indicates vendor, model name and precision.\n", "\n", "First, initialize the inference engine, OpenVINO Runtime. Then, read the network architecture and model weights from the `.bin` and `.xml` files to compile for the desired device. An inference request is then created to infer the compiled model." ] }, { "cell_type": "code", "execution_count": null, "id": "92a04102-aebf-4976-874b-b98dca97ec48", "metadata": {}, "outputs": [], "source": [ "# initialize inference engine\n", "core = ov.Core()\n", "# read the network and corresponding weights from file\n", "model = core.read_model(model=ir_model_path, weights=model_weights_path)\n", "# load the model on the specified device\n", "compiled_model = core.compile_model(model=model, device_name=device.value)\n", "infer_request = compiled_model.create_infer_request()\n", "input_tensor_name = model.inputs[0].get_any_name()\n", "\n", "# get input and output names of nodes\n", "input_layer = compiled_model.input(0)\n", "output_layers = list(compiled_model.outputs)" ] }, { "cell_type": "markdown", "id": "5c0ffd17-df71-4178-8df8-db4ccf431621", "metadata": {}, "source": [ "The input for the model is data from the input image and the outputs are heat maps, PAF (part affinity fields) and features." ] }, { "cell_type": "code", "execution_count": null, "id": "e1b25847-fc80-41a1-930b-7c304fd1fe70", "metadata": {}, "outputs": [], "source": [ "input_layer.any_name, [o.any_name for o in output_layers]" ] }, { "cell_type": "markdown", "id": "48eb5032-a06e-48c1-a3d6-f0fbad9924fb", "metadata": {}, "source": [ "## Processing\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "### Model Inference\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Frames captured from video files or the live webcam are used as the input for the 3D model. This is how you obtain the output heat maps, PAF (part affinity fields) and features." ] }, { "cell_type": "code", "execution_count": null, "id": "08f8055b-a6cf-4003-8232-6f73a86d6034", "metadata": {}, "outputs": [], "source": [ "def model_infer(scaled_img, stride):\n", " \"\"\"\n", " Run model inference on the input image\n", "\n", " Parameters:\n", " scaled_img: resized image according to the input size of the model\n", " stride: int, the stride of the window\n", " \"\"\"\n", "\n", " # Remove excess space from the picture\n", " img = scaled_img[\n", " 0 : scaled_img.shape[0] - (scaled_img.shape[0] % stride),\n", " 0 : scaled_img.shape[1] - (scaled_img.shape[1] % stride),\n", " ]\n", "\n", " img = np.transpose(img, (2, 0, 1))[None,]\n", " infer_request.infer({input_tensor_name: img})\n", " # A set of three inference results is obtained\n", " results = {name: infer_request.get_tensor(name).data[:] for name in {\"features\", \"heatmaps\", \"pafs\"}}\n", " # Get the results\n", " results = (results[\"features\"][0], results[\"heatmaps\"][0], results[\"pafs\"][0])\n", "\n", " return results" ] }, { "cell_type": "markdown", "id": "6991403a-4f87-45be-9b3f-d30b23a46dbe", "metadata": {}, "source": [ "### Draw 2D Pose Overlays\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "We need to define some connections between the joints in advance, so that we can draw the structure of the human body in the resulting image after obtaining the inference results.\n", "Joints are drawn as circles and limbs are drawn as lines. The code is based on the [3D Human Pose Estimation Demo](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos/human_pose_estimation_3d_demo/python) from Open Model Zoo." ] }, { "cell_type": "code", "execution_count": null, "id": "22fd3e08-ed3b-44ac-bd07-4a80130d6681", "metadata": {}, "outputs": [], "source": [ "# 3D edge index array\n", "body_edges = np.array(\n", " [\n", " [0, 1],\n", " [0, 9],\n", " [9, 10],\n", " [10, 11], # neck - r_shoulder - r_elbow - r_wrist\n", " [0, 3],\n", " [3, 4],\n", " [4, 5], # neck - l_shoulder - l_elbow - l_wrist\n", " [1, 15],\n", " [15, 16], # nose - l_eye - l_ear\n", " [1, 17],\n", " [17, 18], # nose - r_eye - r_ear\n", " [0, 6],\n", " [6, 7],\n", " [7, 8], # neck - l_hip - l_knee - l_ankle\n", " [0, 12],\n", " [12, 13],\n", " [13, 14], # neck - r_hip - r_knee - r_ankle\n", " ]\n", ")\n", "\n", "\n", "body_edges_2d = np.array(\n", " [\n", " [0, 1], # neck - nose\n", " [1, 16],\n", " [16, 18], # nose - l_eye - l_ear\n", " [1, 15],\n", " [15, 17], # nose - r_eye - r_ear\n", " [0, 3],\n", " [3, 4],\n", " [4, 5], # neck - l_shoulder - l_elbow - l_wrist\n", " [0, 9],\n", " [9, 10],\n", " [10, 11], # neck - r_shoulder - r_elbow - r_wrist\n", " [0, 6],\n", " [6, 7],\n", " [7, 8], # neck - l_hip - l_knee - l_ankle\n", " [0, 12],\n", " [12, 13],\n", " [13, 14], # neck - r_hip - r_knee - r_ankle\n", " ]\n", ")\n", "\n", "\n", "def draw_poses(frame, poses_2d, scaled_img, use_popup):\n", " \"\"\"\n", " Draw 2D pose overlays on the image to visualize estimated poses.\n", " Joints are drawn as circles and limbs are drawn as lines.\n", "\n", " :param frame: the input image\n", " :param poses_2d: array of human joint pairs\n", " \"\"\"\n", " for pose in poses_2d:\n", " pose = np.array(pose[0:-1]).reshape((-1, 3)).transpose()\n", " was_found = pose[2] > 0\n", "\n", " pose[0], pose[1] = (\n", " pose[0] * frame.shape[1] / scaled_img.shape[1],\n", " pose[1] * frame.shape[0] / scaled_img.shape[0],\n", " )\n", "\n", " # Draw joints.\n", " for edge in body_edges_2d:\n", " if was_found[edge[0]] and was_found[edge[1]]:\n", " cv2.line(\n", " frame,\n", " tuple(pose[0:2, edge[0]].astype(np.int32)),\n", " tuple(pose[0:2, edge[1]].astype(np.int32)),\n", " (255, 255, 0),\n", " 4,\n", " cv2.LINE_AA,\n", " )\n", " # Draw limbs.\n", " for kpt_id in range(pose.shape[1]):\n", " if pose[2, kpt_id] != -1:\n", " cv2.circle(\n", " frame,\n", " tuple(pose[0:2, kpt_id].astype(np.int32)),\n", " 3,\n", " (0, 255, 255),\n", " -1,\n", " cv2.LINE_AA,\n", " )\n", "\n", " return frame" ] }, { "cell_type": "markdown", "id": "a6894ce8-ac91-464d-a7f7-54d09f399f4f", "metadata": {}, "source": [ "### Main Processing Function\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Run 3D pose estimation on the specified source. It could be either a webcam feed or a video file." ] }, { "cell_type": "code", "execution_count": null, "id": "3be526d0-75ad-4bd1-85b1-ca8185eca918", "metadata": { "tags": [] }, "outputs": [], "source": [ "def run_pose_estimation(source=0, flip=False, use_popup=False, skip_frames=0):\n", " \"\"\"\n", " 2D image as input, using OpenVINO as inference backend,\n", " get joints 3D coordinates, and draw 3D human skeleton in the scene\n", "\n", " :param source: The webcam number to feed the video stream with primary webcam set to \"0\", or the video path.\n", " :param flip: To be used by VideoPlayer function for flipping capture image.\n", " :param use_popup: False for showing encoded frames over this notebook, True for creating a popup window.\n", " :param skip_frames: Number of frames to skip at the beginning of the video.\n", " \"\"\"\n", "\n", " focal_length = -1 # default\n", " stride = 8\n", " player = None\n", " skeleton_set = None\n", "\n", " try:\n", " # create video player to play with target fps video_path\n", " # get the frame from camera\n", " # You can skip first N frames to fast forward video. change 'skip_first_frames'\n", " player = utils.VideoPlayer(source, flip=flip, fps=30, skip_first_frames=skip_frames)\n", " # start capturing\n", " player.start()\n", "\n", " input_image = player.next()\n", " # set the window size\n", " resize_scale = 450 / input_image.shape[1]\n", " windows_width = int(input_image.shape[1] * resize_scale)\n", " windows_height = int(input_image.shape[0] * resize_scale)\n", "\n", " # use visualization library\n", " engine3D = engine.Engine3js(grid=True, axis=True, view_width=windows_width, view_height=windows_height)\n", "\n", " if use_popup:\n", " # display the 3D human pose in this notebook, and origin frame in popup window\n", " display(engine3D.renderer)\n", " title = \"Press ESC to Exit\"\n", " cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO | cv2.WINDOW_AUTOSIZE)\n", " else:\n", " # set the 2D image box, show both human pose and image in the notebook\n", " imgbox = widgets.Image(format=\"jpg\", height=windows_height, width=windows_width)\n", " display(widgets.HBox([engine3D.renderer, imgbox]))\n", "\n", " skeleton = engine.Skeleton(body_edges=body_edges)\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", "\n", " # resize image and change dims to fit neural network input\n", " # (see https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/human-pose-estimation-3d-0001)\n", " scaled_img = cv2.resize(frame, dsize=(model.inputs[0].shape[3], model.inputs[0].shape[2]))\n", "\n", " if focal_length < 0: # Focal length is unknown\n", " focal_length = np.float32(0.8 * scaled_img.shape[1])\n", "\n", " # inference start\n", " start_time = time.time()\n", " # get results\n", " inference_result = model_infer(scaled_img, stride)\n", "\n", " # inference stop\n", " stop_time = time.time()\n", " processing_times.append(stop_time - start_time)\n", " # Process the point to point coordinates of the data\n", " poses_3d, poses_2d = engine.parse_poses(inference_result, 1, stride, focal_length, True)\n", "\n", " # use processing times from last 200 frames\n", " if len(processing_times) > 200:\n", " processing_times.popleft()\n", "\n", " processing_time = np.mean(processing_times) * 1000\n", " fps = 1000 / processing_time\n", "\n", " if len(poses_3d) > 0:\n", " # From here, you can rotate the 3D point positions using the function \"draw_poses\",\n", " # or you can directly make the correct mapping below to properly display the object image on the screen\n", " poses_3d_copy = poses_3d.copy()\n", " x = poses_3d_copy[:, 0::4]\n", " y = poses_3d_copy[:, 1::4]\n", " z = poses_3d_copy[:, 2::4]\n", " poses_3d[:, 0::4], poses_3d[:, 1::4], poses_3d[:, 2::4] = (\n", " -z + np.ones(poses_3d[:, 2::4].shape) * 200,\n", " -y + np.ones(poses_3d[:, 2::4].shape) * 100,\n", " -x,\n", " )\n", "\n", " poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3]\n", " people = skeleton(poses_3d=poses_3d)\n", "\n", " try:\n", " engine3D.scene_remove(skeleton_set)\n", " except Exception:\n", " pass\n", "\n", " engine3D.scene_add(people)\n", " skeleton_set = people\n", "\n", " # draw 2D\n", " frame = draw_poses(frame, poses_2d, scaled_img, use_popup)\n", "\n", " else:\n", " try:\n", " engine3D.scene_remove(skeleton_set)\n", " skeleton_set = None\n", " except Exception:\n", " pass\n", "\n", " cv2.putText(\n", " frame,\n", " f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n", " (10, 30),\n", " cv2.FONT_HERSHEY_COMPLEX,\n", " 0.7,\n", " (0, 0, 255),\n", " 1,\n", " cv2.LINE_AA,\n", " )\n", "\n", " if use_popup:\n", " cv2.imshow(title, frame)\n", " key = cv2.waitKey(1)\n", " # escape = 27, use ESC to exit\n", " if key == 27:\n", " break\n", " else:\n", " # encode numpy array to jpg\n", " imgbox.value = cv2.imencode(\n", " \".jpg\",\n", " frame,\n", " params=[cv2.IMWRITE_JPEG_QUALITY, 90],\n", " )[1].tobytes()\n", "\n", " engine3D.renderer.render(engine3D.scene, engine3D.cam)\n", "\n", " except KeyboardInterrupt:\n", " print(\"Interrupted\")\n", " except RuntimeError as e:\n", " print(e)\n", " finally:\n", " clear_output()\n", " if player is not None:\n", " # stop capturing\n", " player.stop()\n", " if use_popup:\n", " cv2.destroyAllWindows()\n", " if skeleton_set:\n", " engine3D.scene_remove(skeleton_set)" ] }, { "cell_type": "markdown", "id": "344840a6-9660-4a11-8b05-729ac2969e28", "metadata": {}, "source": [ "## Run\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Run, using 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**:\n", ">\n", "> *1. 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 (e.g. Binder), the webcam will not work.*\n", ">\n", "> *2. Popup mode may not work if you run this notebook on a remote computer (e.g. 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." ] }, { "cell_type": "markdown", "id": "d2d1a143-afcb-4f22-a4cc-657a080b70bf", "metadata": {}, "source": [ "Using the following method, you can click and move your mouse over the picture on the left to interact." ] }, { "cell_type": "code", "execution_count": null, "id": "3f82e298-5912-48c7-90b5-339aea3c177d", "metadata": { "tags": [] }, "outputs": [], "source": [ "USE_WEBCAM = False\n", "\n", "cam_id = 0\n", "video_path = \"https://github.com/intel-iot-devkit/sample-videos/raw/master/face-demographics-walking.mp4\"\n", "\n", "source = cam_id if USE_WEBCAM else video_path\n", "\n", "run_pose_estimation(source=source, flip=isinstance(source, int), 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.11.8" }, "openvino_notebooks": { "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/3D-pose-estimation-webcam/3D-pose-estimation.gif?raw=true", "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": 5 }