我研究了模板匹配,我理解了这个概念并且已经为我的案例实现了它,并且它有效。这是 documentation 中给出的代码:
import cv2 as cv
import numpy as np
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]
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = 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)
基本上,这里发生的事情是获取源图像和模板,读取模板并在源图像上查找匹配项。如果找到匹配项,它会在源图像上绘制一个矩形。
这适用于一张图片,但就我而言,我将在源代码中查找多个模板,据我所知,我需要为每个模板复制上面的所有代码'我在找,这似乎不对。
所以我正在寻找的是一种将所有这些放入一个函数中的方法,以便它使用一个命令将所有内容写入我的源代码。如果我在这里没有看到明显的东西,我很抱歉,但我想不出一种方法来正确地做到这一点。你会怎么做?
最佳答案
首先,我将列出我所有的图像文件。然后,我将遍历列表的所有元素。现在你的代码将是 -
import cv2 as cv
import numpy as np
img_rgb = cv.imread('mario.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
list = ['file1.png','file2.png','file3.png']
for image in list:
template = cv.imread(image,0)
w, h = template.shape[::-1]
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = 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)
但是,如果您想对每个图像使用不同的阈值和比较方法来进行模板匹配,那么您可以将所有内容放入一个新函数的循环中,并通过传递您的阈值和方法来调用该函数。
关于Python OpenCV - 一个模板匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590190/