Python OpenCV – Template Matching

Template Matching is a technique for locating a template image in a larger image. In this example the template image is a red LED. And the larger image (which I call it a frame) in the picture of a circuit on a breadboard.

import numpy as np
import cv2

template = cv2.imread(r'C:\Users\Linawati\Documents\ACCS\OpenCV\template_led.jpg')
frame = cv2.imread(r'C:\Users\Linawati\Documents\ACCS\OpenCV\Template for template matching.jpg') 

#named the windows and resized them to fit computer screen 
cv2.namedWindow("Template", cv2.WINDOW_NORMAL)
cv2.namedWindow("Frame", cv2.WINDOW_NORMAL)
cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Template", 400,400)
cv2.resizeWindow("Frame", 400,400)
cv2.resizeWindow("Result", 400,400)

cv2.imshow("Template", template)
cv2.imshow("Frame", frame)

result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)

#get the min, max value and location and circled the location
minValue, maxValue, minLocation, maxLocation =  cv2.minMaxLoc(result)
print(maxValue, maxLocation)
cv2.circle(result, maxLocation, 60,255,2)


cv2.imshow("Result", result)

cv2.waitKey(0)
cv2.destroyAllWindows()
The printout values of maxValue and maxLocation.
0.8599664568901062 (1658, 1008)
the small white circle at the center image is the red LED location.