Created
June 2, 2017 09:48
-
-
Save yplam/3c109f273bf25a2ee3ebe688e37c5e12 to your computer and use it in GitHub Desktop.
Opencv Template Matching with template scale
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 numpy as np | |
import cv2 | |
import imutils | |
template = cv2.imread('template.jpg') # template image | |
image_o = cv2.imread('image.jpg') # image | |
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) | |
image = cv2.cvtColor(image_o, cv2.COLOR_BGR2GRAY) | |
loc = False | |
threshold = 0.9 | |
w, h = template.shape[::-1] | |
for scale in np.linspace(0.2, 1.0, 20)[::-1]: | |
resized = imutils.resize(template, width = int(template.shape[1] * scale)) | |
w, h = resized.shape[::-1] | |
res = cv2.matchTemplate(image,resized,cv2.TM_CCOEFF_NORMED) | |
loc = np.where( res >= threshold) | |
if len(zip(*loc[::-1])) > 0: | |
break | |
if loc and len(zip(*loc[::-1])) > 0: | |
for pt in zip(*loc[::-1]): | |
cv2.rectangle(image_o, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) | |
cv2.imshow('Matched Template', image_o) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bug fix for line 20 and line 23: