How to use OpenCV MatchTemplate?

I am trying 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 runs fine, no errors occur. But I'm not sure what to do next. Doc says that result stores a "map of comparison results." I tried to print it, but it gives me width, height and pitch.

How to use this information to determine if one image is in another / where is it located?

+6
source share
2 answers

MatchTemplate returns a similarity map, not a location. Then you can use this map to search for a location.

If you are looking for only one match, you can do something like this to get the location:

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

Then minLoc has the best match, and minVal describes how well the template fits. You need to create a threshold for minVal to determine if you think this result is a match or not.

If you are looking for more than one match for each image, you need to use algorithms such as non-maximum suppression.

+7
source

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 methods. See: http://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html for a complete list.

Not sure if this is the best method, but quick and works great for me! :)

+4
source

Source: https://habr.com/ru/post/910745/


All Articles