{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Visualization utilities\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>Try on [Colab](https://colab.research.google.com/github/pytorch/vision/blob/gh-pages/main/_generated_ipynb_notebooks/plot_visualization_utils.ipynb)\n    or `go to the end <sphx_glr_download_auto_examples_others_plot_visualization_utils.py>` to download the full example code.</p></div>\n\nThis example illustrates some of the utilities that torchvision offers for\nvisualizing images, bounding boxes, segmentation masks and keypoints.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torchvision.transforms.functional as F\n\n\nplt.rcParams[\"savefig.bbox\"] = 'tight'\n\n\ndef show(imgs):\n    if not isinstance(imgs, list):\n        imgs = [imgs]\n    fig, axs = plt.subplots(ncols=len(imgs), squeeze=False)\n    for i, img in enumerate(imgs):\n        img = img.detach()\n        img = F.to_pil_image(img)\n        axs[0, i].imshow(np.asarray(img))\n        axs[0, i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Visualizing a grid of images\nThe :func:`~torchvision.utils.make_grid` function can be used to create a\ntensor that represents multiple images in a grid.  This util requires a single\nimage of dtype ``uint8`` as input.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import make_grid\nfrom torchvision.io import decode_image\nfrom pathlib import Path\n\ndog1_int = decode_image(str(Path('../assets') / 'dog1.jpg'))\ndog2_int = decode_image(str(Path('../assets') / 'dog2.jpg'))\ndog_list = [dog1_int, dog2_int]\n\ngrid = make_grid(dog_list)\nshow(grid)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Visualizing bounding boxes\nWe can use :func:`~torchvision.utils.draw_bounding_boxes` to draw boxes on an\nimage. We can set the colors, labels, width as well as font and font size.\nThe boxes are in ``(xmin, ymin, xmax, ymax)`` format.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import draw_bounding_boxes\n\n\nboxes = torch.tensor([[50, 50, 100, 200], [210, 150, 350, 430]], dtype=torch.float)\ncolors = [\"blue\", \"yellow\"]\nresult = draw_bounding_boxes(dog1_int, boxes, colors=colors, width=5)\nshow(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Naturally, we can also plot bounding boxes produced by torchvision detection\nmodels.  Here is a demo with a Faster R-CNN model loaded from\n:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn`\nmodel. For more details on the output of such models, you may\nrefer to `instance_seg_output`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights\n\n\nweights = FasterRCNN_ResNet50_FPN_Weights.DEFAULT\ntransforms = weights.transforms()\n\nimages = [transforms(d) for d in dog_list]\n\nmodel = fasterrcnn_resnet50_fpn(weights=weights, progress=False)\nmodel = model.eval()\n\noutputs = model(images)\nprint(outputs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's plot the boxes detected by our model. We will only plot the boxes with a\nscore greater than a given threshold.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "score_threshold = .8\ndogs_with_boxes = [\n    draw_bounding_boxes(dog_int, boxes=output['boxes'][output['scores'] > score_threshold], width=4)\n    for dog_int, output in zip(dog_list, outputs)\n]\nshow(dogs_with_boxes)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Visualizing segmentation masks\nThe :func:`~torchvision.utils.draw_segmentation_masks` function can be used to\ndraw segmentation masks on images. Semantic segmentation and instance\nsegmentation models have different outputs, so we will treat each\nindependently.\n\n\n### Semantic segmentation models\n\nWe will see how to use it with torchvision's FCN Resnet-50, loaded with\n:func:`~torchvision.models.segmentation.fcn_resnet50`. Let's start by looking\nat the output of the model.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights\n\nweights = FCN_ResNet50_Weights.DEFAULT\ntransforms = weights.transforms(resize_size=None)\n\nmodel = fcn_resnet50(weights=weights, progress=False)\nmodel = model.eval()\n\nbatch = torch.stack([transforms(d) for d in dog_list])\noutput = model(batch)['out']\nprint(output.shape, output.min().item(), output.max().item())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As we can see above, the output of the segmentation model is a tensor of shape\n``(batch_size, num_classes, H, W)``. Each value is a non-normalized score, and\nwe can normalize them into ``[0, 1]`` by using a softmax. After the softmax,\nwe can interpret each value as a probability indicating how likely a given\npixel is to belong to a given class.\n\nLet's plot the masks that have been detected for the dog class and for the\nboat class:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "sem_class_to_idx = {cls: idx for (idx, cls) in enumerate(weights.meta[\"categories\"])}\n\nnormalized_masks = torch.nn.functional.softmax(output, dim=1)\n\ndog_and_boat_masks = [\n    normalized_masks[img_idx, sem_class_to_idx[cls]]\n    for img_idx in range(len(dog_list))\n    for cls in ('dog', 'boat')\n]\n\nshow(dog_and_boat_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As expected, the model is confident about the dog class, but not so much for\nthe boat class.\n\nThe :func:`~torchvision.utils.draw_segmentation_masks` function can be used to\nplots those masks on top of the original image. This function expects the\nmasks to be boolean masks, but our masks above contain probabilities in ``[0,\n1]``. To get boolean masks, we can do the following:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class_dim = 1\nboolean_dog_masks = (normalized_masks.argmax(class_dim) == sem_class_to_idx['dog'])\nprint(f\"shape = {boolean_dog_masks.shape}, dtype = {boolean_dog_masks.dtype}\")\nshow([m.float() for m in boolean_dog_masks])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The line above where we define ``boolean_dog_masks`` is a bit cryptic, but you\ncan read it as the following query: \"For which pixels is 'dog' the most likely\nclass?\"\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>While we're using the ``normalized_masks`` here, we would have\n  gotten the same result by using the non-normalized scores of the model\n  directly (as the softmax operation preserves the order).</p></div>\n\nNow that we have boolean masks, we can use them with\n:func:`~torchvision.utils.draw_segmentation_masks` to plot them on top of the\noriginal images:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import draw_segmentation_masks\n\ndogs_with_masks = [\n    draw_segmentation_masks(img, masks=mask, alpha=0.7)\n    for img, mask in zip(dog_list, boolean_dog_masks)\n]\nshow(dogs_with_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can plot more than one mask per image! Remember that the model returned as\nmany masks as there are classes. Let's ask the same query as above, but this\ntime for *all* classes, not just the dog class: \"For each pixel and each class\nC, is class C the most likely class?\"\n\nThis one is a bit more involved, so we'll first show how to do it with a\nsingle image, and then we'll generalize to the batch\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "num_classes = normalized_masks.shape[1]\ndog1_masks = normalized_masks[0]\nclass_dim = 0\ndog1_all_classes_masks = dog1_masks.argmax(class_dim) == torch.arange(num_classes)[:, None, None]\n\nprint(f\"dog1_masks shape = {dog1_masks.shape}, dtype = {dog1_masks.dtype}\")\nprint(f\"dog1_all_classes_masks = {dog1_all_classes_masks.shape}, dtype = {dog1_all_classes_masks.dtype}\")\n\ndog_with_all_masks = draw_segmentation_masks(dog1_int, masks=dog1_all_classes_masks, alpha=.6)\nshow(dog_with_all_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can see in the image above that only 2 masks were drawn: the mask for the\nbackground and the mask for the dog. This is because the model thinks that\nonly these 2 classes are the most likely ones across all the pixels. If the\nmodel had detected another class as the most likely among other pixels, we\nwould have seen its mask above.\n\nRemoving the background mask is as simple as passing\n``masks=dog1_all_classes_masks[1:]``, because the background class is the\nclass with index 0.\n\nLet's now do the same but for an entire batch of images. The code is similar\nbut involves a bit more juggling with the dimensions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class_dim = 1\nall_classes_masks = normalized_masks.argmax(class_dim) == torch.arange(num_classes)[:, None, None, None]\nprint(f\"shape = {all_classes_masks.shape}, dtype = {all_classes_masks.dtype}\")\n# The first dimension is the classes now, so we need to swap it\nall_classes_masks = all_classes_masks.swapaxes(0, 1)\n\ndogs_with_masks = [\n    draw_segmentation_masks(img, masks=mask, alpha=.6)\n    for img, mask in zip(dog_list, all_classes_masks)\n]\nshow(dogs_with_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n### Instance segmentation models\n\nInstance segmentation models have a significantly different output from the\nsemantic segmentation models. We will see here how to plot the masks for such\nmodels. Let's start by analyzing the output of a Mask-RCNN model. Note that\nthese models don't require the images to be normalized, so we don't need to\nuse the normalized batch.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>We will here describe the output of a Mask-RCNN model. The models in\n    `object_det_inst_seg_pers_keypoint_det` all have a similar output\n    format, but some of them may have extra info like keypoints for\n    :func:`~torchvision.models.detection.keypointrcnn_resnet50_fpn`, and some\n    of them may not have masks, like\n    :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn`.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.detection import maskrcnn_resnet50_fpn, MaskRCNN_ResNet50_FPN_Weights\n\nweights = MaskRCNN_ResNet50_FPN_Weights.DEFAULT\ntransforms = weights.transforms()\n\nimages = [transforms(d) for d in dog_list]\n\nmodel = maskrcnn_resnet50_fpn(weights=weights, progress=False)\nmodel = model.eval()\n\noutput = model(images)\nprint(output)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's break this down. For each image in the batch, the model outputs some\ndetections (or instances). The number of detections varies for each input\nimage. Each instance is described by its bounding box, its label, its score\nand its mask.\n\nThe way the output is organized is as follows: the output is a list of length\n``batch_size``. Each entry in the list corresponds to an input image, and it\nis a dict with keys 'boxes', 'labels', 'scores', and 'masks'. Each value\nassociated to those keys has ``num_instances`` elements in it.  In our case\nabove there are 3 instances detected in the first image, and 2 instances in\nthe second one.\n\nThe boxes can be plotted with :func:`~torchvision.utils.draw_bounding_boxes`\nas above, but here we're more interested in the masks. These masks are quite\ndifferent from the masks that we saw above for the semantic segmentation\nmodels.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dog1_output = output[0]\ndog1_masks = dog1_output['masks']\nprint(f\"shape = {dog1_masks.shape}, dtype = {dog1_masks.dtype}, \"\n      f\"min = {dog1_masks.min()}, max = {dog1_masks.max()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here the masks correspond to probabilities indicating, for each pixel, how\nlikely it is to belong to the predicted label of that instance. Those\npredicted labels correspond to the 'labels' element in the same output dict.\nLet's see which labels were predicted for the instances of the first image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(\"For the first dog, the following instances were detected:\")\nprint([weights.meta[\"categories\"][label] for label in dog1_output['labels']])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Interestingly, the model detects two persons in the image. Let's go ahead and\nplot those masks. Since :func:`~torchvision.utils.draw_segmentation_masks`\nexpects boolean masks, we need to convert those probabilities into boolean\nvalues. Remember that the semantic of those masks is \"How likely is this pixel\nto belong to the predicted class?\". As a result, a natural way of converting\nthose masks into boolean values is to threshold them with the 0.5 probability\n(one could also choose a different threshold).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "proba_threshold = 0.5\ndog1_bool_masks = dog1_output['masks'] > proba_threshold\nprint(f\"shape = {dog1_bool_masks.shape}, dtype = {dog1_bool_masks.dtype}\")\n\n# There's an extra dimension (1) to the masks. We need to remove it\ndog1_bool_masks = dog1_bool_masks.squeeze(1)\n\nshow(draw_segmentation_masks(dog1_int, dog1_bool_masks, alpha=0.9))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The model seems to have properly detected the dog, but it also confused trees\nwith people. Looking more closely at the scores will help us plot more\nrelevant masks:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(dog1_output['scores'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Clearly the model is more confident about the dog detection than it is about\nthe people detections. That's good news. When plotting the masks, we can ask\nfor only those that have a good score. Let's use a score threshold of .75\nhere, and also plot the masks of the second dog.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "score_threshold = .75\n\nboolean_masks = [\n    out['masks'][out['scores'] > score_threshold] > proba_threshold\n    for out in output\n]\n\ndogs_with_masks = [\n    draw_segmentation_masks(img, mask.squeeze(1))\n    for img, mask in zip(dog_list, boolean_masks)\n]\nshow(dogs_with_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The two 'people' masks in the first image where not selected because they have\na lower score than the score threshold. Similarly, in the second image, the\ninstance with class 15 (which corresponds to 'bench') was not selected.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n## Visualizing keypoints\nThe :func:`~torchvision.utils.draw_keypoints` function can be used to\ndraw keypoints on images. We will see how to use it with\ntorchvision's KeypointRCNN loaded with :func:`~torchvision.models.detection.keypointrcnn_resnet50_fpn`.\nWe will first have a look at output of the model.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.detection import keypointrcnn_resnet50_fpn, KeypointRCNN_ResNet50_FPN_Weights\nfrom torchvision.io import decode_image\n\nperson_int = decode_image(str(Path(\"../assets\") / \"person1.jpg\"))\n\nweights = KeypointRCNN_ResNet50_FPN_Weights.DEFAULT\ntransforms = weights.transforms()\n\nperson_float = transforms(person_int)\n\nmodel = keypointrcnn_resnet50_fpn(weights=weights, progress=False)\nmodel = model.eval()\n\noutputs = model([person_float])\nprint(outputs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As we see the output contains a list of dictionaries.\nThe output list is of length batch_size.\nWe currently have just a single image so length of list is 1.\nEach entry in the list corresponds to an input image,\nand it is a dict with keys `boxes`, `labels`, `scores`, `keypoints` and `keypoint_scores`.\nEach value associated to those keys has `num_instances` elements in it.\nIn our case above there are 2 instances detected in the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "kpts = outputs[0]['keypoints']\nscores = outputs[0]['scores']\n\nprint(kpts)\nprint(scores)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The KeypointRCNN model detects there are two instances in the image.\nIf you plot the boxes by using :func:`~draw_bounding_boxes`\nyou would recognize they are the person and the surfboard.\nIf we look at the scores, we will realize that the model is much more confident about the person than surfboard.\nWe could now set a threshold confidence and plot instances which we are confident enough.\nLet us set a threshold of 0.75 and filter out the keypoints corresponding to the person.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "detect_threshold = 0.75\nidx = torch.where(scores > detect_threshold)\nkeypoints = kpts[idx]\n\nprint(keypoints)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Great, now we have the keypoints corresponding to the person.\nEach keypoint is represented by x, y coordinates and the visibility.\nWe can now use the :func:`~torchvision.utils.draw_keypoints` function to draw keypoints.\nNote that the utility expects uint8 images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import draw_keypoints\n\nres = draw_keypoints(person_int, keypoints, colors=\"blue\", radius=3)\nshow(res)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As we see, the keypoints appear as colored circles over the image.\nThe coco keypoints for a person are ordered and represent the following list.\\\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coco_keypoints = [\n    \"nose\", \"left_eye\", \"right_eye\", \"left_ear\", \"right_ear\",\n    \"left_shoulder\", \"right_shoulder\", \"left_elbow\", \"right_elbow\",\n    \"left_wrist\", \"right_wrist\", \"left_hip\", \"right_hip\",\n    \"left_knee\", \"right_knee\", \"left_ankle\", \"right_ankle\",\n]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "What if we are interested in joining the keypoints?\nThis is especially useful in creating pose detection or action recognition.\nWe can join the keypoints easily using the `connectivity` parameter.\nA close observation would reveal that we would need to join the points in below\norder to construct human skeleton.\n\nnose -> left_eye -> left_ear.                              (0, 1), (1, 3)\n\nnose -> right_eye -> right_ear.                            (0, 2), (2, 4)\n\nnose -> left_shoulder -> left_elbow -> left_wrist.         (0, 5), (5, 7), (7, 9)\n\nnose -> right_shoulder -> right_elbow -> right_wrist.      (0, 6), (6, 8), (8, 10)\n\nleft_shoulder -> left_hip -> left_knee -> left_ankle.      (5, 11), (11, 13), (13, 15)\n\nright_shoulder -> right_hip -> right_knee -> right_ankle.  (6, 12), (12, 14), (14, 16)\n\nWe will create a list containing these keypoint ids to be connected.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "connect_skeleton = [\n    (0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (0, 6), (5, 7), (6, 8),\n    (7, 9), (8, 10), (5, 11), (6, 12), (11, 13), (12, 14), (13, 15), (14, 16)\n]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We pass the above list to the connectivity parameter to connect the keypoints.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res = draw_keypoints(person_int, keypoints, connectivity=connect_skeleton, colors=\"blue\", radius=4, width=3)\nshow(res)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "That looks pretty good.\n\n\n### Drawing Keypoints with Visibility\nLet's have a look at the results, another keypoint prediction module produced, and show the connectivity:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "prediction = torch.tensor(\n    [[[208.0176, 214.2409, 1.0000],\n      [000.0000, 000.0000, 0.0000],\n      [197.8246, 210.6392, 1.0000],\n      [000.0000, 000.0000, 0.0000],\n      [178.6378, 217.8425, 1.0000],\n      [221.2086, 253.8591, 1.0000],\n      [160.6502, 269.4662, 1.0000],\n      [243.9929, 304.2822, 1.0000],\n      [138.4654, 328.8935, 1.0000],\n      [277.5698, 340.8990, 1.0000],\n      [153.4551, 374.5145, 1.0000],\n      [000.0000, 000.0000, 0.0000],\n      [226.0053, 370.3125, 1.0000],\n      [221.8081, 455.5516, 1.0000],\n      [273.9723, 448.9486, 1.0000],\n      [193.6275, 546.1933, 1.0000],\n      [273.3727, 545.5930, 1.0000]]]\n)\n\nres = draw_keypoints(person_int, prediction, connectivity=connect_skeleton, colors=\"blue\", radius=4, width=3)\nshow(res)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "What happened there?\nThe model, which predicted the new keypoints,\ncan't detect the three points that are hidden on the upper left body of the skateboarder.\nMore precisely, the model predicted that `(x, y, vis) = (0, 0, 0)` for the left_eye, left_ear, and left_hip.\nSo we definitely don't want to display those keypoints and connections, and you don't have to.\nLooking at the parameters of :func:`~torchvision.utils.draw_keypoints`,\nwe can see that we can pass a visibility tensor as an additional argument.\nGiven the models' prediction, we have the visibility as the third keypoint dimension, we just need to extract it.\nLet's split the ``prediction`` into the keypoint coordinates and their respective visibility,\nand pass both of them as arguments to :func:`~torchvision.utils.draw_keypoints`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coordinates, visibility = prediction.split([2, 1], dim=-1)\nvisibility = visibility.bool()\n\nres = draw_keypoints(\n    person_int, coordinates, visibility=visibility, connectivity=connect_skeleton, colors=\"blue\", radius=4, width=3\n)\nshow(res)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can see that the undetected keypoints are not draw and the invisible keypoint connections were skipped.\nThis can reduce the noise on images with multiple detections, or in cases like ours,\nwhen the keypoint-prediction model missed some detections.\nMost torch keypoint-prediction models return the visibility for every prediction, ready for you to use it.\nThe :func:`~torchvision.models.detection.keypointrcnn_resnet50_fpn` model,\nwhich we used in the first case, does so too.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.22"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}