pythonopencvimage-processingtemplate-matching

How to find a transparent icon in a picture?


I want to find this icon with transparent background

small image

in this image

large image

I tried the following code:

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)

But, the result is as follows:

result

I think this is because my small image has transparent background. How can I fix that?


Solution

  • Please notice, that cv2.matchTemplate has a mask parameter, where you can set up a mask for the template, which would be the alpha channel of your template (small image). Further, keep in mind to feed image (large image) and template (small image) in that order to cv2.matchTemplate:

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

    To preserve the alpha channel of your template (small image), use the cv2.IMREAD_UNCHANGED flag in cv2.imread:

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

    With these two changes, I get the desired output:

    Output

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