1

I have a set of Pokemon sprites (example) and an image where one of these sprite is shown. an image contains a sprite I am planning to find the best match result among sprites with res = cv2.matchTemplate so that the name of that Pokemon can be obtained.

for t in templates:
    res = cv2.matchTemplate(img, t, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

However, I don't know how to pick the best result with the res. How to use res as a metric to evaluate the match? Thank you!

  • For the CCOEFF method, your `max_loc` will tell you the (x, y) position of the maximum correlation coefficient (which will be where the template matches the best). My answer [here](https://stackoverflow.com/questions/58158129/understanding-and-evaluating-template-matching-methods/58160295#58160295) might help; it tries to explain all the different template matching modes. I'd actually recommend SQDIFF for digital images, as I discuss in that answer. – alkasm Mar 14 '21 at 10:06

1 Answers1

0

The tutorial here describes how to use the output of the matchTemplate function to choose the best match: https://docs.opencv.org/3.4/de/da9/tutorial_template_matching.html

It looks as though you may simply be missing the normalize call, which scales all results to a set range. In the case of the tutorial's example, this range is 0 - 1.

In your case, the below should be what you'll need:

cv2.normalize( res, res, 0, 1, cv2.NORM_MINMAX, -1 )

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)


if (match_method == cv2.TM_SQDIFF or match_method == cv2.TM_SQDIFF_NORMED):
    match_loc = min_loc
else:
    match_loc = max_loc 

Where match_loc gives you the best match depending on the template matching method used.

Edit: If there's a threshold where you decide, say, a "best" match above/below (depending on the method used) 0.5 is considered not a match at all, then you would implement the logic to indicate that no match was found.

Abstract
  • 985
  • 2
  • 8
  • 18