Object Detection in Python Using Template Matching
This article demonstrates how to perform object detection in Python without machine‑learning frameworks by using OpenCV’s template‑matching functions, covering single‑object detection, multi‑object detection with thresholding, and providing complete code examples for loading images, matching, locating matches, drawing bounding boxes, and visualizing results.
When hearing “object detection”, one often thinks of machine learning, but this tutorial shows how to detect objects using only Python and OpenCV’s template‑matching functions.
First, a template image is defined and slid over a source image to find the best match. The code reads the source and template images, converts the source to grayscale, obtains the template’s dimensions, and performs matching with cv2.matchTemplate(img_gray, template, cv2.TM_SQDIFF) . The result matrix is visualized with matplotlib, and the location of the minimum value is obtained via min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) . A rectangle is drawn around the match using top_left = min_loc<br/>bottom_right = (top_left[0] + width, top_left[1] + height)<br/>cv2.rectangle(img_rgb, top_left, bottom_right, (255,0,0), 2) , and the final image is displayed.
For detecting multiple objects, the method switches to a normalized correlation coefficient matcher cv2.TM_CCOEFF_NORMED . After matching, a threshold (e.g., 0.5) is applied: threshold = 0.5<br/>loc = np.where(res >= threshold) . All locations above the threshold are iterated, and rectangles are drawn for each match with for pt in zip(loc[::-1]):<br/> cv2.rectangle(img_rgb, pt, (pt[0] + width, pt[1] + height), (255,0,0), 1) . The result is visualized similarly.
The article provides the full source code for both single‑object and multi‑object detection, demonstrating that template matching can be a simple yet effective alternative to machine‑learning‑based detectors for certain tasks.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.