Python 或其任何模块是否具有等效于 MATLAB 的conv2函数?更具体地说,我对conv2(A, B, 'same')
在 MATLAB 中进行相同计算的东西感兴趣。
问问题
12808 次
4 回答
9
虽然其他答案已经提到scipy.signal.convolve2d
作为等价物,但我发现使用mode='same'
.
虽然 Matlabconv2
会在图像的底部和右侧产生伪影,但在图像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)
于 2016-07-13T15:27:15.583 回答
5
Looks like scipy.signal.convolve2d is what you're looking for.
于 2010-09-16T23:25:30.390 回答
1
scipy.ndimage.convolve
does it in n dimensions.
于 2010-09-16T21:55:38.327 回答
1
您必须为每个非单一维度提供偏移量才能重现 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
于 2015-10-14T12:38:07.150 回答