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.

haykart
  • 957
  • 5
  • 14
  • 34

1 Answers1

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

Sam
  • 19,708
  • 4
  • 59
  • 82
  • If it is possible can you say what function or class I must use for checking? – haykart Dec 15 '11 at 16:12
  • 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() ) – Sam Dec 16 '11 at 06:41
  • if `matchTemplate()` returns probability, why would I get negative value from the return matrix. Do you have any idea about it? – G_cy Jun 20 '18 at 08:42
  • @G_cy 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 https://docs.opencv.org/4.x/d4/dc6/tutorial_py_template_matching.html – Rstar37 Jan 28 '22 at 07:29