微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我想找个透明背景的图标

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,255),2)

cv2.imshow('output',large_image)

cv2.waitKey(0)

但是,结果如下:

result

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

解决方法

请注意,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)

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

Output

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。