我有一张 map , map 上分布着许多相似的符号(树)。我 我正在使用 opencv 查找所有符号的 X、Y 坐标。
它运行良好,但我得到了大量重复的结果。如果我增加过滤器阈值,重复的数量会减少很多符号被遗漏。我尝试编写一些代码来根据接近度过滤结果,但我运气不佳。有没有人知道我可以在这里尝试什么?
img_rgb = cv2.imread('images/map.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('images/tree.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.35
matches = np.where( res >= threshold)
tree_count = 0
for pt in matches:
tree_count += 1
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (255,0,0), 1)
cv2.imwrite('found_map.jpg',img_rgb)
print "Done " + map
最佳答案
您可以跟踪图像中已经检测到树的区域(使用 mask )。然后,如果例如每个匹配项的中心尚未标记,则仅增加树计数器。
代码:
img_rgb = cv2.imread('trees.png')
template = cv2.imread('apple_tree.png')
h, w = template.shape[:2]
res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.95
loc = np.where( res >= threshold)
tree_count = 0
mask = np.zeros(img_rgb.shape[:2], np.uint8)
for pt in zip(*loc[::-1]):
if mask[pt[1] + int(round(h/2)), pt[0] + int(round(w/2))] != 255:
mask[pt[1]:pt[1]+h, pt[0]:pt[0]+w] = 255
tree_count += 1
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,0), 1)
cv2.imwrite('found_map.jpg',img_rgb)
print("Found {} trees in total!".format(tree_count))
您可以注意到底部图像中较细的绿线说明我们检测到 3 棵苹果树而不是 13 棵!
关于python - 使用 Python 删除或防止 OpenCV 中的重复模板匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829469/