{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Registration using optical flow\n\nDemonstration of image registration using optical flow.\n\nBy definition, the optical flow is the vector field *(u, v)* verifying\n*image1(x+u, y+v) = image0(x, y)*, where (image0, image1) is a couple of\nconsecutive 2D frames from a sequence. This vector field can then be\nused for registration by image warping.\n\nTo display registration results, an RGB image is constructed by\nassigning the result of the registration to the red channel and the\ntarget image to the green and blue channels. A perfect registration\nresults in a gray level image while misregistred pixels appear colored\nin the constructed RGB image.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom skimage.color import rgb2gray\nfrom skimage.data import stereo_motorcycle, vortex\nfrom skimage.transform import warp\nfrom skimage.registration import optical_flow_tvl1, optical_flow_ilk\n\n# --- Load the sequence\nimage0, image1, disp = stereo_motorcycle()\n\n# --- Convert the images to gray level: color is not supported.\nimage0 = rgb2gray(image0)\nimage1 = rgb2gray(image1)\n\n# --- Compute the optical flow\nv, u = optical_flow_tvl1(image0, image1)\n\n# --- Use the estimated optical flow for registration\n\nnr, nc = image0.shape\n\nrow_coords, col_coords = np.meshgrid(np.arange(nr), np.arange(nc), indexing='ij')\n\nimage1_warp = warp(image1, np.array([row_coords + v, col_coords + u]), mode='edge')\n\n# build an RGB image with the unregistered sequence\nseq_im = np.zeros((nr, nc, 3))\nseq_im[..., 0] = image1\nseq_im[..., 1] = image0\nseq_im[..., 2] = image0\n\n# build an RGB image with the registered sequence\nreg_im = np.zeros((nr, nc, 3))\nreg_im[..., 0] = image1_warp\nreg_im[..., 1] = image0\nreg_im[..., 2] = image0\n\n# build an RGB image with the registered sequence\ntarget_im = np.zeros((nr, nc, 3))\ntarget_im[..., 0] = image0\ntarget_im[..., 1] = image0\ntarget_im[..., 2] = image0\n\n# --- Show the result\n\nfig, (ax0, ax1, ax2) = plt.subplots(3, 1, figsize=(5, 10))\n\nax0.imshow(seq_im)\nax0.set_title(\"Unregistered sequence\")\nax0.set_axis_off()\n\nax1.imshow(reg_im)\nax1.set_title(\"Registered sequence\")\nax1.set_axis_off()\n\nax2.imshow(target_im)\nax2.set_title(\"Target\")\nax2.set_axis_off()\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The estimated vector field *(u, v)* can also be displayed with a\nquiver plot.\n\nIn the following example, Iterative Lukas-Kanade algorithm (iLK) is\napplied to images of particles in the context of particle image\nvelocimetry (PIV). The sequence is the Case B from the\n[PIV challenge 2001](http://www.pivchallenge.org/)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image0, image1 = vortex()\n\n# --- Compute the optical flow\nv, u = optical_flow_ilk(image0, image1, radius=15)\n\n# --- Compute flow magnitude\nnorm = np.sqrt(u**2 + v**2)\n\n# --- Display\nfig, (ax0, ax1) = plt.subplots(1, 2, figsize=(8, 4))\n\n# --- Sequence image sample\n\nax0.imshow(image0, cmap='gray')\nax0.set_title(\"Sequence image sample\")\nax0.set_axis_off()\n\n# --- Quiver plot arguments\n\nnvec = 20  # Number of vectors to be displayed along each image dimension\nnl, nc = image0.shape\nstep = max(nl // nvec, nc // nvec)\n\ny, x = np.mgrid[:nl:step, :nc:step]\nu_ = u[::step, ::step]\nv_ = v[::step, ::step]\n\nax1.imshow(norm)\nax1.quiver(x, y, u_, v_, color='r', units='dots', angles='xy', scale_units='xy', lw=3)\nax1.set_title(\"Optical flow magnitude and vector field\")\nax1.set_axis_off()\nfig.tight_layout()\n\nplt.show()"
      ]
    }
  ],
  "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.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}