1""" 2================= 3Template Matching 4================= 5 6We use template matching to identify the occurrence of an image patch 7(in this case, a sub-image centered on a single coin). Here, we 8return a single match (the exact same coin), so the maximum value in the 9``match_template`` result corresponds to the coin location. The other coins 10look similar, and thus have local maxima; if you expect multiple matches, you 11should use a proper peak-finding function. 12 13The ``match_template`` function uses fast, normalized cross-correlation [1]_ 14to find instances of the template in the image. Note that the peaks in the 15output of ``match_template`` correspond to the origin (i.e. top-left corner) of 16the template. 17 18.. [1] J. P. Lewis, "Fast Normalized Cross-Correlation", Industrial Light and 19 Magic. 20 21""" 22import numpy as np 23import matplotlib.pyplot as plt 24 25from skimage import data 26from skimage.feature import match_template 27 28 29image = data.coins() 30coin = image[170:220, 75:130] 31 32result = match_template(image, coin) 33ij = np.unravel_index(np.argmax(result), result.shape) 34x, y = ij[::-1] 35 36fig = plt.figure(figsize=(8, 3)) 37ax1 = plt.subplot(1, 3, 1) 38ax2 = plt.subplot(1, 3, 2) 39ax3 = plt.subplot(1, 3, 3, sharex=ax2, sharey=ax2) 40 41ax1.imshow(coin, cmap=plt.cm.gray) 42ax1.set_axis_off() 43ax1.set_title('template') 44 45ax2.imshow(image, cmap=plt.cm.gray) 46ax2.set_axis_off() 47ax2.set_title('image') 48# highlight matched region 49hcoin, wcoin = coin.shape 50rect = plt.Rectangle((x, y), wcoin, hcoin, edgecolor='r', facecolor='none') 51ax2.add_patch(rect) 52 53ax3.imshow(result) 54ax3.set_axis_off() 55ax3.set_title('`match_template`\nresult') 56# highlight matched region 57ax3.autoscale(False) 58ax3.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10) 59 60plt.show() 61