{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Masked Normalized Cross-Correlation\n\nIn this example, we use the masked normalized cross-correlation to\nidentify the relative shift between two similar images containing\ninvalid data.\n\nIn this case, the images cannot simply be masked before computing the\ncross-correlation, as the masks will influence the computation. The\ninfluence of the masks must be removed from the cross-correlation, as\nis described in [1]_.\n\nIn this example, we register the translation between two\nimages. However, one of the images has about 25% of the pixels which\nare corrupted.\n\n.. [1] D. Padfield, \"Masked object registration in the Fourier domain\"\n       IEEE Transactions on Image Processing (2012).\n       :DOI:`10.1109/TIP.2011.2181402`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage import data, draw\nfrom skimage.registration import phase_cross_correlation\nfrom scipy import ndimage as ndi"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Define areas of the image which are invalid.\nProbability of an invalid pixel is 25%.\nThis could be due to a faulty detector, or edges that\nare not affected by translation (e.g. moving object in a window).\nSee reference paper for more examples\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = data.camera()\nshift = (-22, 13)\n\nrng = np.random.default_rng()\ncorrupted_pixels = rng.choice([False, True], size=image.shape, p=[0.25, 0.75])\n\n# The shift corresponds to the pixel offset relative to the reference image\noffset_image = ndi.shift(image, shift)\noffset_image *= corrupted_pixels\nprint(f'Known offset (row, col): {shift}')\n\n# Determine what the mask is based on which pixels are invalid\n# In this case, we know what the mask should be since we corrupted\n# the pixels ourselves\nmask = corrupted_pixels\n\ndetected_shift, _, _ = phase_cross_correlation(image, offset_image, reference_mask=mask)\n\nprint(f'Detected pixel offset (row, col): {-detected_shift}')\n\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(8, 3))\n\nax1.imshow(image, cmap='gray')\nax1.set_axis_off()\nax1.set_title('Reference image')\n\nax2.imshow(offset_image.real, cmap='gray')\nax2.set_axis_off()\nax2.set_title('Corrupted, offset image')\n\nax3.imshow(mask, cmap='gray')\nax3.set_axis_off()\nax3.set_title('Masked pixels')\n\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Solid masks are another illustrating example. In this case, we have\na limited view of an image and an offset image. The masks for these\nimages need not be the same. The `phase_cross_correlation`\nfunction will correctly identify which part of the images should be\ncompared.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = data.camera()\nshift = (-22, 13)\n\nrr1, cc1 = draw.ellipse(259, 248, r_radius=125, c_radius=100, shape=image.shape)\n\nrr2, cc2 = draw.ellipse(300, 200, r_radius=110, c_radius=180, shape=image.shape)\n\nmask1 = np.zeros_like(image, dtype=bool)\nmask2 = np.zeros_like(image, dtype=bool)\nmask1[rr1, cc1] = True\nmask2[rr2, cc2] = True\n\noffset_image = ndi.shift(image, shift)\nimage *= mask1\noffset_image *= mask2\n\nprint(f'Known offset (row, col): {shift}')\n\ndetected_shift, _, _ = phase_cross_correlation(\n    image, offset_image, reference_mask=mask1, moving_mask=mask2\n)\n\nprint(f'Detected pixel offset (row, col): {-detected_shift}')\n\nfig = plt.figure(figsize=(8, 3))\nax1 = plt.subplot(1, 2, 1)\nax2 = plt.subplot(1, 2, 2, sharex=ax1, sharey=ax1)\n\nax1.imshow(image, cmap='gray')\nax1.set_axis_off()\nax1.set_title('Reference image')\n\nax2.imshow(offset_image.real, cmap='gray')\nax2.set_axis_off()\nax2.set_title('Masked, offset image')\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
}