模板匹配

模板匹配

目标

  • 使用模板在一副图像中查找目标
  • 函数:cv2.matchTemplate(),cv2.minMaxLoc()

1.原理

模板匹配是用来在一幅大图像中搜寻查找模板图像位置的方法。OpenCV提供了函数cv2.matchTemplate()。和2D卷积一样,他也是用模板图像在输入图像上滑动,并在每一个位置对模板图像和与其对应的输入图像的子区域进行比较。OpenCV提供了几种不同的比较方法。返回的结果是一个灰度图像,每一个像素值表示了此区域与模板的匹配程度。
如果输入图像的大小是W * H,模板的大小是w * h,输出的结果大小是W - w + 1,H - h + 1。当你得到这幅图像之后,就可以使用函数cv2.minMaxLoc()来其中的最大值和最小值的位置了。第一个值为矩形左上角的点(位置),(w,h)为模板矩形的宽和高。这个矩形就是找到的模板区域了。

注意:如果你使用的比较方法是cv2.TM_SQDIFF,最小值对应的位置才是匹配的区域。

2.OpenCV中的模板匹配

我们会搜索Arya的脸,并且尝试不同的比较方法,比较他们的效果:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('D://DL/img/Arya.jpeg',0)
img2 = img.copy()
template = cv2.imread('D://DL/img/Arya_face.jpeg',0)
w,h = template.shape[::-1]

#All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF','cv2.TM_CCOEFF_NORMED','cv2.TM_CCORR','cv2.TM_CCORR_NORMED','cv2.TM_SQDIFF','cv2.TM_SQDIFF_NORMED']

for meth in methods:
    img = img2.copy()
    
    #exec 语句用来执行存储在字符串或文件中的python语句
    #例如,我们可以在运行时生成一个包含python代码的字符串,然后使用exec语句执行这些语句
    #eval 语句用来计算存储在字符串中的有效python表达式
    method = eval(meth)
    
    #apply template matching
    res = cv2.matchTemplate(img,template,method)
    min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(res)
    
    #使用不同的比较方法,对结果的解释不同
    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(img,top_left,bottom_right,255,2)
    
    plt.subplot(121),plt.imshow(res,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.suptitle(meth)
    plt.show()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.多对象的模板匹配

在前面的部分,我们在图片中搜索Arya的脸,而且Arya的脸只出现过一次。加入你的目标对象在图像中出现很多次怎么办?函数cv2.minMaxLoc()只会给输出最大值和最小值。此时,我们就要使用阈值了。

import cv2
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv2.imread('D://DL/img/mario.jpg')
img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)
template = cv2.imread('D://DL/img/mario_coin.jpg',0)
w,h = template.shape[::-1]

res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8

#numpy.where(condition[,x,y])
#return elements,either from x or y,depending on condition
#if only condition is given,return condition.nonzere()
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w,pt[1] + h),(0,0,255),2)
    
cv2.imshow('img_rgb',img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值