How to know if matchTemplate found an object or not?
Asked Answered
E

2

8

I used this answer and wrote my own program, but I have a specific problem.

If the image does not have the object, matchTemplate does not throw an error, and I do not know of any method to check if matchTemplate found the object or not, can anyone give me advice, or give me a function name which checks this.

Extraction answered 15/12, 2011 at 13:31 Comment(0)
A
12

matchTemplate() returns a matrix whose values indicate the probability that your object is centered in that pixel. If you know the object (and only one object) is there, all you have to do is look for the location of the maximum value.

If you don't know, you have to find the max value, and if it is above a certain threshold, your object should be there.

Now, selection of that threshold is tricky - it's up to you to find the good threshold specifically for your app. And of course you'll have some false positives (when there is no object, but the max is bigger than threshold), and some false negatives (your object does not create a big enough peak)

The way to choose the threshold is to collect a fairly large database of images with and without your object inside, and make a statistic of how big is the peak when object is inside, and how big is when it isn't, and choose the threshold that best separates the two classes

Amble answered 15/12, 2011 at 14:20 Comment(4)
If it is possible can you say what function or class I must use for checking?Extraction
minMaxLoc(), in the link you provided, returns only the max location. Fill in the right place a double ref, instead of NULL, and you will receive the max value in the image. (check the OpenCV doc for minMaxLoc() )Amble
if matchTemplate() returns probability, why would I get negative value from the return matrix. Do you have any idea about it?Choragus
@Choragus it can return negative depending on the method you have used, I'd suggest you to read about each method if you're only going to be using one here's a good site showing all methods docs.opencv.org/4.x/d4/dc6/tutorial_py_template_matching.htmlFiscus
N
0

In my project I used Template Matching with Multiple Objects example and just checked length one of "loc" array:

 res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
 threshold = 0.20
 loc = np.where( res >= threshold) 

 if len(loc[0])>0:
     detection = True
 else:
     detection = False
Nellienellir answered 6/10, 2023 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.