首页 > 解决方案 > cv2.matchTemplate 在图像中找到错误的模板

问题描述

我正在尝试创建一个程序,该程序知道具有以下功能的图像上的数字:

def img_in_img(big_picture, small_picture, tamper):
    big_picture = str(big_picture)
    small_picture = str(small_picture)
    if os.path.isfile(big_picture) == False or os.path.isfile(small_picture) == False:
        return "Image does not exist"

    img = cv2.imread(big_picture,0)
    templace_loc = small_picture
    template = cv2.imread(templace_loc,0)
    w, h = template.shape[::-1]
    method = cv2.TM_CCOEFF
    
    tamper = int(tamper)

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

    top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    height, width, channels = cv2.imread(templace_loc).shape

    if int(top_left[0]) < int(height + tamper) and int(top_left[0]) > int(height - tamper) and int(top_left[1]) < int(width + tamper) and int(top_left[1]) > int(width - tamper):
        return True
    else:
        return False

但是当我检查是否7.pngimg.png代码中时

nur = "7"
if img_in_img("2020-01-14-17-36-08.537043/verification_image2.png", "verifynr/" + "old_orange" + "/" + nur + ".png", 25):
    print(Style.BRIGHT + Fore.GREEN + "Color: " + "old_orange" + ", Num: " + nur + Fore.RESET)
else:
    print(Style.BRIGHT + Fore.RED + "Color: " + "old_orange" + ", Num: " + nur + Fore.RESET)

它给了我红色:Color: old_orange, Num: 7

但是,如果我通过更改from来检查是否6.png在其中,它会给我 Green: ,但这是错误的图像。img.pngnur76Color: old_orange, Num: 6

我还尝试了以下代码:

img_rgb = cv2.imread("2020-01-14-17-36-08.537043/verification_image2.png")
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('verifynr/old_orange/7.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_SQDIFF)
threshold = 0.8
loc = np.where( res >= threshold)
pt = list(zip(*loc[::-1]))

if len(pt) >= 1:
    print("True")

打印True,但它为我保存的每个数字 png 执行此操作。

如何让我的程序7.pngimg.png不识别每个数字 png 的情况下识别 in?

图片.png:

图片.png

6.png:

6.png

7.png:

7.png

标签: pythonpython-3.xopencv

解决方案


模板匹配不用于物体检测或模式识别,它的功能是找到最相似的补丁位置。对于检测使用检测器(haar,基于 dnn 的检测器,...),对于识别使用分类器(基于描述符或基于 nn)。'


推荐阅读