Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created July 19, 2019 19:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pknowledge/eada42b1db043f4cc6a16e66bc6d1bbc to your computer and use it in GitHub Desktop.
Save pknowledge/eada42b1db043f4cc6a16e66bc6d1bbc to your computer and use it in GitHub Desktop.
Template matching using OpenCV in Python
import cv2
import numpy as np
img = cv2.imread("messi5.jpg")
grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("messi_face.jpg", 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(grey_img, template, cv2.TM_CCORR_NORMED )
print(res)
threshold = 0.99;
loc = np.where(res >= threshold)
print(loc)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
@Sudhanshu-mehta
Copy link

Getting error
w, h = template.shape[:-1]
AttributeError: 'NoneType' object has no attribute 'shape'

@Mynuddin-dev
Copy link

w, h = template.shape[::-1] # you should understand numpy indexing operation in a proper way

@Anweshatitly
Copy link

import cv2
import numpy as np

Load the main image

img = cv2.imread(r'C:\opencv-4.x\opencv-4.x\samples\data\lena.jpg')

Convert the main image to grayscale

grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Load the template image

template = cv2.imread(r'C:\opencv-4.x\opencv-4.x\samples\data\lena_face.jpg', 0)

Find the width and height of the template

w, h = template.shape[::-1]

Perform template matching

res = cv2.matchTemplate(grey_img, template, cv2.TM_CCORR_NORMED)

Set a threshold

threshold = 0.99

Find locations where the correlation coefficient is greater than the threshold

loc = np.where(res >= threshold)

Draw rectangles around the matched regions

for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

Display the result

cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

run this code
Screenshot 2024-03-11 224759

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment