Skip to content

Instantly share code, notes, and snippets.

@AVatch
Created May 9, 2016 19:01
Show Gist options
  • Save AVatch/a266eab29e7882acf8962c4c81e4c5be to your computer and use it in GitHub Desktop.
Save AVatch/a266eab29e7882acf8962c4c81e4c5be to your computer and use it in GitHub Desktop.
OpenCV Template Matching
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Load images
img = cv2.imread('image.jpg', 0)
template = cv2.imread('template.jpg', 0)
w, h = template.shape[::-1]
# Apply template matching
# availible methods are
# cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR
# cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED
res = cv2.mathTemplate( template, img, cv2.TM_CCOEFF )
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc( res )
top_left = max_loc
bottom_right = ( top_left[0] + w, top_left[1] + h )
# draw box on template
cv2.rectangle( template, top_left, bottom_right, 255, 2 )
plt.imshow( template, cmap='gray' )
ply.show()
@melsener
Copy link

this code has several syntax errors.

@BrilliantOne
Copy link

Line 15 should be:
res = cv2.matchTemplate( template, img, cv2.TM_CCOEFF )

Line 24 should be:
plt.show()

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