OpenCV入门(二十五)快速学会OpenCV 24 模板匹配
作者:Xiou
1.模板匹配概述
模板匹配是指在当前图像A内寻找与图像B最相似的部分,一般将图像A称为输入图像,将图像B称为模板图像。模板匹配的操作方法是将模板图像B在图像A上滑动,遍历所有像素以完成匹配。
语法格式:
cv2.matchTemplate(image, templ, method, result=None, mask=None)
参数:
image: 输入图像;
templ: 输入模板;
method: 方法;
TM_SQDIFF: 计算平方差, 计算出来的值越小, 越相关;
TM_CCORR: 计算相关性, 计算出来的值越大, 越相关;
TM_CCOEFF: 计算相关系数, 计算出来的值越大, 越相关;
TM_SQDIFF_NORMED: 计算归一化平方不同, 计算出来的值越接近 0, 越相关;
TM_CCORR_NORMED: 计算归一化相关性, 计算出来的值越接近 1, 越相关;
TM_CCOEFF_NORMED: 计算归一化系数, 计算出来的值越接近 1, 越相关。
2.代码实例
2.1代码实例1
使用函数cv2.matchTemplate()进行模板匹配。要求参数method的值设置为cv2.TM_SQDIFF,显示函数的返回结果及匹配结果。
测试原图:
代码实例:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('lena512g.bmp',0)
template = cv2.imread('temp.bmp',0)
th, tw = template.shape[::]
rv = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(rv)
topLeft = minLoc
bottomRight = (topLeft[0] + tw, topLeft[1] + th)
cv2.rectangle(img, topLeft, bottomRight, 255, 2)
plt.subplot(121), plt.imshow(rv, cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img, cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.show()
输出结果:
2.2代码实例2
import cv2
# 读取图片
img = cv2.imread("girl1.jpg", 0)
print(img.shape)
# 读取模板
template = cv2.imread("test.jpg", 0)
h, w = template.shape
print(template.shape)
# 模板匹配
result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
输出结果:
import cv2
from matplotlib import pyplot as plt
# 读取图片
img = cv2.imread("girl1.jpg", 0)
# 读取模板
template = cv2.imread("test.jpg", 0)
h, w = template.shape
# 模式
methods = ['cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED']
# 循环
for meth in methods:
img2 = img.copy()
# 匹配方法的真值
method = eval(meth)
print("method:", method)
res = cv2.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 如果是平方差匹配TM_SQDIFF或归一化平方差匹配TM_SQDIFF_NORMED,取最小值
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
# 画矩形
cv2.rectangle(img2, top_left, bottom_right, 255, 2)
# 展示
f, ax = plt.subplots(1, 2, figsize=(16, 8))
ax[0].imshow(img2, cmap='gray')
ax[1].imshow(res, cmap='gray')
plt.suptitle(meth)
plt.show()
输出结果: