如果我必须针对单个图像源测试多个模板,我会为模板文件夹创建一个目录(而不是像VIVEK建议的那样列出列表)
在这个模板文件夹中,我将保留我的所有模板。在
另外,我将为源映像创建一个文件夹,在其中保存所有源映像。在
最后,我将创建一个results文件夹,在那里我将存储测试后的所有源图像(带有红色矩形的图像)import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
import os, errno
threshold = 0.8 #set threshold
resultsDirectory = 'results'
sourceDirectory = os.fsencode('sourceImages')
templateDirectory = os.fsencode('templates')
detectedCount = 0
for file in os.listdir(sourceDirectory):
filename = os.fsdecode(file)
if filename.endswith(".jpg") or filename.endswith(".png"):
print (filename)
img_rgb = cv2.imread('sourceImages/'+filename)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
for templateFile in os.listdir(templateDirectory):
templateFilename = os.fsdecode(templateFile)
if filename.endswith(".jpg") or filename.endswith(".png"):
template = cv2.imread('templates/'+templateFilename,0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
loc = np.where( res >= threshold)
if (len(loc[0])):
detectedCount = detectedCount + 1
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite(resultsDirectory+'/res_'+filename+'.png',img_rgb)
print ('/res_'+filename+'.png'+' saved')
# break
print ('detected positive ' + str(detectedCount))
continue
else:
continue
所以,把上面的代码放到模板中_匹配.py
其他文件夹将与此文件一起位于根目录中。
使文件夹结构如下所示。在
^{pr2}$
您还可以使用此选项检查多个源图像与多个模板。
只需运行py template_matching.py就可以看到魔力了。在