Created
July 19, 2019 19:33
-
-
Save pknowledge/eada42b1db043f4cc6a16e66bc6d1bbc to your computer and use it in GitHub Desktop.
Template matching using OpenCV in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
w, h = template.shape[::-1] # you should understand numpy indexing operation in a proper way
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()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting error
w, h = template.shape[:-1]
AttributeError: 'NoneType' object has no attribute 'shape'