What is template matching

Template matching refers to finding the most similar part of image B in the current image A, which can be understood as finding fault, but here it is finding the same information.

Generally we call image A the input image and image B the template image. The principle of template matching is to slide the template B image over the image A to find the part that matches it.

Template matching function

In OpenCV, it gives us the cv2.matchtemplate () function to do template matching. The full definition of its function is as follows:

def matchTemplate(image, templ, method, result=None, mask=None) :
Copy the code

Image: original image

Templ: Template image

Method: Indicates the matching method. This parameter is implemented through TemplateMatchModes as shown in the following table:

parameter The values meaning
cv2.TM_SQDIFF 0 Match based on variance. If the match is perfect, the result is 0; If they don’t match, you get a big difference
cv2.TM_SQDIFF_NORMED 1 Standard (normalized) square variance matching
cv2.TM_CCORR 2 Correlation matching, which multiplicates the template image and the input image. If the product is larger, the matching degree is higher. If the product is 0, the match is the worst
cv2.TM_CCORR_NORMED 3 Standard (normalized) correlation matching
cv2.TM_CCOEFF 4 Correlation system matching, which matches the relative value of the template image with its mean value and the relative value of the input image with its mean value. 1 for a perfect match, -1 for a bad match, and 0 for no correlation match (random sequence)
cv2.TM_CCOEFF_NORMED 5 Standard (normalized) correlation coefficient matching

Result: returns a value. It is a result set composed of a combination of comparison results at each position and is of type single-channel 32-bit floating point. If the input image size is WH and the template size is WH, the size of the returned value is (w-W +1)*(h-H +1).

Mask: Mask of template image. It must have the same type of size as the template image. Usually use the default value.

Implement template matching

First of all, we need two pictures, here we still choose the often used beauty photo and the eye part as the template image, as follows:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("4.jpg".0)
template = cv2.imread("4_1.jpg".0)

th, tw = template.shape[::]

rv = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
min.max, minLoc, maxLoc = cv2.minMaxLoc(rv)

topLeft = minLoc
bottomRight = (topLeft[0] + tw, topLeft[1] + th)
cv2.rectangle(img, topLeft, bottomRight, 255.2)

plt.subplot(121)
plt.imshow(template, cmap="gray")
plt.axis('off')
plt.subplot(122)
plt.imshow(img, cmap="gray")
plt.axis('off')
plt.show()
Copy the code

After running, the effect is as follows:

Appendix:

Template figure

The original image