{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Template Matching\n\nWe use template matching to identify the occurrence of an image patch\n(in this case, a sub-image centered on a single coin). Here, we\nreturn a single match (the exact same coin), so the maximum value in the\n``match_template`` result corresponds to the coin location. The other coins\nlook similar, and thus have local maxima; if you expect multiple matches, you\nshould use a proper peak-finding function.\n\nThe ``match_template`` function uses fast, normalized cross-correlation [1]_\nto find instances of the template in the image. Note that the peaks in the\noutput of ``match_template`` correspond to the origin (i.e. top-left corner) of\nthe template.\n\n.. [1] J. P. Lewis, \"Fast Normalized Cross-Correlation\", Industrial Light and\n       Magic.\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\nfrom skimage.feature import match_template\n\n\nimage = data.coins()\ncoin = image[170:220, 75:130]\n\nresult = match_template(image, coin)\nij = np.unravel_index(np.argmax(result), result.shape)\nx, y = ij[::-1]\n\nfig = plt.figure(figsize=(8, 3))\nax1 = plt.subplot(1, 3, 1)\nax2 = plt.subplot(1, 3, 2)\nax3 = plt.subplot(1, 3, 3, sharex=ax2, sharey=ax2)\n\nax1.imshow(coin, cmap=plt.cm.gray)\nax1.set_axis_off()\nax1.set_title('template')\n\nax2.imshow(image, cmap=plt.cm.gray)\nax2.set_axis_off()\nax2.set_title('image')\n# highlight matched region\nhcoin, wcoin = coin.shape\nrect = plt.Rectangle((x, y), wcoin, hcoin, edgecolor='r', facecolor='none')\nax2.add_patch(rect)\n\nax3.imshow(result)\nax3.set_axis_off()\nax3.set_title('`match_template`\\nresult')\n# highlight matched region\nax3.autoscale(False)\nax3.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10)\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
}