自动化定位元素-图像识别获取元素位置:opencv 模板匹配

背景

没有背景
我想在当前图片上找到某一块图片(称为模板),然后再根据坐标点击操作
模板图片:image

我期望在下面图片上找到他:
image

opencv模板匹配

上代码:

import cv2 as cv
from matplotlib import pyplot as plt

network_path = '/home/tarzan/Desktop/playw_test/images/network.png'
dock_path = '/home/tarzan/Desktop/playw_test/images/dock.png'
template = cv.imread(network_path, 0)
img = cv.imread(dock_path, 0)
img2 = img.copy()
w, h = template.shape[::-1]
print(w, h)
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
           'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
for meth in methods:
    print(meth)
    img = img2.copy()
    method = eval(meth)
    res = cv.matchTemplate(img, template, method)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)

    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    cv.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.TM_CCOEFF结果正确:
    image

  • cv.TM_CCOEFF_NORMED结果正确
    image

  • cv.TM_CCORR结果错误
    image

  • cv.TM_CCORR_NORMED结果正确
    image

  • cv.TM_SQDIFF结果正确
    image

  • cv.TM_SQDIFF_NORMED结果正确
    image

教程地址

https://opencv-python-tutorials.readthedocs.io/zh/latest/4. OpenCV中的图像处理/4.12. 模板匹配/

posted @ 2022-12-29 15:36  Tarzen  阅读(793)  评论(0编辑  收藏  举报