问题描述
我想找个透明背景的图标
我尝试了以下代码:
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,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
中使用 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
----------------------------------------