Python或其任何模块是否有类似于MATLAB的conv2函数的等效函数?更具体地说,我对能够执行与MATLAB中conv2(A, B, 'same')
相同计算的内容感兴趣。
Python或其任何模块是否有类似于MATLAB的conv2函数的等效函数?更具体地说,我对能够执行与MATLAB中conv2(A, B, 'same')
相同计算的内容感兴趣。
虽然其他答案已经提到了scipy.signal.convolve2d
作为等效方法,但我发现当使用mode='same'
时结果确实不同。
虽然Matlab的conv2
在图像底部和右侧会产生伪影,scipy.signal.convolve2d
在图像顶部和左侧也会产生相同的伪影。
请参见这些链接以查看行为的细节(没有足够的声望直接发布图片):
以下包装器可能效率不是很高,但通过将输入数组和输出数组都旋转180度来解决我的问题:
import numpy as np
from scipy.signal import convolve2d
def conv2(x, y, mode='same'):
return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2)
看起来你需要的是 scipy.signal.convolve2d。
为了重现Matlab的conv2结果,您必须为每个非单例维度提供一个偏移量。可以像这样制作仅支持“same”选项的简单实现:
import numpy as np
from scipy.ndimage.filters import convolve
def conv2(x,y,mode='same'):
"""
Emulate the function conv2 from Mathworks.
Usage:
z = conv2(x,y,mode='same')
TODO:
- Support other modes than 'same' (see conv2.m)
"""
if not(mode == 'same'):
raise Exception("Mode not supported")
# Add singleton dimensions
if (len(x.shape) < len(y.shape)):
dim = x.shape
for i in range(len(x.shape),len(y.shape)):
dim = (1,) + dim
x = x.reshape(dim)
elif (len(y.shape) < len(x.shape)):
dim = y.shape
for i in range(len(y.shape),len(x.shape)):
dim = (1,) + dim
y = y.reshape(dim)
origin = ()
# Apparently, the origin must be set in a special way to reproduce
# the results of scipy.signal.convolve and Matlab
for i in range(len(x.shape)):
if ( (x.shape[i] - y.shape[i]) % 2 == 0 and
x.shape[i] > 1 and
y.shape[i] > 1):
origin = origin + (-1,)
else:
origin = origin + (0,)
z = convolve(x,y, mode='constant', origin=origin)
return z
scipy.ndimage.convolve
它是否在n维度中实现。
scipy.signal.convolve
也是这样吗? - endolith