资讯专栏INFORMATION COLUMN

opencv python 模板匹配

魏明 / 982人阅读

摘要:理论模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。将其作为矩形的左上角,并将,作为矩形的宽度和高度中的模板匹配与多个对象匹配的模板将不会提供所有的位置在这种情况下,我们将使用阈值

Template Matching

理论

模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。OpenCV带有一个函数cv2.matchTemplate()用于此目的.它只是简单地将模板图像放在输入图像上(就像在2D卷积中那样),并在模板图像下对输入图像的模板和补丁进行比较,在OpenCV中实现了几种比较方法,它返回一个灰度图像,每个像素表示该像素区域与模板的匹配程度.

如果输入图像的大小(W x H)且模板图像的大小(w x h),则输出图像的大小为(W-w + 1,H-h + 1).获得结果后,可以使用cv.minMaxLoc()函数查找最大/最小值的位置。将其作为矩形的左上角,并将(w,h)作为矩形的宽度和高度.

OpenCV中的模板匹配
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread("img.jpg",0)
img2 = img.copy()
template = cv2.imread("img_roi.png",0)
w, h = template.shape[::-1]

# All the 6 methods for comparison in a list
methods = ["cv2.TM_CCOEFF", "cv2.TM_CCOEFF_NORMED", "cv2.TM_CCORR",
            "cv2.TM_CCORR_NORMED", "cv2.TM_SQDIFF", "cv2.TM_SQDIFF_NORMED"]

for meth in methods:
    img = img2.copy()
    method = eval(meth)

    # Apply template Matching
    res = cv2.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    cv2.rectangle(img,top_left, bottom_right, 255, 2)

    plt.subplot(121),plt.imshow(res,cmap = "gray")
    plt.title("Matching Result"), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img,cmap = "gray")
    plt.title("Detected Point"), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)

    plt.show()

与多个对象匹配的模板

cv.minMaxLoc()将不会提供所有的位置.在这种情况下,我们将使用阈值.

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

img_rgb = cv2.imread("img5.png")
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread("img_roi1.png",0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

cv2.imshow("res",img_rgb)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42031.html

相关文章

  • OpenCV搞定腾讯滑块验证码

    摘要:前言废话滑块验证码破解是一直都想搞的项目,毕竟多数网站都会采用滑块验证码,于是最近在修改论文的闲暇之余把这事儿给解决了。 前言 废话滑块验证码破解是一直都想搞的项目,毕竟多数网站都会采用滑块验证码,于是最近在修改论文的闲暇之余把这事儿给解决了。要搞现在的滑块验证码绕不开图像处理,图像处理当然是首推OpenCV-Python啦!当然我的OpenCV非常菜(P.S.两天速成不敢保证代码质量...

    loostudy 评论0 收藏0

发表评论

0条评论

魏明

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<