python opencv -模板匹配
模板匹配就是,我们现有一个模板和一个图片,然后,在这个图片中寻找和模板近似的部分。
在opencv 中主要通过cv2.matchTemplate这个函数去实现。
下面我们先看一下,模板图片和需要匹配的图片:
模板:
需要匹配的图片:
下面来看代码:
python
import cv2
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os
path=r'D:\learn\photo\cv\lena.jpg'
path2=r'D:\learn\photo\cv\face.jpg'
img=cv2.imread(path,1)
img_gray=cv2.imread(path,0)
img_template=cv2.imread(path2,1)
img_gray_template=cv2.imread(path2,0)
def cv_show(name,img):
cv2.imshow(name,img)
#cv2.waitKey(0),接收0,表示窗口暂停
cv2.waitKey(0)
#销毁所有窗口
cv2.destroyAllWindows()
print(img.shape)
print(img_template.shape)
h, w = img_template.shape[:2]
"""
- TM_SQDIFF:计算平方不同,计算出来的值越小,越相关
- TM_SQDIFF_NORMED:计算归一化平方不同,计算出来的值越接近0,越相关
- TM_CCORR:计算相关性,计算出来的值越大,越相关
- TM_CCOEFF:计算相关系数,计算出来的值越大,越相关
- TM_CCORR_NORMED:计算归一化相关性,计算出来的值越接近1,越相关
- TM_CCOEFF_NORMED:计算归一化相关系数,计算出来的值越接近1,越相关
链接:https://docs.opencv.org/3.3.1/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d
"""
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
res = cv2.matchTemplate(img, img_template, cv2.TM_SQDIFF)
print(res.shape)
# exit()
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
print(min_val, max_val, min_loc, max_loc)
for meth in methods:
img2 = img.copy()
# 匹配方法的真值
method = eval(meth)
print(method)
res = cv2.matchTemplate(img, 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)
plt.subplot(121), plt.imshow(res,'gray')
plt.xticks([]), plt.yticks([]) # 隐藏坐标轴
plt.subplot(122), plt.imshow(img2[:,:,::-1])
plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
运行结果如下: