我要检查opencv中的模板是否匹配

问题描述

我要检查模板匹配是对还是错。

就是这样:

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

img = cv.imread('messi5.jpg',0)
img2 = img.copy() 
template = cv.imread('template.jpg',0)
w,h = template.shape[::-1]
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)
    min_val,max_val,min_loc,max_loc = cv.minMaxLoc(res)

    if template_match:
        //do something

我已经读过这篇文章,但我没明白https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html

感谢答案。

解决方法

  1. 获取模板的功能。

  • 图像特征(例如边缘和兴趣点)可提供有关图像内容的丰富信息。 source


  • 例如:如果下面是您的模板,请找到其特征。

    enter image description here enter image description here

     import numpy as np
     import imutils
     import glob
     import cv2
    
     template = cv2.imread("template.jpg")
     template = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
     template = cv2.Canny(template,50,200)
     (h,w) = template.shape[:2]
    
  1. 获取图像的特征。

  • enter image description here enter image description here
  1. 检查模板特征是否与图像特征匹配。

result = cv2.matchTemplate(edged,template,cv2.TM_CCOEFF)
  • cv2.TM_CCOEFF只是一个选择,您可以使用其他许多templates
  1. 找到result变量的最小值和最大值

(_,maxVal,_,maxLoc) = cv2.minMaxLoc(result)
  1. 现在,您可以检查模板匹配是对还是错。

found = (maxVal,maxLoc,r)

因此,如果检测到模板,则found变量将返回一个长度为3的元组,这意味着可以匹配模板。例如:

(495.000,(148,26),1)
  • 495.000是数组中的最大值。

  • (148,26)从找到的对象的(x,y)坐标开始。

  • 1.0是半径。