具有多个匹配的opencv python MatchTemplate函数

时间:2013-02-06 10:53:27

标签: python opencv

我试图在大图中找到小图片并使用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)

工作正常我总是得到左上角的坐标,但这只是一点。如果我在大局上有多场比赛,我怎么能得到所有这些?

2 个答案:

答案 0 :(得分:7)

以下是:

result = cv2.matchTemplate(img, template, cv2.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

这是最快的方式,因为上面对所有比赛进行了分类,即使是完全错误的比赛。如果性能对您很重要,您可以使用瓶颈的partsort函数。

答案 1 :(得分:1)

@b_m的答案会起作用,但是会发现太多的匹配项。匹配过程使模板在图像上滑动,并以EVERY PIXEL进行比较。 (或几乎每个像素。扫描区域会因模板的大小而减小)。这意味着在一个好的匹配项附近,您会得到许多其他匹配项,它们相差一个像素。如果您对匹配结果进行图像处理,则可以看到有很多匹配项。

import cv2
import numpy as np

image = cv2.imread('smiley.png', cv2.IMREAD_COLOR )
template = cv2.imread('template.png', cv2.IMREAD_COLOR)

h, w = template.shape[:2]

method = cv2.TM_CCOEFF_NORMED

threshold = 0.95

res = cv2.matchTemplate(image, template, method)
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

cv2.imwrite('output.png', 255*res)

输入图片:

enter image description here

将眼睛用作模板:

enter image description here

并查看输出。两只眼睛附近有很多白色像素。您会得到很多高分的答案:

enter image description here

在同一张图像中查找模板的多个副本的另一种方法是通过覆盖找到的区域,然后再次进行匹配来修改图像。但比这更好的是修改结果并重新运行minMaxLoc。两种技术都在this answer中进行了演示。