{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "context_rcnn_tutorial.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jZc1kMel3sZP",
        "colab_type": "text"
      },
      "source": [
        "# Context R-CNN Demo\n",
        "\n",
        "<table align=\"left\"><td>\n",
        "  <a target=\"_blank\"  href=\"https://colab.sandbox.google.com/github/tensorflow/models/blob/master/research/object_detection/colab_tutorials/context_rcnn_tutorial.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab\n",
        "  </a>\n",
        "</td><td>\n",
        "  <a target=\"_blank\"  href=\"https://github.com/tensorflow/models/blob/master/research/object_detection/colab_tutorials/context_rcnn_tutorial.ipynb\">\n",
        "    <img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "</td></table>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XuHWvdag3_b9",
        "colab_type": "text"
      },
      "source": [
        " This notebook will walk you step by step through the process of using a pre-trained model to build up a contextual memory bank for a set of images, and then detect objects in those images+context using [Context R-CNN](https://arxiv.org/abs/1912.03538)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "u0e-OOtn4hQ8",
        "colab_type": "text"
      },
      "source": [
        "# Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w-UrhxBw4iLA",
        "colab_type": "text"
      },
      "source": [
        "Important: If you're running on a local machine, be sure to follow the [installation instructions](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md). This notebook includes only what's necessary to run in Colab."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SAqMxS4V4lqS",
        "colab_type": "text"
      },
      "source": [
        "### Install"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BPkovrxF4o8n",
        "colab_type": "code",
        "outputId": "e1b8debc-ab73-4b3e-9e44-c86446c7cda1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 785
        }
      },
      "source": [
        "!pip install -U --pre tensorflow==\"2.*\"\n",
        "!pip install tf_slim"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Requirement already up-to-date: tensorflow==2.* in /usr/local/lib/python3.6/dist-packages (2.2.0)\n",
            "Requirement already satisfied, skipping upgrade: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.4.1)\n",
            "Requirement already satisfied, skipping upgrade: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (3.10.0)\n",
            "Requirement already satisfied, skipping upgrade: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (2.10.0)\n",
            "Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (3.2.1)\n",
            "Requirement already satisfied, skipping upgrade: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.18.5)\n",
            "Requirement already satisfied, skipping upgrade: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (0.34.2)\n",
            "Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (0.9.0)\n",
            "Requirement already satisfied, skipping upgrade: tensorflow-estimator<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (2.2.0)\n",
            "Requirement already satisfied, skipping upgrade: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (0.2.0)\n",
            "Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.29.0)\n",
            "Requirement already satisfied, skipping upgrade: tensorboard<2.3.0,>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (2.2.2)\n",
            "Requirement already satisfied, skipping upgrade: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (0.3.3)\n",
            "Requirement already satisfied, skipping upgrade: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.6.3)\n",
            "Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.1.2)\n",
            "Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.1.0)\n",
            "Requirement already satisfied, skipping upgrade: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.12.0)\n",
            "Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.*) (1.12.1)\n",
            "Requirement already satisfied, skipping upgrade: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.8.0->tensorflow==2.*) (47.1.1)\n",
            "Requirement already satisfied, skipping upgrade: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.7.2)\n",
            "Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.0.1)\n",
            "Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (2.23.0)\n",
            "Requirement already satisfied, skipping upgrade: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (0.4.1)\n",
            "Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (3.2.2)\n",
            "Requirement already satisfied, skipping upgrade: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.6.0.post3)\n",
            "Requirement already satisfied, skipping upgrade: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (3.1.1)\n",
            "Requirement already satisfied, skipping upgrade: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (4.0)\n",
            "Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (0.2.8)\n",
            "Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (2.9)\n",
            "Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (3.0.4)\n",
            "Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (2020.4.5.1)\n",
            "Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.24.3)\n",
            "Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.3.0)\n",
            "Requirement already satisfied, skipping upgrade: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (1.6.0)\n",
            "Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /usr/local/lib/python3.6/dist-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (0.4.8)\n",
            "Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (3.1.0)\n",
            "Requirement already satisfied, skipping upgrade: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.*) (3.1.0)\n",
            "Collecting tf_slim\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n",
            "\u001b[K     |████████████████████████████████| 358kB 2.8MB/s \n",
            "\u001b[?25hRequirement already satisfied: absl-py>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from tf_slim) (0.9.0)\n",
            "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py>=0.2.2->tf_slim) (1.12.0)\n",
            "Installing collected packages: tf-slim\n",
            "Successfully installed tf-slim-1.1.0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zpKF8a2x4tec",
        "colab_type": "text"
      },
      "source": [
        "Make sure you have `pycocotools` installed"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "owcrp0AW4uCg",
        "colab_type": "code",
        "outputId": "001148a8-b0a8-43a1-f6df-225d86d90b8f",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        }
      },
      "source": [
        "!pip install pycocotools"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Requirement already satisfied: pycocotools in /usr/local/lib/python3.6/dist-packages (2.0.0)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wHFSRVaO4wuq",
        "colab_type": "text"
      },
      "source": [
        "Get `tensorflow/models` or `cd` to parent directory of the repository."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "E0ZuGKoi4wTn",
        "colab_type": "code",
        "outputId": "2b5d93cb-3548-4347-9b76-ce12bea44a56",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 136
        }
      },
      "source": [
        "import os\n",
        "import pathlib\n",
        "\n",
        "\n",
        "if \"models\" in pathlib.Path.cwd().parts:\n",
        "  while \"models\" in pathlib.Path.cwd().parts:\n",
        "    os.chdir('..')\n",
        "elif not pathlib.Path('models').exists():\n",
        "  !git clone --depth 1 https://github.com/tensorflow/models"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Cloning into 'models'...\n",
            "remote: Enumerating objects: 2694, done.\u001b[K\n",
            "remote: Counting objects: 100% (2694/2694), done.\u001b[K\n",
            "remote: Compressing objects: 100% (2370/2370), done.\u001b[K\n",
            "remote: Total 2694 (delta 520), reused 1332 (delta 290), pack-reused 0\u001b[K\n",
            "Receiving objects: 100% (2694/2694), 34.10 MiB | 29.32 MiB/s, done.\n",
            "Resolving deltas: 100% (520/520), done.\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GkqRm-WY47MR",
        "colab_type": "text"
      },
      "source": [
        "Compile protobufs and install the object_detection package"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "62Dn1_YU45O2",
        "colab_type": "code",
        "outputId": "439166dd-6202-4ff9-897d-100a35ae5af5",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        }
      },
      "source": [
        "%%bash\n",
        "cd models/research/\n",
        "protoc object_detection/protos/*.proto --python_out=."
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "object_detection/protos/input_reader.proto: warning: Import object_detection/protos/image_resizer.proto but not used.\n"
          ],
          "name": "stderr"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "83kNiD-24-ZB",
        "colab_type": "code",
        "outputId": "aa148939-7dcc-4fbd-ea48-41236523712c",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 343
        }
      },
      "source": [
        "%%bash \n",
        "cd models/research\n",
        "pip install ."
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Processing /content/models/research\n",
            "Requirement already satisfied: Pillow>=1.0 in /usr/local/lib/python3.6/dist-packages (from object-detection==0.1) (7.0.0)\n",
            "Requirement already satisfied: Matplotlib>=2.1 in /usr/local/lib/python3.6/dist-packages (from object-detection==0.1) (3.2.1)\n",
            "Requirement already satisfied: Cython>=0.28.1 in /usr/local/lib/python3.6/dist-packages (from object-detection==0.1) (0.29.19)\n",
            "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from Matplotlib>=2.1->object-detection==0.1) (0.10.0)\n",
            "Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from Matplotlib>=2.1->object-detection==0.1) (2.4.7)\n",
            "Requirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.6/dist-packages (from Matplotlib>=2.1->object-detection==0.1) (1.18.5)\n",
            "Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from Matplotlib>=2.1->object-detection==0.1) (2.8.1)\n",
            "Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from Matplotlib>=2.1->object-detection==0.1) (1.2.0)\n",
            "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->Matplotlib>=2.1->object-detection==0.1) (1.12.0)\n",
            "Building wheels for collected packages: object-detection\n",
            "  Building wheel for object-detection (setup.py): started\n",
            "  Building wheel for object-detection (setup.py): finished with status 'done'\n",
            "  Created wheel for object-detection: filename=object_detection-0.1-cp36-none-any.whl size=1141324 sha256=1dff68de415a4ccc3af0e20b8f409a73d147d79720a713dcdc30f9bc8d4ab3a2\n",
            "  Stored in directory: /tmp/pip-ephem-wheel-cache-rlyj8yrw/wheels/94/49/4b/39b051683087a22ef7e80ec52152a27249d1a644ccf4e442ea\n",
            "Successfully built object-detection\n",
            "Installing collected packages: object-detection\n",
            "Successfully installed object-detection-0.1\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LBdjK2G5ywuc"
      },
      "source": [
        "### Imports"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "hV4P5gyTWKMI",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "import os\n",
        "import six\n",
        "import six.moves.urllib as urllib\n",
        "import sys\n",
        "import tarfile\n",
        "import tensorflow as tf\n",
        "import zipfile\n",
        "import pathlib\n",
        "import json\n",
        "import datetime\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "from collections import defaultdict\n",
        "from io import StringIO\n",
        "from matplotlib import pyplot as plt\n",
        "from PIL import Image\n",
        "from IPython.display import display"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "r5FNuiRPWKMN"
      },
      "source": [
        "Import the object detection module."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "4-IMl4b6BdGO",
        "colab": {}
      },
      "source": [
        "from object_detection.utils import ops as utils_ops\n",
        "from object_detection.utils import label_map_util\n",
        "from object_detection.utils import visualization_utils as vis_utils"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "RYPCiag2iz_q"
      },
      "source": [
        "Patches:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "mF-YlMl8c_bM",
        "colab": {}
      },
      "source": [
        "# patch tf1 into `utils.ops`\n",
        "utils_ops.tf = tf.compat.v1\n",
        "\n",
        "# Patch the location of gfile\n",
        "tf.gfile = tf.io.gfile"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cfn_tRFOWKMO"
      },
      "source": [
        "# Model preparation "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7ai8pLZZWKMS"
      },
      "source": [
        "## Loader"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zm8xp-0eoItE",
        "colab": {}
      },
      "source": [
        "def load_model(model_name):\n",
        "  base_url = 'http://download.tensorflow.org/models/object_detection/'\n",
        "  model_file = model_name + '.tar.gz'\n",
        "  model_dir = tf.keras.utils.get_file(\n",
        "    fname=model_name,\n",
        "    origin=base_url + model_file,\n",
        "    untar=True)\n",
        "\n",
        "  model_dir = pathlib.Path(model_dir)/\"saved_model\"\n",
        "  model = tf.saved_model.load(str(model_dir))\n",
        "  model = model.signatures['serving_default']\n",
        "\n",
        "  return model"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "_1MVVTcLWKMW"
      },
      "source": [
        "## Loading label map\n",
        "Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `zebra`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "hDbpHkiWWKMX",
        "colab": {}
      },
      "source": [
        "# List of the strings that is used to add correct label for each box.\n",
        "PATH_TO_LABELS = 'models/research/object_detection/data/snapshot_serengeti_label_map.pbtxt'\n",
        "category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=False)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "oVU3U_J6IJVb"
      },
      "source": [
        "We will test on a context group of images from one month at one camera from the Snapshot Serengeti val split defined on [LILA.science](http://lila.science/datasets/snapshot-serengeti), which was not seen during model training:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "jG-zn5ykWKMd",
        "outputId": "c7bbbb2f-0f6e-4380-fd92-c88c088bd766",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85
        }
      },
      "source": [
        "# If you want to test the code with your images, just add path to the images to\n",
        "# the TEST_IMAGE_PATHS.\n",
        "PATH_TO_TEST_IMAGES_DIR = pathlib.Path('models/research/object_detection/test_images/snapshot_serengeti')\n",
        "TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob(\"*.jpeg\")))\n",
        "TEST_IMAGE_PATHS"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[PosixPath('models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0038.jpeg'),\n",
              " PosixPath('models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0039.jpeg'),\n",
              " PosixPath('models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0040.jpeg'),\n",
              " PosixPath('models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0041.jpeg')]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oBcQzptnQ-x6",
        "colab_type": "text"
      },
      "source": [
        "Load the metadata for each image"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZLLINOHcQ-An",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "test_data_json = 'models/research/object_detection/test_images/snapshot_serengeti/context_rcnn_demo_metadata.json'\n",
        "with open(test_data_json, 'r') as f:\n",
        "  test_metadata = json.load(f)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BgGTPHhkOAel",
        "colab_type": "code",
        "outputId": "1421a32a-c208-498f-931f-1bfeb25d6488",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 105
        }
      },
      "source": [
        "image_id_to_datetime = {im['id']:im['date_captured'] for im in test_metadata['images']}\n",
        "image_path_to_id = {im['file_name']: im['id'] \n",
        "                    for im in test_metadata['images']}\n",
        "image_path_to_id"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0038.jpeg': 'S1/E03/E03_R3/S1_E03_R3_PICT0038',\n",
              " 'models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0039.jpeg': 'S1/E03/E03_R3/S1_E03_R3_PICT0039',\n",
              " 'models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0040.jpeg': 'S1/E03/E03_R3/S1_E03_R3_PICT0040',\n",
              " 'models/research/object_detection/test_images/snapshot_serengeti/S1_E03_R3_PICT0041.jpeg': 'S1/E03/E03_R3/S1_E03_R3_PICT0041'}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 13
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "H0_1AGhrWKMc"
      },
      "source": [
        "# Generate Context Features for each image"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kt3_pPQOj7ii",
        "colab_type": "code",
        "outputId": "fc72e978-f576-43f4-bcf1-3eb49fef5726",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 88
        }
      },
      "source": [
        "faster_rcnn_model_name = 'faster_rcnn_resnet101_snapshot_serengeti_2020_06_10'\n",
        "faster_rcnn_model = load_model(faster_rcnn_model_name)"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Downloading data from http://download.tensorflow.org/models/object_detection/faster_rcnn_resnet101_snapshot_serengeti_2020_06_10.tar.gz\n",
            "588832768/588829839 [==============================] - 3s 0us/step\n",
            "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "k6Clkv_mBo_U",
        "colab_type": "text"
      },
      "source": [
        "Check the model's input signature, it expects a batch of 3-color images of type uint8."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "H1qNlFESBsTR",
        "colab_type": "code",
        "outputId": "9b8b84e0-d7a8-4ec9-d6e0-22d574cb6209",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        }
      },
      "source": [
        "faster_rcnn_model.inputs"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[<tf.Tensor 'image_tensor:0' shape=(None, None, None, 3) dtype=uint8>]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eYS8KpRCBtBH",
        "colab_type": "text"
      },
      "source": [
        "And it returns several outputs. Note this model has been exported with additional output 'detection_features' which will be used to build the contextual memory bank."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5M-1yxgfkmQl",
        "colab_type": "code",
        "outputId": "1da98c3b-79c5-4d19-d64c-3e9dbadc97c0",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 153
        }
      },
      "source": [
        "faster_rcnn_model.output_dtypes"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'detection_boxes': tf.float32,\n",
              " 'detection_classes': tf.float32,\n",
              " 'detection_features': tf.float32,\n",
              " 'detection_multiclass_scores': tf.float32,\n",
              " 'detection_scores': tf.float32,\n",
              " 'num_detections': tf.float32,\n",
              " 'raw_detection_boxes': tf.float32,\n",
              " 'raw_detection_scores': tf.float32}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 16
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zVjNFFNIDCst",
        "colab_type": "code",
        "outputId": "edb46db0-05fb-4952-bc88-db09d7811b01",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 153
        }
      },
      "source": [
        "faster_rcnn_model.output_shapes"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'detection_boxes': TensorShape([None, 300, 4]),\n",
              " 'detection_classes': TensorShape([None, 300]),\n",
              " 'detection_features': TensorShape([None, None, None, None, None]),\n",
              " 'detection_multiclass_scores': TensorShape([None, 300, 49]),\n",
              " 'detection_scores': TensorShape([None, 300]),\n",
              " 'num_detections': TensorShape([None]),\n",
              " 'raw_detection_boxes': TensorShape([None, 300, 4]),\n",
              " 'raw_detection_scores': TensorShape([None, 300, 49])}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JP5qZ7sXJpwG"
      },
      "source": [
        "Add a wrapper function to call the model, and cleanup the outputs:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ajmR_exWyN76",
        "colab": {}
      },
      "source": [
        "def run_inference_for_single_image(model, image):\n",
        "  '''Run single image through tensorflow object detection saved_model.\n",
        "\n",
        "  This function runs a saved_model on a (single) provided image and returns\n",
        "  inference results in numpy arrays.\n",
        "\n",
        "  Args:\n",
        "    model: tensorflow saved_model. This model can be obtained using \n",
        "      export_inference_graph.py.\n",
        "    image: uint8 numpy array with shape (img_height, img_width, 3)\n",
        "\n",
        "  Returns:\n",
        "    output_dict: a dictionary holding the following entries:\n",
        "      `num_detections`: an integer\n",
        "      `detection_boxes`: a numpy (float32) array of shape [N, 4]\n",
        "      `detection_classes`: a numpy (uint8) array of shape [N]\n",
        "      `detection_scores`: a numpy (float32) array of shape [N]\n",
        "      `detection_features`: a numpy (float32) array of shape [N, 7, 7, 2048]\n",
        "  '''\n",
        "  image = np.asarray(image)\n",
        "  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.\n",
        "  input_tensor = tf.convert_to_tensor(image)\n",
        "  # The model expects a batch of images, so add an axis with `tf.newaxis`.\n",
        "  input_tensor = input_tensor[tf.newaxis,...]\n",
        "\n",
        "  # Run inference\n",
        "  output_dict = model(input_tensor)\n",
        "  # All outputs are batches tensors.\n",
        "  # Convert to numpy arrays, and take index [0] to remove the batch dimension.\n",
        "  # We're only interested in the first num_detections.\n",
        "  num_dets = output_dict.pop('num_detections')\n",
        "  num_detections = int(num_dets)\n",
        "  for key,value in output_dict.items():\n",
        "    output_dict[key] = value[0, :num_detections].numpy() \n",
        "  output_dict['num_detections'] = num_detections\n",
        "\n",
        "  # detection_classes should be ints.\n",
        "  output_dict['detection_classes'] = output_dict['detection_classes'].astype(\n",
        "      np.int64)\n",
        "  return output_dict"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "un5SXxIxMaaV",
        "colab_type": "text"
      },
      "source": [
        "Functions for embedding context features"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qvtvAZFDMoTM",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def embed_date_captured(date_captured):\n",
        "  \"\"\"Encodes the datetime of the image.\n",
        "\n",
        "  Takes a datetime object and encodes it into a normalized embedding of shape \n",
        "  [5], using hard-coded normalization factors for year, month, day, hour,\n",
        "  minute.\n",
        "\n",
        "  Args:\n",
        "    date_captured: A datetime object.\n",
        "\n",
        "  Returns:\n",
        "    A numpy float32 embedding of shape [5].\n",
        "  \"\"\"\n",
        "  embedded_date_captured = []\n",
        "  month_max = 12.0\n",
        "  day_max = 31.0\n",
        "  hour_max = 24.0\n",
        "  minute_max = 60.0\n",
        "  min_year = 1990.0\n",
        "  max_year = 2030.0\n",
        "\n",
        "  year = (date_captured.year-min_year)/float(max_year-min_year)\n",
        "  embedded_date_captured.append(year)\n",
        "\n",
        "  month = (date_captured.month-1)/month_max\n",
        "  embedded_date_captured.append(month)\n",
        "\n",
        "  day = (date_captured.day-1)/day_max\n",
        "  embedded_date_captured.append(day)\n",
        "\n",
        "  hour = date_captured.hour/hour_max\n",
        "  embedded_date_captured.append(hour)\n",
        "\n",
        "  minute = date_captured.minute/minute_max\n",
        "  embedded_date_captured.append(minute)\n",
        "\n",
        "  return np.asarray(embedded_date_captured)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xN8k5daOOA7b",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def embed_position_and_size(box):\n",
        "  \"\"\"Encodes the bounding box of the object of interest.\n",
        "\n",
        "  Takes a bounding box and encodes it into a normalized embedding of shape \n",
        "  [4] - the center point (x,y) and width and height of the box.\n",
        "\n",
        "  Args:\n",
        "    box: A bounding box, formatted as [ymin, xmin, ymax, xmax].\n",
        "\n",
        "  Returns:\n",
        "    A numpy float32 embedding of shape [4].\n",
        "  \"\"\"\n",
        "  ymin = box[0]\n",
        "  xmin = box[1]\n",
        "  ymax = box[2]\n",
        "  xmax = box[3]\n",
        "  w = xmax - xmin\n",
        "  h = ymax - ymin\n",
        "  x = xmin + w / 2.0\n",
        "  y = ymin + h / 2.0\n",
        "  return np.asarray([x, y, w, h])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lJe2qy8HPc6Z",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def get_context_feature_embedding(date_captured, detection_boxes,\n",
        "                                  detection_features, detection_scores):\n",
        "  \"\"\"Extracts representative feature embedding for a given input image.\n",
        "\n",
        "  Takes outputs of a detection model and focuses on the highest-confidence\n",
        "  detected object. Starts with detection_features and uses average pooling to\n",
        "  remove the spatial dimensions, then appends an embedding of the box position\n",
        "  and size, and an embedding of the date and time the image was captured,\n",
        "  returning a one-dimensional representation of the object.\n",
        "\n",
        "  Args:\n",
        "    date_captured: A datetime string of format '%Y-%m-%d %H:%M:%S'.\n",
        "    detection_features: A numpy (float32) array of shape [N, 7, 7, 2048].\n",
        "    detection_boxes: A numpy (float32) array of shape [N, 4].\n",
        "    detection_scores: A numpy (float32) array of shape [N].\n",
        "\n",
        "  Returns:\n",
        "    A numpy float32 embedding of shape [2057].\n",
        "  \"\"\"\n",
        "  date_captured = datetime.datetime.strptime(date_captured,'%Y-%m-%d %H:%M:%S')\n",
        "  temporal_embedding = embed_date_captured(date_captured)\n",
        "  embedding = detection_features[0]\n",
        "  pooled_embedding = np.mean(np.mean(embedding, axis=1), axis=0)\n",
        "  box = detection_boxes[0]\n",
        "  position_embedding = embed_position_and_size(box)\n",
        "  bb_embedding = np.concatenate((pooled_embedding, position_embedding))\n",
        "  embedding = np.expand_dims(np.concatenate((bb_embedding,temporal_embedding)),\n",
        "                             axis=0)\n",
        "  score = detection_scores[0]\n",
        "  return embedding, score"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "z1wq0LVyMRR_"
      },
      "source": [
        "Run it on each test image and use the output detection features and metadata to build up a context feature bank:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "DWh_1zz6aqxs",
        "colab": {}
      },
      "source": [
        "def run_inference(model, image_path, date_captured, resize_image=True):\n",
        "  \"\"\"Runs inference over a single input image and extracts contextual features.\n",
        "\n",
        "  Args:\n",
        "    model: A tensorflow saved_model object.\n",
        "    image_path: Absolute path to the input image.\n",
        "    date_captured: A datetime string of format '%Y-%m-%d %H:%M:%S'.\n",
        "    resize_image: Whether to resize the input image before running inference.\n",
        "\n",
        "  Returns:\n",
        "    context_feature: A numpy float32 array of shape [2057].\n",
        "    score: A numpy float32 object score for the embedded object.\n",
        "    output_dict: The saved_model output dictionary for the image.\n",
        "  \"\"\"\n",
        "  with open(image_path,'rb') as f:\n",
        "    image = Image.open(f)\n",
        "    if resize_image:\n",
        "      image.thumbnail((640,640),Image.ANTIALIAS)\n",
        "    image_np = np.array(image)\n",
        "\n",
        "  # Actual detection.\n",
        "  output_dict = run_inference_for_single_image(model, image_np)\n",
        "\n",
        "  context_feature, score = get_context_feature_embedding(\n",
        "      date_captured, output_dict['detection_boxes'],\n",
        "      output_dict['detection_features'], output_dict['detection_scores'])\n",
        "  return context_feature, score, output_dict"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "3a5wMHN8WKMh",
        "colab": {}
      },
      "source": [
        "context_features = []\n",
        "scores = []\n",
        "faster_rcnn_results = {}\n",
        "for image_path in TEST_IMAGE_PATHS:\n",
        "  image_id = image_path_to_id[str(image_path)]\n",
        "  date_captured = image_id_to_datetime[image_id]\n",
        "  context_feature, score, results = run_inference(\n",
        "      faster_rcnn_model, image_path, date_captured)\n",
        "  faster_rcnn_results[image_id] = results\n",
        "  context_features.append(context_feature)\n",
        "  scores.append(score)\n",
        "\n",
        "# Concatenate all extracted context embeddings into a contextual memory bank.\n",
        "context_features_matrix = np.concatenate(context_features, axis=0)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DsspMPX3Cssg"
      },
      "source": [
        "## Run Detection With Context"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "f7aOtOlebK7h"
      },
      "source": [
        "Load a context r-cnn object detection model:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "1XNT0wxybKR6",
        "outputId": "cc5b0677-cf16-46c2-9ae5-32681725f856",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 88
        }
      },
      "source": [
        "context_rcnn_model_name = 'context_rcnn_resnet101_snapshot_serengeti_2020_06_10'\n",
        "context_rcnn_model = load_model(context_rcnn_model_name)\n"
      ],
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Downloading data from http://download.tensorflow.org/models/object_detection/context_rcnn_resnet101_snapshot_serengeti_2020_06_10.tar.gz\n",
            "724664320/724658931 [==============================] - 3s 0us/step\n",
            "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G6IGGtGqBH6y",
        "colab_type": "text"
      },
      "source": [
        "We need to define the expected context padding size for the\n",
        "model, this must match the definition in the model config (max_num_context_features)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4oh9XNLBjkTL",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "context_padding_size = 2000"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "yN1AYfAEJIGp"
      },
      "source": [
        "Check the model's input signature, it expects a batch of 3-color images of type uint8, plus context_features padded to the maximum context feature size for this model (2000) and valid_context_size to represent the non-padded context features: "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "CK4cnry6wsHY",
        "outputId": "d77af014-769f-4e20-b4ac-bfdd40502128",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 68
        }
      },
      "source": [
        "context_rcnn_model.inputs"
      ],
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[<tf.Tensor 'image_tensor:0' shape=(1, None, None, 3) dtype=uint8>,\n",
              " <tf.Tensor 'context_features:0' shape=(1, 2000, 2057) dtype=float32>,\n",
              " <tf.Tensor 'valid_context_size:0' shape=(1,) dtype=int32>]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 26
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Q8u3BjpMJXZF"
      },
      "source": [
        "And returns several outputs:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "oLSZpfaYwuSk",
        "outputId": "63a3903f-529b-41f9-b742-9b81c4c5e096",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 136
        }
      },
      "source": [
        "context_rcnn_model.output_dtypes"
      ],
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'detection_boxes': tf.float32,\n",
              " 'detection_classes': tf.float32,\n",
              " 'detection_multiclass_scores': tf.float32,\n",
              " 'detection_scores': tf.float32,\n",
              " 'num_detections': tf.float32,\n",
              " 'raw_detection_boxes': tf.float32,\n",
              " 'raw_detection_scores': tf.float32}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "FZyKUJeuxvpT",
        "outputId": "d2feeaba-2bb2-4779-a96a-94a8a0aff362",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 136
        }
      },
      "source": [
        "context_rcnn_model.output_shapes"
      ],
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'detection_boxes': TensorShape([1, 300, 4]),\n",
              " 'detection_classes': TensorShape([1, 300]),\n",
              " 'detection_multiclass_scores': TensorShape([1, 300, 49]),\n",
              " 'detection_scores': TensorShape([1, 300]),\n",
              " 'num_detections': TensorShape([1]),\n",
              " 'raw_detection_boxes': TensorShape([1, 300, 4]),\n",
              " 'raw_detection_scores': TensorShape([1, 300, 49])}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 28
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "CzkVv_n2MxKC",
        "colab": {}
      },
      "source": [
        "def run_context_rcnn_inference_for_single_image(\n",
        "    model, image, context_features, context_padding_size):\n",
        "  '''Run single image through a Context R-CNN saved_model.\n",
        "\n",
        "  This function runs a saved_model on a (single) provided image and provided \n",
        "  contextual features and returns inference results in numpy arrays.\n",
        "\n",
        "  Args:\n",
        "    model: tensorflow Context R-CNN saved_model. This model can be obtained\n",
        "      using export_inference_graph.py and setting side_input fields. \n",
        "      Example export call - \n",
        "        python export_inference_graph.py \\\n",
        "          --input_type image_tensor \\\n",
        "          --pipeline_config_path /path/to/context_rcnn_model.config \\\n",
        "          --trained_checkpoint_prefix /path/to/context_rcnn_model.ckpt \\\n",
        "          --output_directory /path/to/output_dir \\\n",
        "          --use_side_inputs True \\\n",
        "          --side_input_shapes 1,2000,2057/1 \\\n",
        "          --side_input_names context_features,valid_context_size \\\n",
        "          --side_input_types float,int \\\n",
        "          --input_shape 1,-1,-1,3\n",
        "\n",
        "    image: uint8 numpy array with shape (img_height, img_width, 3)\n",
        "    context_features: A numpy float32 contextual memory bank of shape \n",
        "      [num_context_examples, 2057]\n",
        "    context_padding_size: The amount of expected padding in the contextual\n",
        "      memory bank, defined in the Context R-CNN config as \n",
        "      max_num_context_features.\n",
        "\n",
        "  Returns:\n",
        "    output_dict: a dictionary holding the following entries:\n",
        "      `num_detections`: an integer\n",
        "      `detection_boxes`: a numpy (float32) array of shape [N, 4]\n",
        "      `detection_classes`: a numpy (uint8) array of shape [N]\n",
        "      `detection_scores`: a numpy (float32) array of shape [N]\n",
        "  '''\n",
        "  image = np.asarray(image)\n",
        "  # The input image needs to be a tensor, convert it using \n",
        "  # `tf.convert_to_tensor`.\n",
        "  image_tensor = tf.convert_to_tensor(\n",
        "      image, name='image_tensor')[tf.newaxis,...]\n",
        "\n",
        "  context_features = np.asarray(context_features)\n",
        "  valid_context_size = context_features.shape[0]\n",
        "  valid_context_size_tensor = tf.convert_to_tensor(\n",
        "      valid_context_size, name='valid_context_size')[tf.newaxis,...]\n",
        "  padded_context_features = np.pad(\n",
        "      context_features,\n",
        "      ((0,context_padding_size-valid_context_size),(0,0)), mode='constant')\n",
        "  padded_context_features_tensor = tf.convert_to_tensor(\n",
        "      padded_context_features,\n",
        "      name='context_features',\n",
        "      dtype=tf.float32)[tf.newaxis,...]\n",
        "\n",
        "  # Run inference\n",
        "  output_dict = model(\n",
        "      inputs=image_tensor,\n",
        "      context_features=padded_context_features_tensor,\n",
        "      valid_context_size=valid_context_size_tensor)\n",
        "  # All outputs are batches tensors.\n",
        "  # Convert to numpy arrays, and take index [0] to remove the batch dimension.\n",
        "  # We're only interested in the first num_detections.\n",
        "  num_dets = output_dict.pop('num_detections')\n",
        "  num_detections = int(num_dets)\n",
        "  for key,value in output_dict.items():\n",
        "    output_dict[key] = value[0, :num_detections].numpy() \n",
        "  output_dict['num_detections'] = num_detections\n",
        "\n",
        "  # detection_classes should be ints.\n",
        "  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)\n",
        "  return output_dict"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "0FqVkR3Agc6U",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def show_context_rcnn_inference(\n",
        "    model, image_path, context_features, faster_rcnn_output_dict,\n",
        "    context_padding_size, resize_image=True):\n",
        "  \"\"\"Runs inference over a single input image and visualizes Faster R-CNN vs. \n",
        "  Context R-CNN results.\n",
        "\n",
        "  Args:\n",
        "    model: A tensorflow saved_model object.\n",
        "    image_path: Absolute path to the input image.\n",
        "    context_features: A numpy float32 contextual memory bank of shape \n",
        "      [num_context_examples, 2057]\n",
        "    faster_rcnn_output_dict: The output_dict corresponding to this input image\n",
        "      from the single-frame Faster R-CNN model, which was previously used to\n",
        "      build the memory bank.\n",
        "    context_padding_size: The amount of expected padding in the contextual\n",
        "      memory bank, defined in the Context R-CNN config as \n",
        "      max_num_context_features.\n",
        "    resize_image: Whether to resize the input image before running inference.\n",
        "\n",
        "  Returns:\n",
        "    context_rcnn_image_np: Numpy image array showing Context R-CNN Results.\n",
        "    faster_rcnn_image_np: Numpy image array showing Faster R-CNN Results.\n",
        "  \"\"\"\n",
        "\n",
        "  # the array based representation of the image will be used later in order to prepare the\n",
        "  # result image with boxes and labels on it.\n",
        "  with open(image_path,'rb') as f:\n",
        "    image = Image.open(f)\n",
        "    if resize_image:\n",
        "      image.thumbnail((640,640),Image.ANTIALIAS)\n",
        "    image_np = np.array(image)\n",
        "    image.thumbnail((400,400),Image.ANTIALIAS)\n",
        "    context_rcnn_image_np = np.array(image)\n",
        "    \n",
        "  faster_rcnn_image_np = np.copy(context_rcnn_image_np)\n",
        "\n",
        "  # Actual detection.\n",
        "  output_dict = run_context_rcnn_inference_for_single_image(\n",
        "      model, image_np, context_features, context_padding_size)\n",
        "\n",
        "  # Visualization of the results of a context_rcnn detection.\n",
        "  vis_utils.visualize_boxes_and_labels_on_image_array(\n",
        "      context_rcnn_image_np,\n",
        "      output_dict['detection_boxes'],\n",
        "      output_dict['detection_classes'],\n",
        "      output_dict['detection_scores'],\n",
        "      category_index,\n",
        "      use_normalized_coordinates=True,\n",
        "      line_thickness=2)\n",
        "  \n",
        "  # Visualization of the results of a faster_rcnn detection.\n",
        "  vis_utils.visualize_boxes_and_labels_on_image_array(\n",
        "      faster_rcnn_image_np,\n",
        "      faster_rcnn_output_dict['detection_boxes'],\n",
        "      faster_rcnn_output_dict['detection_classes'],\n",
        "      faster_rcnn_output_dict['detection_scores'],\n",
        "      category_index,\n",
        "      use_normalized_coordinates=True,\n",
        "      line_thickness=2)\n",
        "  return context_rcnn_image_np, faster_rcnn_image_np"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3cYa2B8uAYx0",
        "colab_type": "text"
      },
      "source": [
        "Define Matplotlib parameters for pretty visualizations"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9F8okR1uAQ0T",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "%matplotlib inline\n",
        "plt.rcParams['axes.grid'] = False\n",
        "plt.rcParams['xtick.labelsize'] = False\n",
        "plt.rcParams['ytick.labelsize'] = False\n",
        "plt.rcParams['xtick.top'] = False\n",
        "plt.rcParams['xtick.bottom'] = False\n",
        "plt.rcParams['ytick.left'] = False\n",
        "plt.rcParams['ytick.right'] = False\n",
        "plt.rcParams['figure.figsize'] = [15,10]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YGj7nXXQAaQ7",
        "colab_type": "text"
      },
      "source": [
        "Run Context R-CNN inference and compare results to Faster R-CNN"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "vQ2Sj2VIOZLA",
        "outputId": "1c043894-09e5-4c9f-a99d-ae21d6e72d0c",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        }
      },
      "source": [
        "for image_path in TEST_IMAGE_PATHS:\n",
        "  image_id = image_path_to_id[str(image_path)]\n",
        "  faster_rcnn_output_dict = faster_rcnn_results[image_id]\n",
        "  context_rcnn_image, faster_rcnn_image = show_context_rcnn_inference(\n",
        "      context_rcnn_model, image_path, context_features_matrix,\n",
        "      faster_rcnn_output_dict, context_padding_size)\n",
        "  plt.subplot(1,2,1)\n",
        "  plt.imshow(faster_rcnn_image)\n",
        "  plt.title('Faster R-CNN')\n",
        "  plt.subplot(1,2,2)\n",
        "  plt.imshow(context_rcnn_image)\n",
        "  plt.title('Context R-CNN')\n",
        "  plt.show()"
      ],
      "execution_count": 32,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/png": "[encoded data, 153132 characters]\n",
            "text/plain": [
              "<Figure size 1080x720 with 2 Axes>"
            ]
          },
          "metadata": {
            "tags": [],
            "needs_background": "light"
          }
        },
        {
          "output_type": "display_data",
          "data": {
            "image/png": "[encoded data, 149056 characters]\n",
            "text/plain": [
              "<Figure size 1080x720 with 2 Axes>"
            ]
          },
          "metadata": {
            "tags": [],
            "needs_background": "light"
          }
        },
        {
          "output_type": "display_data",
          "data": {
            "image/png": "[encoded data, 151020 characters]\n",
            "text/plain": [
              "<Figure size 1080x720 with 2 Axes>"
            ]
          },
          "metadata": {
            "tags": [],
            "needs_background": "light"
          }
        },
        {
          "output_type": "display_data",
          "data": {
            "image/png": "[encoded data, 154124 characters]\n",
            "text/plain": [
              "<Figure size 1080x720 with 2 Axes>"
            ]
          },
          "metadata": {
            "tags": [],
            "needs_background": "light"
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lMombPr0GF9a",
        "colab_type": "text"
      },
      "source": [
        "The images used in this demo are from the [Snapshot Serengeti dataset](http://lila.science/datasets/snapshot-serengeti), and released under the [Community Data License Agreement (permissive variant)](https://cdla.io/permissive-1-0/)."
      ]
    }
  ]
}