14

I'm attempting to find an image in another.

im = cv.LoadImage('1.png', cv.CV_LOAD_IMAGE_UNCHANGED)
    tmp = cv.LoadImage('e1.png', cv.CV_LOAD_IMAGE_UNCHANGED)
    w,h = cv.GetSize(im)
    W,H = cv.GetSize(tmp)
    width = w-W+1
    height = h-H+1
    result = cv.CreateImage((width, height), 32, 1)
    cv.MatchTemplate(im, tmp, result, cv.CV_TM_SQDIFF)
    print result

When I run this, everything executes just fine, no errors get thrown. But I'm unsure what to do from here. The doc says that result stores "A map of comparison results". I tried printing it, but it gives me width, height, and step.

How do I use this information to find whether or not one image is in another/where it is located?

eol
  • 23,236
  • 5
  • 46
  • 64
Zack
  • 4,177
  • 8
  • 34
  • 52
  • 1
    So you don't struggle with OpenCV as much, try SimpleCV. It's a wrapper around the OpenCV modules that makes them easy to use: http://simplecv.org/ – Blender Mar 14 '12 at 20:21

2 Answers2

13

This might work for you! :)

def FindSubImage(im1, im2):
    needle = cv2.imread(im1)
    haystack = cv2.imread(im2)

    result = cv2.matchTemplate(needle,haystack,cv2.TM_CCOEFF_NORMED)
    y,x = np.unravel_index(result.argmax(), result.shape)
    return x,y

CCOEFF_NORMED is just one of many comparison methoeds. See: http://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html for full list.

Not sure if this is the best method, but is fast, and works just fine for me! :)

b0bz
  • 2,140
  • 1
  • 27
  • 27
  • Note that this will always return x, y irregardless of whether the template image is actually present, I recommend using a threshold instead. – Alexis Drakopoulos Dec 27 '20 at 13:42
12

MatchTemplate returns a similarity map and not a location. You can then use this map to find a location.

If you are only looking for a single match you could do something like this to get a location:

minVal,maxVal,minLoc,maxLoc = cv.MinMaxLoc(result)

Then minLoc has the location of the best match and minVal describes how well the template fits. You need to come up with a threshold for minVal to determine whether you consider this result a match or not.

If you are looking for more than one match per image you need to use algorithms like non-maximum supression.

sietschie
  • 7,425
  • 3
  • 33
  • 54