Opencv python Multiple Match MatchTemplate Function

I am trying to find a small picture in a large picture and use MatchTemplate ()

img = cv2.imread("c:\picture.jpg")
template = cv2.imread("c:\template.jpg")

result = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
y,x = np.unravel_index(result.argmax(), result.shape)

It works well. I always get the coordinates of the upper left corner, but this is only one point. If I have some matches in the big picture, how can I get them all?

+5
source share
1 answer

Here's how:

result = cv2.matchTemplate(img,template,cv.CV_TM_SQDIFF)

#the get the best match fast use this:
(min_x,max_y,minloc,maxloc) = cv2.minMaxLoc(result)
(x,y) = minloc

#get all the matches:
result2 = np.reshape(result, result.shape[0]*result.shape[1])
sort = np.argsort(result2)
(y1, x1) = np.unravel_index(sort[0], result.shape) #best match
(y2, x2) = np.unravel_index(sort[1], result.shape) #second best match

This is the fastest way, as the aforementioned sortings of all matches, even completely wrong ones. If performance is important to you, you can use the partsort bottleneck instead .

+4
source

All Articles