How does template matching work in OpenCV

This recipe explains how does template matching work in OpenCV

Recipe Objective: How does template matching work in OpenCV?

In this recipe, let us understand how template matching works in OpenCV.

Step 1: Import the libraries and read the input image

Let us first import the necessary libraries and read the image. The image that we are using here is the one shown below. Let us read the image in grayscale this time for better results.

Input Image

import cv2
import numpy as np
from matplotlib import pyplot as plt
image = cv2.imread("ironman.jpg",0)

Step 2: Read the template image

Template matching is nothing but searching for a template image inside a larger image. And hence we will need two images in this process. One is the source image, and the other is the template image. Let us now read the template image. The template image that we are using in this example is shown below. Let us also store the template width and height in temp_w and temp_h for later use

template Image
template = cv2.imread('template.jpg',0)
temp_w, temp_h = template.shape[::-1]

Step 3: Template matching

Now that we have our source and template images ready let us try to find the location of the template image in the source image. This can be done using the cv2.matchTemplate() function, which takes the following arguments.

  • image: The source image
  • templ: The template image
  • method: The method which is to be used to find the template

To put it in a nutshell, the cv2.matchTemplate() function glides the template image over the source image and compares the template with all patches of the source image. The obtained result is compared with a threshold value. Generally, the starting point of the template patch in the source image will have the highest value. Hence, it is enough to consider the location with maximum value.

There are various options available to pass into the method parameter of the cv2.matchTemplate() function. They are :

  • TM_SQDIFF
  • TM_SQDIFF_NORMED
  • TM_CCORR
  • TM_CCORR_NORMED
  • TM_CCOEFF
  • TM_CCOEFF_NORMED

We are going to use the TM_CCORR_NORMED method in this example. It is also important to note that in the case of TM_SQDIFF and TM_SQDIFF_NORMED methods, we should consider the minimum values instead of the maximum values.

result = cv2.matchTemplate(image,template,cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

The cv2.minMaxLoc() function provides the minimum and maximum values of the given image with their corresponding locations.

Step 4: Draw a rectangle around the matched area.

We now have the location of the maximum values in the result array. Let us now find out the coordinates of the matched area in the input image and draw a rectangle around it. The coordinates for the rectangle can be found using the width and height of the template image. Finally, we can quickly draw the rectangle using the cv2.rectangle() function.

top_left = max_loc
bottom_right = (top_left[0] + temp_w, top_left[1] + temp_h)
detected = cv2.rectangle(image,top_left, bottom_right, (255,0,0), 2)

Step 5: Display the output

Let us display the output using the cv2.imshow() function.

cv2.imshow('Detected template',detected)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Output

What Users are saying..

profile image

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

Build Regression Models in Python for House Price Prediction
In this Machine Learning Regression project, you will build and evaluate various regression models in Python for house price prediction.

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Build a Churn Prediction Model using Ensemble Learning
Learn how to build ensemble machine learning models like Random Forest, Adaboost, and Gradient Boosting for Customer Churn Prediction using Python

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

Classification Projects on Machine Learning for Beginners - 2
Learn to implement various ensemble techniques to predict license status for a given business.

Skip Gram Model Python Implementation for Word Embeddings
Skip-Gram Model word2vec Example -Learn how to implement the skip gram algorithm in NLP for word embeddings on a set of documents.