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

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

我有一个大小为 2000*4000 的 numpy 数组,其中包含二进制值。我有一个模板,我想将其与我的源数组相匹配。目前我 运行 在源数组上滑动 window。这种方法虽然效果很好,但是非常耗时。我猜本机实现会快得多。它也可以匹配多次出现的模板吗?

类似

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, 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)