TemplateMatch -- Applying masks to templates

I am trying to template match using masked template. However, my results using the mask and without using the mask seems to be exactly the same. Does anyone know what I did wrong here? Here is my code:

import cv2
import numpy as np

# Load the image and the template
img = cv2.imread('Image.bmp', cv2.IMREAD_COLOR)
template = cv2.imread('template.bmp', cv2.IMREAD_COLOR)

h, w = template.shape[:2]
s = (h,w)
# Form the mask (assuming the mask is a grayscale image)
mask1 = np.zeros(s)
mask2 = 255 - mask1

# Ensure the loaded images are valid
if img is None or template is None:
    print("Error: Image, template, or mask not found.")
    exit()

# Perform template matching with the masked template
result = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED, mask1)
result2 = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED, mask2)

# Find the location of the best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
min_val2, max_val2, min_loc2, max_loc2 = cv2.minMaxLoc(result2)

print(cv2.minMaxLoc(result))
print(cv2.minMaxLoc(result2))


# Draw the rectangles around the matched region
top_left1 = max_loc
top_left2 = max_loc2

bottom_right1 = (top_left1[0] + w, top_left1[1] + h)
bottom_right2 = (top_left2[0] + w, top_left2[1] + h)



cv2.rectangle(img, top_left1, bottom_right1, (255, 0, 0), 2)
cv2.rectangle(img, top_left2, bottom_right2, (0, 0, 255), 2)

# Display the result
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

since your ‘mask’ only contains ones, it will ‘let everything through’.

lookup, how masks work, and how to derive a useful one for your object/shape

a mask of all zeros should make the algorithm blind.

did you observe that?

what does the result2 array look like? MINMAX-normalize it before displaying

oh also, pay attention to the dtype. np.zeros returns an array of floats/fp64. matchTemplate() probably does not like that. I’m surprised it didn’t throw an error at you for this.

Thanks for the reply. I wrote this code because I receive some complaints from my colleagues that their results are exactly the same when applying and without applying the mask. That’s why I chose to apply a mask with all zeroes and and a mask with all ones. And it really frightened me when I find the results to be the same.
After reading your post, I realized it is because the way I applied the masks are not correct, I should specify the type in the dumpy array to be uint8.