在编程中,你应该避免使用cv2.minMaxLoc(result)函数,因为它只会返回单个最佳匹配结果。我们需要的是多个好的匹配结果,并且这些结果都要高于一个阈值。
使用非极大值抑制算法是在图像中查找多个匹配结果的一种方法。
import cv2
from imutils.object_detection import non_max_suppression
image = cv2.imread(img_path, cv2.IMREAD_COLOR)
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.90
(yCoords, xCoords) = np.where(result >= threshold)
template_h, template_w = template.shape[:2]
rects = []
for (x, y) in zip(xCoords, yCoords):
rects.append((x, y, x + template_w, y + template_h))
pick = non_max_suppression(np.array(rects))
for (startX, startY, endX, endY) in pick:
cv2.rectangle(image, (startX, startY), (endX, endY),(0, 255, 0), 2)
cv2.imshow('Results', image)
解释:
我们进行非极大值抑制是因为在原始图像中每个匹配周围会有很多“好”的结果(例如将模板向右移动1个像素通常会得到一个好的结果,因此您会在每个对象实例周围获得一堆重叠的边界框)。非极大值抑制将过滤每个图像区域中的一个良好匹配。
请注意,这种非极大值抑制不直接使用分数,因此在使用matchTemplate时,上面提到的this answer可能更适合。