OpenCV  3.1.0
Open Source Computer Vision
Template Matching

Goals

In this chapter, you will learn

Theory

Template Matching is a method for searching and finding the location of a template image in a larger image. OpenCV comes with a function cv2.matchTemplate() for this purpose. It simply slides the template image over the input image (as in 2D convolution) and compares the template and patch of input image under the template image. Several comparison methods are implemented in OpenCV. (You can check docs for more details). It returns a grayscale image, where each pixel denotes how much does the neighbourhood of that pixel match with template.

If input image is of size (WxH) and template image is of size (wxh), output image will have a size of (W-w+1, H-h+1). Once you got the result, you can use cv2.minMaxLoc() function to find where is the maximum/minimum value. Take it as the top-left corner of rectangle and take (w,h) as width and height of the rectangle. That rectangle is your region of template.

Note
If you are using cv2.TM_SQDIFF as comparison method, minimum value gives the best match.

Template Matching in OpenCV

Here, as an example, we will search for Messi's face in his photo. So I created a template as below:

messi_face.jpg
image

We will try all the comparison methods so that we can see how their results look like:

1 import cv2
2 import numpy as np
3 from matplotlib import pyplot as plt
4 
5 img = cv2.imread('messi5.jpg',0)
6 img2 = img.copy()
7 template = cv2.imread('template.jpg',0)
8 w, h = template.shape[::-1]
9 
10 # All the 6 methods for comparison in a list
11 methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
12  'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
13 
14 for meth in methods:
15  img = img2.copy()
16  method = eval(meth)
17 
18  # Apply template Matching
19  res = cv2.matchTemplate(img,template,method)
20  min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
21 
22  # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
23  if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
24  top_left = min_loc
25  else:
26  top_left = max_loc
27  bottom_right = (top_left[0] + w, top_left[1] + h)
28 
29  cv2.rectangle(img,top_left, bottom_right, 255, 2)
30 
31  plt.subplot(121),plt.imshow(res,cmap = 'gray')
32  plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
33  plt.subplot(122),plt.imshow(img,cmap = 'gray')
34  plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
35  plt.suptitle(meth)
36 
37  plt.show()

See the results below:

template_ccoeff_1.jpg
image
template_ccoeffn_2.jpg
image
template_ccorr_3.jpg
image
template_ccorrn_4.jpg
image
template_sqdiff_5.jpg
image
template_sqdiffn_6.jpg
image

You can see that the result using cv2.TM_CCORR is not good as we expected.

Template Matching with Multiple Objects

In the previous section, we searched image for Messi's face, which occurs only once in the image. Suppose you are searching for an object which has multiple occurances, cv2.minMaxLoc() won't give you all the locations. In that case, we will use thresholding. So in this example, we will use a screenshot of the famous game Mario and we will find the coins in it.

1 import cv2
2 import numpy as np
3 from matplotlib import pyplot as plt
4 
5 img_rgb = cv2.imread('mario.png')
6 img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
7 template = cv2.imread('mario_coin.png',0)
8 w, h = template.shape[::-1]
9 
10 res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
11 threshold = 0.8
12 loc = np.where( res >= threshold)
13 for pt in zip(*loc[::-1]):
14  cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
15 
16 cv2.imwrite('res.png',img_rgb)

Result:

res_mario.jpg
image

Additional Resources

Exercises