Template Matching - ( Template Matching and Transformations )
Heading h2
Syntax
cv2.matchTemplate(image, templ, method, result=None, mask=None)
Example
import cv2
import numpy as np
# Load the original image and the template
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
template = cv2.imread('template.jpg', cv2.IMREAD_GRAYSCALE)
# Apply template matching using normalized correlation coefficient method
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
# Get the coordinates of the matched region
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
# Draw a rectangle around the matched region
cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2)
# Show the resulting image
cv2.imshow('Matching Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
The output of the above code will be the original image with a rectangle drawn around the matched region.
Explanation
Template matching is a technique in computer vision for finding a sub-image (template) in an image. It is widely used in various applications such as object detection, face recognition, and image segmentation.
cv2.matchTemplate()
is a function in OpenCV for performing template matching. It takes in the original image, the template image, and the method of comparison as input.
In the above example, we load an original image and a template image, and apply template matching using the normalized correlation coefficient method. We then find the coordinates of the matched region using the cv2.minMaxLoc()
function and draw a rectangle around the matched region on the original image using the cv2.rectangle()
function.
Use
Template matching is a powerful technique for finding objects in images. It can be used in various applications such as object detection, face recognition, and image segmentation.
Important Points
- Template matching is a technique in computer vision for finding a sub-image in an image
cv2.matchTemplate()
is a function in OpenCV for performing template matching- It takes in the original image, template image, and method of comparison as input
- The resulting image is a grayscale image with high values where the template matches and low values elsewhere
Summary
In conclusion, template matching is a powerful technique for finding objects in images and can be used in various applications such as object detection and image segmentation. OpenCV provides the cv2.matchTemplate()
function for performing template matching. The function takes in the original image, template image, and method of comparison as input and returns a grayscale image with high values where the template matches and low values elsewhere.