How to know if matchTemplate found an object or not?

haykart picture haykart · Dec 15, 2011 · Viewed 39.4k times · Source

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.

Answer

Sam picture Sam · Dec 15, 2011

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