Reputation: 1419
THRESHOLD = 0.9
results = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
locations = numpy.where( results >= THRESHOLD) # <---
With the code above (where the arrow is) I can get all the matches that are above a certain threshold
.
But I want just to get the best match from the results
and then check the best match if it is above the threshold
or not. How do I do it?
Note: Please make your answer beginner-friendly.
Upvotes: 1
Views: 2307
Reputation: 21203
You ought to use cv2.minMaxLoc()
. This will return only one and the best match.
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(results)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image.copy(), top_left, bottom_right, 255, 2)
**Illustration: **
I have Messi on the football ground as the images and his face as the template.
img = cv2.imread('C:/Users/selwyn77/Desktop/messi.jpg', 0)
img2 = cv2.imread('C:/Users/selwyn77/Desktop/messi.jpg', 1)
template = cv2.imread('C:/Users/selwyn77/Desktop/messi_face.jpg', 0)
w, h = template.shape[::-1]
#img3 = img2.copy()
res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
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)
cv2.rectangle(img2, top_left, bottom_right, (0, 255, 0), 2)
cv2.imshow('img', img2)
EDIT:
You can set a threshold and check whether max_val
is greater than this threshold. If it is greater then proceed to draw the matching region.
threshold = 0.85
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(results)
if max_val > threshold:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image.copy(), top_left, bottom_right, 255, 2)
Upvotes: 4