繁体   English   中英

在Numpy数组中匹配模板的最有效方法是什么?

[英]What is the most efficient way to match templates in a Numpy array?

我有一个大小为2000 * 4000的numpy数组,其中带有二进制值。 我有一个想要与源数组匹配的模板。 目前,我正在源数组上运行一个滑动窗口。 尽管此方法可以正常工作,但非常耗时。 我猜本机实现会快得多。 还可以匹配模板的多次出现吗?

就像是

x = [[0 0 1 1 1 1 1 0 0]
     [0 0 1 1 0 0 0 0 0]
     [0 0 1 1 0 0 0 0 0]
     [0 0 1 1 0 0 0 0 0]]

template = [[1 1 1 1]
            [1 0 0 0]
            [1 0 0 0]]

cords = np.matchtemplate(x, template)

理想情况下,打印线应该给出一个元组列表,该列表具有匹配段的对角坐标。

print(cords)

[[(0, 3), (6, 2)]]

正如@MPA所建议的那样,这将提供候选人列表:

from scipy import signal

match = np.sum(template)
tst = signal.convolve2d(x, template[::-1, ::-1], mode='valid') == match
candidates = np.argwhere(tst)

对于您的示例(0, 2)这给出了(0, 2)(0, 3)


对于二进制矩阵 ,可以按照@Paul的建议进行操作:

from scipy import signal

match = np.sum(template)
tst = signal.convolve2d(x, (2 * template - 1)[::-1, ::-1], mode='valid') == match
positions = np.argwhere(tst)

您的示例给出了(0, 3)

使用OpenCV的解决方案:

import cv2

result = cv2.matchTemplate(
    x.astype(np.float32),
    template.astype(np.float32),
    cv2.TM_SQDIFF)

positions = np.argwhere(result == 0.0)

您的示例给出了(0, 3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM