Template matching is a technique in digital image processing for finding small parts of an image that match a template image. It can be used in manufacturing as a part of quality control, or as a way to detect edges in images. OpenCV comes with the cv2.matchTemplate () function for this purpose. It simply launches the template image above the input image and compares the template and pastes the input image under the template image. Several comparison methods are implemented in OpenCV. It returns a grayscale image, where each pixel shows how large the pixel circle is with the template.
If the input image is of size (WxH) and the template image is of size (wxh), the 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 the rectangle and take (w,h) as the width and height of the rectangle. That rectangle is your region of the template.
This video shows how I use OpenCV template matching to find and count the object on an image using Raspberry Pi 400.
This is the list of items used in the video.
This is python3 sample program for OpenCV template matching using Raspberry Pi. You can use it with Thonny Python IDE.
|import numpy as np|
|img = cv2.imread("Cover.jpg")|
|gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)|
|template = cv2.imread("Raspberry Pi.jpg", 0)|
|w, h = template.shape[::–1]|
|count = 0|
|res = cv2.matchTemplate(gray_img, template, cv2.TM_CCORR_NORMED )|
|#methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR','cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']|
|threshold = 0.99;|
|loc = np.where(res >= threshold)|
|for pt in zip(*loc[::–1]):|
|cv2.rectangle(img, pt, (pt + w, pt + h), (0, 255, 0), 2)#colour of rectangle(b,g,r)|
|count = count + 1|
Thanks for reading this tutorial. If you have any technical inquiries, please post at Cytron Technical Forum.
“Please be reminded, this tutorial is prepared for you to try and learn.
You are encouraged to improve the code for better application.“