Open In App

Template matching using OpenCV in Python

Template matching is a technique for finding areas of an image that are similar to a patch (template). A patch is a small image with certain features. The goal of template matching is to find the patch/template in an image. To find it, the user has to give two input images: Source Image (S) – The image to find the template in, and Template Image (T) – The image that is to be found in the source image.  

How does Template Matching Work?




# Python program to illustrate
# template matching
import cv2
import numpy as np
  
# Read the main image
img_rgb = cv2.imread('mainimage.jpg').
  
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
  
# Read the template
template = cv2.imread('template', 0)
  
# Store width and height of template in w and h
w, h = template.shape[::-1]
  
# Perform match operations.
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
  
# Specify a threshold
threshold = 0.8
  
# Store the coordinates of matched area in a numpy array
loc = np.where(res >= threshold)
  
# Draw a rectangle around the matched region.
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2)
  
# Show the final image with the matched area.
cv2.imshow('Detected', img_rgb)

Limitations of Template Matching: 

  1. Pattern occurrences have to preserve the orientation of the reference pattern image(template)
  2. As a result, it does not work for rotated or scaled versions of the template as a change in shape/size/shear, etc. of object w.r.t. the template will give a false match.
  3. The method is inefficient when calculating the pattern correlation image for medium to large images as the process is time-consuming.

To avoid the issue caused by the different sizes of the template and original image we can use multiscaling. In the case where, just because the dimensions of your template do not match the dimensions of the region in the image you want to match, does not mean that you cannot apply template matching. 

Multiscaling mechanism in Template Matching

The process of Multi scaling is as follows: 

  1. Loop over the input image at multiple scales (i.e. make the input image progressively smaller and smaller).
  2. Apply template matching using cv2.matchTemplate and keep track of the match with the largest correlation coefficient (along with the x, and y-coordinates of the region with the largest correlation coefficient).
  3. After looping over all scales, take the region with the largest correlation coefficient and use that as your “matched” region.




# Python program to illustrate
# template matching
import cv2
import numpy as np
  
# Read the main image
img_rgb = cv2.imread('mainimage.jpg').
  
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
  
# Read the template
template = cv2.imread('template', 0)
  
# Store width and height of template in w and h
w, h = template.shape[::-1]
  
# Resize the image according to scale and
# keeping track of ratio of resizing
resize = imutils.resize(img_gray, width=int(shape[0]), height=int(img_gray.shape[1]*scale)
  
# If resize image is smaller than that of template
# break the loop
# Detect edges in the resized, grayscale image and apply template
# Matching to find the template in image edged
# If we have found a new maximum correlation value, update
# the found variable if
# found = null/maxVal > found][0]
if resized.shape[0] < h or resized.shape[1] < w:
          break
found=(maxVal, maxLoc, r)
  
# Unpack the found variables and compute(x,y) coordinates
# of the bounding box
(__, maxLoc, r)=found
(startX, startY)=(int(maxLoc[0]*r), int maxLoc[1]*r)
(endX, endY)=(int((maxLoc[0]+tw)*r), int(maxLoc[1]+tH)*r)
  
# Draw a bounding box around the detected result and display the image
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)

A step-by-step explanation of the above code is as follows: 

 


Article Tags :