opencv python模板匹配_Python OpenCV一个模板匹配函数

该代码段展示了一个Python脚本,用于在单个图像源上测试多个图像模板,以检测是否存在匹配项。它首先创建结果、源图像和模板文件夹,然后遍历源图像和模板,应用匹配模板算法并用红色矩形标记检测到的匹配位置。检测到的匹配项数量会打印出来,且结果图像会被保存到results文件夹中。
摘要由CSDN通过智能技术生成

如果我必须针对单个图像源测试多个模板,我会为模板文件夹创建一个目录(而不是像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就可以看到魔力了。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值