{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Repurposing masks into bounding boxes\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_repurposing_annotations.ipynb)\n    or `go to the end <sphx_glr_download_auto_examples_others_plot_repurposing_annotations.py>` to download the full example code.</p></div>\n\nThe following example illustrates the operations available\nthe `torchvision.ops <ops>` module for repurposing\nsegmentation masks into object localization annotations for different tasks\n(e.g. transforming masks used by instance and panoptic segmentation\nmethods into bounding boxes used by object detection methods).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\n\nimport torchvision.transforms.functional as F\n\n\nASSETS_DIRECTORY = \"../assets\"\n\nplt.rcParams[\"savefig.bbox\"] = \"tight\"\n\n\ndef show(imgs):\n    if not isinstance(imgs, list):\n        imgs = [imgs]\n    fix, 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": [
        "## Masks\nIn tasks like instance and panoptic segmentation, masks are commonly defined, and are defined by this package,\nas a multi-dimensional array (e.g. a NumPy array or a PyTorch tensor) with the following shape:\n\n      (num_objects, height, width)\n\nWhere num_objects is the number of annotated objects in the image. Each (height, width) object corresponds to exactly\none object. For example, if your input image has the dimensions 224 x 224 and has four annotated objects the shape\nof your masks annotation has the following shape:\n\n      (4, 224, 224).\n\nA nice property of masks is that they can be easily repurposed to be used in methods to solve a variety of object\nlocalization tasks.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Converting Masks to Bounding Boxes\nFor example, the :func:`~torchvision.ops.masks_to_boxes` operation can be used to\ntransform masks into bounding boxes that can be\nused as input to detection models such as FasterRCNN and RetinaNet.\nWe will take images and masks from the [PenFudan Dataset](https://www.cis.upenn.edu/~jshi/ped_html/).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.io import decode_image\n\nimg_path = os.path.join(ASSETS_DIRECTORY, \"FudanPed00054.png\")\nmask_path = os.path.join(ASSETS_DIRECTORY, \"FudanPed00054_mask.png\")\nimg = decode_image(img_path)\nmask = decode_image(mask_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here the masks are represented as a PNG Image, with floating point values.\nEach pixel is encoded as different colors, with 0 being background.\nNotice that the spatial dimensions of image and mask match.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(mask.size())\nprint(img.size())\nprint(mask)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We get the unique colors, as these would be the object ids.\nobj_ids = torch.unique(mask)\n\n# first id is the background, so remove it.\nobj_ids = obj_ids[1:]\n\n# split the color-encoded mask into a set of boolean masks.\n# Note that this snippet would work as well if the masks were float values instead of ints.\nmasks = mask == obj_ids[:, None, None]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now the masks are a boolean tensor.\nThe first dimension in this case 3 and denotes the number of instances: there are 3 people in the image.\nThe other two dimensions are height and width, which are equal to the dimensions of the image.\nFor each instance, the boolean tensors represent if the particular pixel\nbelongs to the segmentation mask of the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(masks.size())\nprint(masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us visualize an image and plot its corresponding segmentation masks.\nWe will use the :func:`~torchvision.utils.draw_segmentation_masks` to draw the segmentation masks.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import draw_segmentation_masks\n\ndrawn_masks = []\nfor mask in masks:\n    drawn_masks.append(draw_segmentation_masks(img, mask, alpha=0.8, colors=\"blue\"))\n\nshow(drawn_masks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To convert the boolean masks into bounding boxes.\nWe will use the :func:`~torchvision.ops.masks_to_boxes` from the torchvision.ops module\nIt returns the boxes in ``(xmin, ymin, xmax, ymax)`` format.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.ops import masks_to_boxes\n\nboxes = masks_to_boxes(masks)\nprint(boxes.size())\nprint(boxes)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As the shape denotes, there are 3 boxes and in ``(xmin, ymin, xmax, ymax)`` format.\nThese can be visualized very easily with :func:`~torchvision.utils.draw_bounding_boxes` utility\nprovided in `torchvision.utils <utils>`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import draw_bounding_boxes\n\ndrawn_boxes = draw_bounding_boxes(img, boxes, colors=\"red\")\nshow(drawn_boxes)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "These boxes can now directly be used by detection models in torchvision.\nHere is demo with a Faster R-CNN model loaded from\n:func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn`\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\nweights = FasterRCNN_ResNet50_FPN_Weights.DEFAULT\nmodel = fasterrcnn_resnet50_fpn(weights=weights, progress=False)\nprint(img.size())\n\ntransforms = weights.transforms()\nimg = transforms(img)\ntarget = {}\ntarget[\"boxes\"] = boxes\ntarget[\"labels\"] = labels = torch.ones((masks.size(0),), dtype=torch.int64)\ndetection_outputs = model(img.unsqueeze(0), [target])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Converting Segmentation Dataset to Detection Dataset\n\nWith this utility it becomes very simple to convert a segmentation dataset to a detection dataset.\nWith this we can now use a segmentation dataset to train a detection model.\nOne can similarly convert panoptic dataset to detection dataset.\nHere is an example where we re-purpose the dataset from the\n[PenFudan Detection Tutorial](https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class SegmentationToDetectionDataset(torch.utils.data.Dataset):\n    def __init__(self, root, transforms):\n        self.root = root\n        self.transforms = transforms\n        # load all image files, sorting them to\n        # ensure that they are aligned\n        self.imgs = list(sorted(os.listdir(os.path.join(root, \"PNGImages\"))))\n        self.masks = list(sorted(os.listdir(os.path.join(root, \"PedMasks\"))))\n\n    def __getitem__(self, idx):\n        # load images and masks\n        img_path = os.path.join(self.root, \"PNGImages\", self.imgs[idx])\n        mask_path = os.path.join(self.root, \"PedMasks\", self.masks[idx])\n\n        img = decode_image(img_path)\n        mask = decode_image(mask_path)\n\n        img = F.convert_image_dtype(img, dtype=torch.float)\n        mask = F.convert_image_dtype(mask, dtype=torch.float)\n\n        # We get the unique colors, as these would be the object ids.\n        obj_ids = torch.unique(mask)\n\n        # first id is the background, so remove it.\n        obj_ids = obj_ids[1:]\n\n        # split the color-encoded mask into a set of boolean masks.\n        masks = mask == obj_ids[:, None, None]\n\n        boxes = masks_to_boxes(masks)\n\n        # there is only one class\n        labels = torch.ones((masks.shape[0],), dtype=torch.int64)\n\n        target = {}\n        target[\"boxes\"] = boxes\n        target[\"labels\"] = labels\n\n        if self.transforms is not None:\n            img, target = self.transforms(img, target)\n\n        return img, target"
      ]
    }
  ],
  "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
}