0

I'm trying to find all occurrences of a smaller image within a larger image. Is there a way to set the tolerance level of the match so I could match everything that was at least a 90% match or something like that?

Here's my code right now:

import cv2
from cv2 import cv
import numpy as np

method = cv.CV_TM_SQDIFF_NORMED

small_image = cv2.imread('small_image.jpg')
large_image = cv2.imread('large_image.jpg')

height,width = small_image.shape[:2]

result = cv2.matchTemplate(large_image, small_image, method)
result2 = np.reshape(result, result.shape[0]*result.shape[1])
sort = np.argsort(result2)

for i in range(50):
    (y1, x1) = np.unravel_index(sort[i], result.shape)
    x2 = x1 + width
    y2 = y1 + height
    print '%s: (%s, %s) to (%s, %s)' % (i, x1, y1, x2, y2)
    cv2.rectangle(large_image, (x1-3,y1-3), (x2+3,y2+3), (0,255,255), 2)

cv2.imshow('output',large_image)
cv2.waitKey(0)

1 Answer 1

0

After the function finishes the comparison, the best matches can be found as global minimums (when CV_TM_SQDIFF was used) or maximums (when CV_TM_CCORR or CV_TM_CCOEFF was used) using the minMaxLoc() function

You can use minMaxLoc() to do this threshholding for you.

Here is a tutorial - the key point is below:

   minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

  /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
  if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
  else
    { matchLoc = maxLoc; }

Edit: From comment:

The solution you've given seems to only give SINGLE matches. The issue is that I need to be able to set tolerance for MULTIPLE matches. Am I missing something?

Sort of, like I said, you need to use this value as a threshold. This tutorial shows you how to use that threshold value in order to match for multiple occurrences.

It uses minMaxLoc, then it floodFills the image, then repeats.

4
  • Will that return multiple matches?
    – eisaacson
    Mar 3, 2015 at 21:36
  • The solution you've given seems to only give SINGLE matches. The issue is that I need to be able to set tolerance for MULTIPLE matches. Am I missing something?
    – eisaacson
    Mar 4, 2015 at 15:23
  • Sorry. I'm sure that makes a lot of sense to somebody really familiar with Python and/or OpenCV. Both are pretty new to me. From this AND the tutorial, I still don't see where I set the threshold or pull multiple results.
    – eisaacson
    Mar 4, 2015 at 17:58
  • 1
    this doesn't work for python, those are the c++ arguments
    – duedl0r
    Oct 14, 2015 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.