使用Python+OpenCV进行图像模板匹配(Match Template)

2017年9月22日 BY 蓝鲸 LEAVE A COMMENT

687474703a2f2f692e737461636b2e696d6775722e636f6d2f4a496f51382e6a7067

本篇文章介绍使用Python和OpenCV对图像进行模板匹配和识别。模板匹配是在图像中寻找和识别模板的一种简单的方法。以下是具体的步骤及代码。

首先导入所需库文件,numpy和cv2。

Source code    
#导入所需库文件
import cv2
import numpy as np

然后加载原始图像和要搜索的图像模板。OpenCV对原始图像进行处理,创建一个灰度版本,在灰度图像里进行处理和查找匹配。然后使用相同的坐标在原始图像中进行还原并输出。

 

Source code    
#加载原始RGB图像
img_rgb = cv2.imread("photo.jpg")
#创建一个原始图像的灰度版本,所有操作在灰度版本中处理,然后在RGB图像中使用相同坐标还原
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
 
#加载将要搜索的图像模板
template = cv2.imread('face.jpg',0)
#记录图像模板的尺寸
w, h = template.shape[::-1]

这里我们分别输出并查看原始图像,原始图像的灰度版本,以及图像模板。

原图

灰度图

 

匹配图

Source code    
#查看三组图像(图像标签名称,文件名称)
cv2.imshow('rgb',img_rgb)
cv2.imshow('gray',img_gray)
cv2.imshow('template',template)
cv2.waitKey(0)
cv2.destroyAllWindows()

使用matchTemplate在原始图像中查找并匹配图像模板中的内容,并设置阈值。

Source code    
#使用matchTemplate对原始灰度图像和图像模板进行匹配
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
#设定阈值
threshold = 0.7
#res大于70%
loc = np.where( res >= threshold)

匹配完成后在原始图像中使用灰度图像的坐标对原始图像进行标记。

 

Source code    
#使用灰度图像中的坐标对原始RGB图像进行标记
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2)
#显示图像    
cv2.imshow('Detected',img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()

匹配结果

以下为完整代码:

Source code    
def mathc_img(image,Target,value):
    import cv2
    import numpy as np
    img_rgb = cv2.imread(image)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(Target,0)
    w, h = template.shape[::-1]
    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = value
    loc = np.where( res >= threshold)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2)   
    cv2.imshow('Detected',img_rgb)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Source code    
image=("photo.jpg")
Target=('face.jpg')
value=0.9
mathc_img(image,Target,value)



Read more: http://bluewhale.cc/2017-09-22/use-python-opencv-for-image-template-matching-match-template.html#ixzz5HwAZaIKb

posted @ 2018-06-09 22:10  decode126  阅读(6936)  评论(0编辑  收藏  举报