Template matching helps find a small image inside a bigger one. It is like looking for a puzzle piece in a big puzzle.
Template matching in Computer Vision
result = cv2.matchTemplate(image, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
image is the big picture where you search.
template is the small image you want to find.
method is how you compare images, like cv2.TM_CCOEFF_NORMED.
result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
This program loads a big image and a template, finds where the template best fits inside the big image, draws a green box around it, and shows the result. It also prints how confident the match is.
import cv2 import numpy as np # Load the big image and template in grayscale image = cv2.imread('big_image.jpg', cv2.IMREAD_GRAYSCALE) template = cv2.imread('template.jpg', cv2.IMREAD_GRAYSCALE) # Check if images loaded if image is None or template is None: print('Error loading images') exit() # Apply template matching result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) # Find the best match location min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) # Draw a rectangle around the matched region top_left = max_loc h, w = template.shape bottom_right = (top_left[0] + w, top_left[1] + h) image_color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) cv2.rectangle(image_color, top_left, bottom_right, (0, 255, 0), 2) # Show the result cv2.imshow('Matched Result', image_color) cv2.waitKey(0) cv2.destroyAllWindows() # Print match confidence print(f'Maximum match confidence: {max_val:.2f}')
Template matching works best when the template and image have similar lighting and scale.
It is sensitive to rotation and size changes; the template must match exactly.
Use normalized methods like cv2.TM_CCOEFF_NORMED for better results.
Template matching finds a small image inside a bigger one by comparing pixel patterns.
It returns a confidence score and location of the best match.
It is simple but works best when the template matches the image exactly in size and orientation.