Learn Before
Activity (Process)

Object Detection (Template Matching)

Basic template matching involves having an identical object image (template) and searching for that same pattern within a larger base image. OpenCV provides several methods for template matching:

methods = [cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR, cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]

OpenCV recommends trying all the methods and choosing whichever gives the best match for your use case.

img = cv2.imread('path', 0) template = cv2.imread('path', 0) height, width = template.shape for method in methods: img2 = img.copy() result = cv2.matchTemplate(img2, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: location = min_loc else: location = max_loc bottom_right = (location[0] + width, location[1] + height) cv2.rectangle(img2, location, bottom_right, 255, 5) cv2.imshow("Match", img2) cv2.waitKey(0) cv2.destroyAllWindows()

This slides the template across the base image and scores how well it matches at each position, returning an array of size (W_base - W_temp + 1, H_base - H_temp + 1). The best-matching location is used to draw a rectangle on the base image: SQDIFF-based methods use min_loc, while all other methods use max_loc.

0

1

Updated 2026-07-11

Tags

Python Programming Language

Data Science