{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Optical Flow: Predicting movement with the RAFT model\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_optical_flow.ipynb)\n    or `go to the end <sphx_glr_download_auto_examples_others_plot_optical_flow.py>` to download the full example code.</p></div>\n\nOptical flow is the task of predicting movement between two images, usually two\nconsecutive frames of a video. Optical flow models take two images as input, and\npredict a flow: the flow indicates the displacement of every single pixel in the\nfirst image, and maps it to its corresponding pixel in the second image. Flows\nare (2, H, W)-dimensional tensors, where the first axis corresponds to the\npredicted horizontal and vertical displacements.\n\nThe following example illustrates how torchvision can be used to predict flows\nusing our implementation of the RAFT model. We will also see how to convert the\npredicted flows to RGB images for visualization.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nimport torchvision.transforms.functional as F\n\n\nplt.rcParams[\"savefig.bbox\"] = \"tight\"\n\n\ndef plot(imgs, **imshow_kwargs):\n    if not isinstance(imgs[0], list):\n        # Make a 2d grid even if there's just 1 row\n        imgs = [imgs]\n\n    num_rows = len(imgs)\n    num_cols = len(imgs[0])\n    _, axs = plt.subplots(nrows=num_rows, ncols=num_cols, squeeze=False)\n    for row_idx, row in enumerate(imgs):\n        for col_idx, img in enumerate(row):\n            ax = axs[row_idx, col_idx]\n            img = F.to_pil_image(img.to(\"cpu\"))\n            ax.imshow(np.asarray(img), **imshow_kwargs)\n            ax.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])\n\n    plt.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reading Videos Using TorchCodec\nWe will first read a video using\n[TorchCodec](https://github.com/pytorch/torchcodec).\nThe video we will use here is free of use from [pexels.com](https://www.pexels.com/video/a-man-playing-a-game-of-basketball-5192157/),\ncredits go to [Pavel Danilyuk](https://www.pexels.com/@pavel-danilyuk).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import tempfile\nfrom pathlib import Path\nfrom urllib.request import urlretrieve\n\n\nvideo_url = \"https://download.pytorch.org/tutorial/pexelscom_pavel_danilyuk_basketball_hd.mp4\"\nvideo_path = Path(tempfile.mkdtemp()) / \"basketball.mp4\"\n_ = urlretrieve(video_url, video_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We use :class:`~torchcodec.decoders.VideoDecoder` to decode the video frames.\nTorchCodec returns frames in NCHW format by default.\n\nHere we will just make 2 predictions between 2 pre-selected pairs of frames,\nnamely frames (100, 101) and (150, 151). Each of these pairs corresponds to a\nsingle model input.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchcodec.decoders import VideoDecoder\ndecoder = VideoDecoder(str(video_path))\nframes = decoder[:]\n\nimg1_batch = torch.stack([frames[100], frames[150]])\nimg2_batch = torch.stack([frames[101], frames[151]])\n\nplot(img1_batch)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The RAFT model accepts RGB images. We first get the frames from\nthe decoder and resize them to ensure their dimensions\nare divisible by 8. Note that we explicitly use ``antialias=False``, because\nthis is how those models were trained. Then we use the transforms bundled into\nthe weights in order to preprocess the input and rescale its values to the\nrequired ``[-1, 1]`` interval.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.optical_flow import Raft_Large_Weights\n\nweights = Raft_Large_Weights.DEFAULT\ntransforms = weights.transforms()\n\n\ndef preprocess(img1_batch, img2_batch):\n    img1_batch = F.resize(img1_batch, size=[520, 960], antialias=False)\n    img2_batch = F.resize(img2_batch, size=[520, 960], antialias=False)\n    return transforms(img1_batch, img2_batch)\n\n\nimg1_batch, img2_batch = preprocess(img1_batch, img2_batch)\n\nprint(f\"shape = {img1_batch.shape}, dtype = {img1_batch.dtype}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Estimating Optical flow using RAFT\nWe will use our RAFT implementation from\n:func:`~torchvision.models.optical_flow.raft_large`, which follows the same\narchitecture as the one described in the [original paper](https://arxiv.org/abs/2003.12039).\nWe also provide the :func:`~torchvision.models.optical_flow.raft_small` model\nbuilder, which is smaller and faster to run, sacrificing a bit of accuracy.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.models.optical_flow import raft_large\n\n# If you can, run this example on a GPU, it will be a lot faster.\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nmodel = raft_large(weights=Raft_Large_Weights.DEFAULT, progress=False).to(device)\nmodel = model.eval()\n\nlist_of_flows = model(img1_batch.to(device), img2_batch.to(device))\nprint(f\"type = {type(list_of_flows)}\")\nprint(f\"length = {len(list_of_flows)} = number of iterations of the model\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The RAFT model outputs lists of predicted flows where each entry is a\n(N, 2, H, W) batch of predicted flows that corresponds to a given \"iteration\"\nin the model. For more details on the iterative nature of the model, please\nrefer to the [original paper](https://arxiv.org/abs/2003.12039). Here, we\nare only interested in the final predicted flows (they are the most accurate\nones), so we will just retrieve the last item in the list.\n\nAs described above, a flow is a tensor with dimensions (2, H, W) (or (N, 2, H,\nW) for batches of flows) where each entry corresponds to the horizontal and\nvertical displacement of each pixel from the first image to the second image.\nNote that the predicted flows are in \"pixel\" unit, they are not normalized\nw.r.t. the dimensions of the images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "predicted_flows = list_of_flows[-1]\nprint(f\"dtype = {predicted_flows.dtype}\")\nprint(f\"shape = {predicted_flows.shape} = (N, 2, H, W)\")\nprint(f\"min = {predicted_flows.min()}, max = {predicted_flows.max()}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Visualizing predicted flows\nTorchvision provides the :func:`~torchvision.utils.flow_to_image` utility to\nconvert a flow into an RGB image. It also supports batches of flows.\neach \"direction\" in the flow will be mapped to a given RGB color. In the\nimages below, pixels with similar colors are assumed by the model to be moving\nin similar directions. The model is properly able to predict the movement of\nthe ball and the player. Note in particular the different predicted direction\nof the ball in the first image (going to the left) and in the second image\n(going up).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchvision.utils import flow_to_image\n\nflow_imgs = flow_to_image(predicted_flows)\n\n# The images have been mapped into [-1, 1] but for plotting we want them in [0, 1]\nimg1_batch = [(img1 + 1) / 2 for img1 in img1_batch]\n\ngrid = [[img1, flow_img] for (img1, flow_img) in zip(img1_batch, flow_imgs)]\nplot(grid)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Bonus: Creating GIFs of predicted flows\nIn the example above we have only shown the predicted flows of 2 pairs of\nframes. A fun way to apply the Optical Flow models is to run the model on an\nentire video, and create a new video from all the predicted flows. Below is a\nsnippet that can get you started with this. We comment out the code, because\nthis example is being rendered on a machine without a GPU, and it would take\ntoo long to run it.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# from torchvision.io import write_jpeg\n# for i, (img1, img2) in enumerate(zip(frames, frames[1:])):\n#     # Note: it would be faster to predict batches of flows instead of individual flows\n#     img1, img2 = preprocess(img1, img2)\n\n#     list_of_flows = model(img1.to(device), img2.to(device))\n#     predicted_flow = list_of_flows[-1][0]\n#     flow_img = flow_to_image(predicted_flow).to(\"cpu\")\n#     output_folder = \"/tmp/\"  # Update this to the folder of your choice\n#     write_jpeg(flow_img, output_folder + f\"predicted_flow_{i}.jpg\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Once the .jpg flow images are saved, you can convert them into a video or a\nGIF using ffmpeg with e.g.:\n\nffmpeg -f image2 -framerate 30 -i predicted_flow_%d.jpg -loop -1 flow.gif\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
}