Skip to content

Instantly share code, notes, and snippets.

@ahmadmustafaanis
Created July 17, 2021 06:16
Show Gist options
  • Save ahmadmustafaanis/6b8f9ad29a53d01867f49d38acbb7ee1 to your computer and use it in GitHub Desktop.
Save ahmadmustafaanis/6b8f9ad29a53d01867f49d38acbb7ee1 to your computer and use it in GitHub Desktop.
Give
import numpy as np
import matplotlib.pyplot as plt
import cv2
def template_detection(image, template):
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
fig, axs = plt.subplots(2,3, figsize=(15, 6))
axs = axs.ravel()
fig.subplots_adjust(hspace = .5, wspace=.001)
_,w, h = template.shape[::-1]
for i,meth in zip(range(len(methods)), methods):
img = image.copy()
method = eval(meth)
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img,top_left, bottom_right, (0,0,0), 4)
axs[i].imshow(img)
axs[i].set_title(f'Template Matching using \n{meth}')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment