使用numpy在2d数组中查找模式



我有一个由1和0组成的数组a。例如:

a= 
[[0,0,1,1,1,0],
[0,0,0,0,0,0],
[1,0,0,0,0,1],
[0,0,0,0,1,0],
[0,0,0,1,0,0],
[0,0,1,0,0,1]]

和一个内核(k):

k =
[[0,0,1]
[0,1,0]
[1,0,0]]

我想找到a中k的所有实例。我想要卷积的结果是:

conv(a,k) = 
[[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,1,0],
[0,0,0,1,0,0],
[0,0,0,0,0,0]]

是否有一个内置的功能?

我知道它可以用for循环来完成,但是这对于大数组来说太慢了。Thx

可以使用numpy.fft应用卷积

代码来自:https://laurentperrinet.github.io/sciblog/posts/2017-09-20-the-fastest-2d-convolution-in-the-world.html#using-directly-numpy

from numpy.fft  import fft2, ifft2
def np_fftconvolve(A, B):
return np.real(ifft2(fft2(A)*fft2(B, s=A.shape)))