如何在图片中找到透明图标?

How to find a transparent icon in a picture?

我要找这个透明背景的图标

在此图像中

我尝试了以下代码:

import cv2
method = cv2.TM_SQDIFF_NORMED

small_image = cv2.imread('icons/new/test.png')
large_image = cv2.imread('icons/example.png')

result = cv2.matchTemplate(small_image, large_image, method)

mn,_,mnLoc,_ = cv2.minMaxLoc(result)

MPx,MPy = mnLoc

trows,tcols = small_image.shape[:2]

cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)

cv2.imshow('output',large_image)

cv2.waitKey(0)

但是,结果如下:

我认为这是因为我的小图片有透明背景。我该如何解决?

请注意,cv2.matchTemplate 有一个 mask 参数,您可以在其中为模板设置遮罩,这将是您的模板(小图像)的 Alpha 通道。此外,请记住按顺序将图像(大图像)和模板(小图像)提供给 cv2.matchTemplate:

result = cv2.matchTemplate(large_image, small_image[..., :3], method, mask=small_image[..., 3])

要保留模板(小图像)的 Alpha 通道,请使用 cv2.IMREAD_UNCHANGED flag in cv2.imread:

small_image = cv2.imread('icons/new/test.png', cv2.IMREAD_UNCHANGED)

通过这两个更改,我得到了所需的输出:

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
OpenCV:        4.5.2
----------------------------------------