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

2024-09-27 22:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到这个背景透明的图标

small image

在这幅图中

large image

我尝试了以下代码:

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)

但是,结果如下:

result

我想这是因为我的小图像有透明的背景。我怎样才能解决这个问题


Tags: imagepngresultcv2methodsmalliconslarge
1条回答
网友
1楼 · 发布于 2024-09-27 22:34:41

请注意,^{}有一个mask参数,您可以在其中为模板设置掩码,该掩码将是模板的alpha通道(小图像)。此外,请记住,按以下顺序馈送图像(大图像)和模板(小图像):

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

要保留模板的alpha通道(小图像),请使用^{}中的^{}标志:

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

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

Output

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

相关问题 更多 >

    热门问题