代码之家  ›  专栏  ›  技术社区  ›  Jürgen K.

图像匹配导致图像不应该是一个图像(python opencv教程)

  •  0
  • Jürgen K.  · 技术社区  · 6 年前

    我正在和 following python opencv示例:

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv2.imread('messi5.jpg',0)
    img2 = img.copy()
    template = cv2.imread('template.jpg',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()
    

    匹配在一组选定的图像上工作得很好,这些图像清楚地包含了模板。我的问题是,即使在那些明显不包含模板的图像中,也会绘制一个矩形。我如何适应源代码,这样它就可以处理完全不匹配的图像。

    提前谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ha Bom    6 年前

    在文档中:

    它返回灰度图像,其中每个像素表示该像素的邻域与模板的匹配程度

    因此,为 res 如果图像中没有相似性,它就什么也不做。

    res = cv2.matchTemplate(img,template,method)
    if res<0.8:
        return
    ...
    

    就像在 Template Matching with Multiple Objects part

        2
  •  1
  •   MSpiller    6 年前

    不管匹配有多好,代码总是显示最佳匹配。

    你可以查一下 max_val (或) min_val 什么时候? SQDIFF 仅当该值超过某个阈值时才显示匹配。

    推荐文章