OpenCV Template Matching on Raspberry Pi 400

Do you know what is template matching?


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.

Hardware Preparation

This is the list of items used in the video.

Sample Program

This is python3 sample program for OpenCV template matching using Raspberry Pi. You can use it with Thonny Python IDE.

import cv2
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 )
threshold = 0.99;
loc = np.where(res >= threshold)
for pt in zip(*loc[::1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)#colour of rectangle(b,g,r)
count = count + 1
cv2.imshow("img", img)

view raw
hosted with ❤ by GitHub


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.

1 thought on “OpenCV Template Matching on Raspberry Pi 400”

Leave a Comment

Your email address will not be published.

Share this Tutorial

Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest
Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest

Latest Tutorial

DIY Digital Alarm Clock Using REKA:BIT With Micro:bit
Display Internet Time (NTP) on micro:bit
DIY Interactive Robot Using REKA:BIT With Micro:bit
BLTouch Installation for Ender 3 with 32-bit V4.2.2 Board
Pick and Send Random Meal’s Option and Locations through Telegram Bot Using Grove WiFi 8266 on micro:bit
Tutorials of Cytron Technologies Scroll to Top