Created
March 4, 2013 06:57
-
-
Save moshekaplan/5080519 to your computer and use it in GitHub Desktop.
Python OpenCV example (2.3.1) - matchTemplate
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 | |
from cv2 import cv | |
method = cv.CV_TM_SQDIFF_NORMED | |
template_name = "mozicon128.png" | |
image_name = "test2.jpeg" | |
# Load | |
needle = cv2.imread(template_name) | |
haystack = cv2.imread(image_name) | |
# Convert to gray: | |
needle_g = cv2.cvtColor(needle, cv2.CV_32FC1) | |
haystack_g = cv2.cvtColor(haystack, cv2.CV_32FC1) | |
# Attempt match | |
d = cv2.matchTemplate(needle_g, haystack_g, cv2.cv.CV_TM_SQDIFF_NORMED) | |
# we want the minimum squared difference | |
mn,_,mnLoc,_ = cv2.minMaxLoc(d) | |
# Print it, for comparison | |
print mn | |
# Draw the rectangle | |
MPx,MPy = mnLoc | |
trows,tcols = needle_g.shape[:2] | |
# Normed methods give better results, ie matchvalue = [1,3,5], others sometimes shows errors | |
cv2.rectangle(haystack, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2) | |
cv2.imshow('output',haystack) | |
cv2.waitKey(0) | |
import sys | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment