如何匹配模板透明图像opencv

How to matchtemplate a transparent image opencv

我尝试了这个答案中的方法:,这正是我要找的,但对我来说没有用,我在 alpha 之后一直得到黑色图像处理中。

我试过了

    result = cv2.matchTemplate(Image, Template, cv2.TM_CCOEFF_NORMED)

    base = template[:,:,0:3]
    alpha = template[:,:,3]
    alpha = cv2.merge([alpha,alpha,alpha])

    # do masked template matching and save correlation image
    correlation = cv2.matchTemplate(img, base, cv2.TM_CCORR_NORMED, mask=alpha)

模板: 1

图片: 2

模板在左下方供参考

试试这个:

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

original = cv.imread('Original_game.png')
img = cv.imread('Original_game.png',0)
img2 = img.copy()
template = cv.imread('template.png',0)

w, h = template.shape[::-1]
# All the 3 methods for comparison in a list
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR_NORMED']#,'cv.TM_CCORR','cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED'

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

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

    print(f"meth={meth} , min_val={min_val}, max_val={max_val}, min_loc={min_loc}, max_loc={max_loc}")
    
    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = min_loc#max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv.rectangle(original,top_left, bottom_right, 255, 2)
    fig = plt.figure(figsize=(10, 7))
    plt.imshow(original)
    plt.show()

示例结果:

关注算法:

  1. 更改阈值以找到不同的匹配位置
  2. 更改匹配算法

检查为什么有时应该使用最大值而有时使用最小值找到位置匹配。

有用的链接:

Template Matching

OpenCV Template Matching ( cv2.matchTemplate )

Template matching using OpenCV in Python

更新 #1

如果您想获得更好的结果,您应该使用“HOG”、“Surf”、“SIFT”和...等特征描述符。或者像 YOLO 这样的最先进的对象检测模型是您的问题最广为人知的。