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()