In this IPython Notebook, we will explore the various template matching methods provided by OpenCV. The first step is to import the required modules.
%pylab inline
# OpenCV Bindings
import cv2
# Install this utility package from pip using
# pip install cvutils
import cvutils
Populating the interactive namespace from numpy and matplotlib
Next, we will load the source image in a numpy array im_src
and the template image in another numpy array im_tplt
. We will also display the images. We'll look for the template image in the source.
# Load the images
im_src = cv2.imread("../data/template-matching/wayne-rooney.jpg")
im_tplt = cv2.imread("../data/template-matching/wayne-rooney-template.jpg")
# Display the images
cvutils.imshow("Source Image", im_src)
cvutils.imshow("Template Image", im_tplt)
We now iterate over all the 6 methods available for use in OpenCV. The cv2.matchTemplate
function returns a mask based on the method used for performing template matching in the source image.
Based on the methods used, we need to look up global maxima or global minima in the mask image.
We will use cv2.minMaxLoc
function to find the global maxima and global minima. Once we have calculated the extremas, we draw the matched template on the input image and display it. Additionally, we also display the template matching mask.
# List to all the Template Matching methods
methods = (cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR, cv2.TM_CCORR_NORMED,
cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED)
# Names of all the methods for template matching
methods_names = ("Correlation Coefficient", "Normalized Correlation Coefficient", "Correlation",
"Normalized Correlation", "Sum of Differences", "Normalized Sum of Differences")
# For each method in the list above perform template matching
for index, method in enumerate(methods):
# Get the Template Matching Mask
result = cv2.matchTemplate(im_src, im_tplt, method)
# Get the location of the global minima and maxima
# Minima Co-ordinates are in minLoc and Maxima Co-ordinates are in maxLoc
_, _, minLoc, maxLoc = cv2.minMaxLoc(result)
# In Sum of Squared Difference, we need to look for minimas
# In Correlation Coefficient, we need to look for maximas
# In Correlation, we need to look for maximas
if method in (cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED):
top_left = minLoc
else:
top_left = maxLoc
# Get the bottom right co-ordinate
bottom_right = (top_left[0]+im_tplt.shape[1], top_left[1]+im_tplt.shape[0])
# Draw the matched template on the input image and display it
im_display = im_src.copy()
cv2.rectangle(im_display, top_left, bottom_right, (255,255,255), 2)
cvutils.imshow("Resulting Match with {}".format(methods_names[index]), im_display)
# Display the template matching mask
cvutils.imshow("TM Mask with {}".format(methods_names[index]), result)