模糊匹配 是一种用于较大图像中搜索和查找模板图像位置的方法
import cv2 as cvimport numpy as npfrom matplotlib import pyplot as plot# 单匹配方式def mathTemplate():# 读取图片img = cv.imread("images/tg.jpg", 0)# 复制图片img2 = img.copy()template = cv.imread("images/mb.png", 0)width, height = template.shape[:2]# 列表中所有的6种比较方法methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR','cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']for meth in methods:img = img2.copy()method = eval(meth)# 应用模板匹配res = cv.matchTemplate(img, template, method)# minMaxLoc寻找矩阵中最大和最小的位置min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:top_left = max_locelse:top_left = max_locbottom_right = (top_left[0] + width, top_left[1] + height)# 在图片上面绘制矩形边框cv.rectangle(img, top_left, bottom_right, 255, 3)plot.xticks([]), plot.yticks([])plot.subplot(122), plot.imshow(img, cmap='gray')plot.xticks([]), plot.yticks([])plot.suptitle(meth)plot.show()# 多匹配方式def matchMore():# 读取图片img_rgb = cv.imread('mario.png')# 转换颜色为灰色img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)template = cv.imread('mario_coin.png', 0)# 获取款跟高w, h = template.shape[::-1]# 匹配模板 采用TM_CCOEFF_NORMEDres = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)threshold = 0.8loc = np.where(res >= threshold)for pt in zip(*loc[::-1]):# 绘画方框cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)cv.imwrite('res.png', img_rgb)if __name__ == '__main__':mathTemplate()
