I found scipy.signal.fftconvolve
, 正如马格努斯也指出的那样 https://stackoverflow.com/a/1477259/125507,但当时并没有意识到这是n-维度。由于它是内置的并产生正确的值,因此它似乎是理想的解决方案。
From 2D 卷积示例 http://www.songho.ca/dsp/convolution/convolution2d_example.html:
In [1]: a = asarray([[ 1, 2, 3],
...: [ 4, 5, 6],
...: [ 7, 8, 9]])
In [2]: b = asarray([[-1,-2,-1],
...: [ 0, 0, 0],
...: [ 1, 2, 1]])
In [3]: scipy.signal.fftconvolve(a, b, mode = 'same')
Out[3]:
array([[-13., -20., -17.],
[-18., -24., -18.],
[ 13., 20., 17.]])
正确的!另一方面,STSCI 版本需要一些额外的工作才能使边界正确?
In [4]: stsci.convolve2d(a, b, fft = True)
Out[4]:
array([[-12., -12., -12.],
[-24., -24., -24.],
[-12., -12., -12.]])
(STSCI方法也需要编译,我没有成功(我只是注释掉了非python部分),有一些错误,例如this http://projects.scipy.org/scipy/ticket/973并修改输入([1, 2] 变为 [[1, 2]])等。所以我将我接受的答案更改为内置fftconvolve()
功能。)
当然,相关性与卷积是一样的,只是一个输入相反:
In [5]: a
Out[5]:
array([[3, 0, 0],
[2, 0, 0],
[1, 0, 0]])
In [6]: b
Out[6]:
array([[3, 2, 1],
[0, 0, 0],
[0, 0, 0]])
In [7]: scipy.signal.fftconvolve(a, b[::-1, ::-1])
Out[7]:
array([[ 0., -0., 0., 0., 0.],
[ 0., -0., 0., 0., 0.],
[ 3., 6., 9., 0., 0.],
[ 2., 4., 6., 0., 0.],
[ 1., 2., 3., 0., 0.]])
In [8]: scipy.signal.correlate2d(a, b)
Out[8]:
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 6, 9, 0, 0],
[2, 4, 6, 0, 0],
[1, 2, 3, 0, 0]])
and 最新修订版 http://projects.scipy.org/scipy/browser/trunk/scipy/signal/signaltools.py?rev=5968通过在内部使用二次方尺寸来加速(然后我通过以下方式加快了它的速度)使用真实 FFT 进行真实输入 https://github.com/scipy/scipy/pull/337 and 使用 5 平滑长度代替 2 的幂 https://github.com/scipy/scipy/pull/3144 :D ).