【发布时间】:2010-09-16 21:49:10
【问题描述】:
Python 或其任何模块是否具有等效于 MATLAB 的 conv2 函数?更具体地说,我对在 MATLAB 中与 conv2(A, B, 'same') 进行相同计算的东西感兴趣。
【问题讨论】:
-
@aaa 鲤鱼 - 没问题!还是谢谢
标签: python matlab matrix convolution
Python 或其任何模块是否具有等效于 MATLAB 的 conv2 函数?更具体地说,我对在 MATLAB 中与 conv2(A, B, 'same') 进行相同计算的东西感兴趣。
【问题讨论】:
标签: python matlab matrix convolution
虽然其他答案已经提到 scipy.signal.convolve2d 作为等效项,但我发现使用 mode='same' 时结果确实不同。
虽然 Matlab 的 conv2 会在图像的底部和右侧产生伪影,但 scipy.signal.convolve2d 在图像的顶部和左侧有相同的伪影。
查看这些链接以了解显示行为的图表(没有足够的声誉直接发布图像):
Upper left corner of convoluted Barbara
Lower right corner of convoluted Barbara
以下包装器可能效率不高,但在我的情况下通过将输入数组和输出数组都旋转 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 就是您要查找的内容。
【讨论】:
same 模式时,我认为它们实际上并不相同。 SciPy 的中心与 Matlab 不同。 Matlab 说“如果有奇数的行或列,则“中心”在开头比结尾多留一个。 SciPy 似乎正好相反。
scipy.ndimage.convolve
在 n 个维度上进行。
【讨论】:
scipy.signal.convolve也是如此?
您必须为每个非单维提供偏移量才能重现 Matlab 的 conv2 的结果。仅支持“相同”选项的简单实现可以这样制作
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
【讨论】: