python - 使用 Python 删除或防止 OpenCV 中的重复模板匹配

标签 python opencv

我有一张 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))

之前(不删除重复项): enter image description here

enter image description here

之后(使用掩码删除重复项): enter image description here enter image description here

您可以注意到底部图像中较细的绿线说明我们检测到 3 棵苹果树而不是 13 棵!

关于python - 使用 Python 删除或防止 OpenCV 中的重复模板匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21829469/

相关文章:

python - numpy array - 使用 np.concatenate 或 np.insert 将零行添加到 ndarray

python - 了解 toolz 用例

python - PyQt GUI 在 Python 中多线程时卡住,直到线程完成

c++ - OpenCV drawMatches 错误

python - OpenCV:selectROI返回零元组

python - 无法将 Django 设置为与 smtp.gmail.com 一起使用

python - 使用 python SDK v2 删除 AzureML 模型

python - 如何手动将包安装到 anaconda 的 python 发行版中?

c++ - 从 MATLAB 到 C++ : equivalent of bwmorph with option 'remove'

python - 在 GUI 中嵌入窗口