Skip to content

Instantly share code, notes, and snippets.

@yplam
Created June 2, 2017 09:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yplam/3c109f273bf25a2ee3ebe688e37c5e12 to your computer and use it in GitHub Desktop.
Save yplam/3c109f273bf25a2ee3ebe688e37c5e12 to your computer and use it in GitHub Desktop.
Opencv Template Matching with template scale
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()
@def-fun
Copy link

def-fun commented Jul 25, 2021

bug fix for line 20 and line 23:

# if len(zip(*loc[::-1])) > 0:
if len(list(zip(*loc[::-1]))) > 0:
# if loc and len(zip(*loc[::-1])) > 0:
if loc and len(list(zip(*loc[::-1]))) > 0:

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