What is the main purpose of template matching in computer vision?
Think about matching a small picture inside a bigger one.
Template matching is used to locate a smaller image within a larger one by sliding the template over the image and comparing regions.
Given the following Python code using OpenCV, what is the shape of the result matrix?
import cv2 import numpy as np img = np.zeros((100, 100), dtype=np.uint8) template = np.zeros((20, 20), dtype=np.uint8) result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) print(result.shape)
The result size is the input image size minus the template size plus one.
The result matrix shape is (image_height - template_height + 1, image_width - template_width + 1). Here, 100 - 20 + 1 = 81.
Which OpenCV template matching method is best when you want to find the location with the highest similarity score?
Look for the method that normalizes and uses correlation coefficient.
cv2.TM_CCOEFF_NORMED returns values between -1 and 1, where 1 means perfect match, so the highest value indicates best match.
When using cv2.TM_SQDIFF method, what does a lower score in the result matrix indicate?
Think about squared differences and what a small value means.
cv2.TM_SQDIFF calculates squared differences; lower values mean the template and image region are more similar.
What error will this code produce when run, and why?
import cv2 import numpy as np img = np.zeros((50, 50), dtype=np.uint8) template = np.zeros((60, 60), dtype=np.uint8) result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) print(result.shape)
Check the sizes of the image and template.
The template cannot be larger than the image. OpenCV raises an assertion error if template size exceeds image size.