3

How can I get an absolute value that tells me how much the template matched in the place it matched the best? I know about minMaxLoc() but that only tells me what the biggest value is, but I have no idea what the MAXIMUM value is so that I can get some kind of idea about how good a match it is.

I've seen people saying that you can get a percentage using normalization, but that doesn't really help me since the biggest value will always be 100%. Am I missing something?

Stefan Manciu
  • 490
  • 1
  • 6
  • 19

1 Answers1

3

The OpenCV documentation describes the different formulas available for calculating the template match score at each xy offset position.

If you want an easy metric, use the normalized cross-correlation by passing CV_TM_CCORR_NORMED, to matchTemplate then make sure you don't do the often-used normalization on the result before calling minMaxLoc. The maximum value will be one for a perfect match.

Don't be confused by the word "normalized" in "normalized cross-correlation", this refers to the normalization of brightness/contrast differences between the search image and the template, not to the resulting score.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113
  • So I have to make some tests on 2 photos that will have a perfect match and use the value obtained to calculate the percent for all the future matches? – Stefan Manciu Jul 03 '14 at 06:38
  • 1
    @StefanManciu A perfect match should give an NCC score of +1.0. You can assume that scores of 0..1 equate to 0%..100% match. – Roger Rowland Jul 03 '14 at 06:45
  • 1
    I made some tests and got how it works, but I got a 93% match on two completely unrelated images. I guess that's the algorithms fault and I don't really have a way to work around that. – Stefan Manciu Jul 03 '14 at 06:55
  • 1
    @StefanManciu Well not strictly the fault of the algorithm - the images *were* statistically correlated, they just weren't the same images! This can happen sometimes if the images are noisy - you might get a "better" result if you perform low-pass filtering on both images first, or apply a window function (e.g. a Hanning window) to the template image to avoid edge effects in the frequency domain. – Roger Rowland Jul 03 '14 at 07:54
  • 1
    This answer allows one to take the `matchTemplate()` examples provided by OpenCV to make a sample that actually is useful for 1:1 exact matches. I really wish they provided an alternative sample with these easy changes, or at least some comments either within the code or directly in the sample documentation. It would have saved so many unneeded questions both on StackOverflow and OpenCV's own Q&A site. – kayleeFrye_onDeck Jun 19 '18 at 20:34