备注
单击 here 下载完整的示例代码或通过活页夹在浏览器中运行此示例
模板匹配¶
我们使用模板匹配来识别图像块(在本例中,是以一枚硬币为中心的子图像)的出现。在这里,我们返回单个匹配(完全相同的硬币),因此 match_template
结果与硬币的位置相对应。其他硬币看起来相似,因此具有局部最大值;如果您希望有多个匹配,则应该使用适当的峰值查找函数。
这个 match_template
函数使用快速、归一化的互相关 1 若要在图像中查找模板实例,请执行以下操作。请注意,输出中的峰值 match_template
对应于模板的原点(即左上角)。
- 1
J·P·刘易斯,《快速归一化互相关》,工业光魔。

import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import match_template
image = data.coins()
coin = image[170:220, 75:130]
result = match_template(image, coin)
ij = np.unravel_index(np.argmax(result), result.shape)
x, y = ij[::-1]
fig = plt.figure(figsize=(8, 3))
ax1 = plt.subplot(1, 3, 1)
ax2 = plt.subplot(1, 3, 2)
ax3 = plt.subplot(1, 3, 3, sharex=ax2, sharey=ax2)
ax1.imshow(coin, cmap=plt.cm.gray)
ax1.set_axis_off()
ax1.set_title('template')
ax2.imshow(image, cmap=plt.cm.gray)
ax2.set_axis_off()
ax2.set_title('image')
# highlight matched region
hcoin, wcoin = coin.shape
rect = plt.Rectangle((x, y), wcoin, hcoin, edgecolor='r', facecolor='none')
ax2.add_patch(rect)
ax3.imshow(result)
ax3.set_axis_off()
ax3.set_title('`match_template`\nresult')
# highlight matched region
ax3.autoscale(False)
ax3.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10)
plt.show()
脚本的总运行时间: (0分0.102秒)