198 West 21th Street, Suite 721 New York NY 10016
(+92) 300-8921854

Template Matching in OpenCV | Tutorial

Template Matching in OpenCV | Tutorial

Task: Find the template image in the original image using OpenCV and create a bounding box around the template in original image. 

Original Image: (Student.jpg) 

Template Image (Template.jpg): 


In this tutorial we will guide you how you can find a face of a person in an image using a technique called Template Matching in OpenCV. 

For this purpose, we will be needing two images the first one is our 

  1. Original image named student.jpg 
  1. Template image named template.jpg 



  1. Import OpenCV and Numpy library. 
import cv2
import numpy as np
  1. Reading the original image 
image = cv2.imread('students.jpg')
  1. Converting the original image to gray scale. 
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
  1. Reading the template image as grayscale and extracting its width and height 
template = cv2.imread('template.jpg',0)
w, h = template.shape[::-1]
  1. Using cv2 matchTemplate function to match grayscale original image with template image 
res = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
  1. Creating a bounding box rectangle where template image is matching original image.    
 cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
  1. Display the dimension of image using print function and resize it according to your display size. 
print('Original Dimensions : ',image.shape)
resized = cv2.resize(image, (800,800), interpolation = cv2.INTER_AREA)
  1. Display the image using  cv2.imshow function and save the result image as template_matching.png in your current directory. 
cv2.imwrite('template_matching.png', image

Result (Template_matching.png): 

Leave a Reply

Your email address will not be published. Required fields are marked *