Python 是否有与MATLAB';s conv2函数?
Python或其任何模块是否具有与MATLAB功能等效的功能?更具体地说,我感兴趣的是与MATLAB中的conv2(A,B,'same')进行相同计算的东西Python 是否有与MATLAB';s conv2函数?,python,matlab,matrix,convolution,Python,Matlab,Matrix,Convolution,Python或其任何模块是否具有与MATLAB功能等效的功能?更具体地说,我感兴趣的是与MATLAB中的conv2(A,B,'same')进行相同计算的东西 scipy.ndimage.convolve 在n维中执行此操作。看起来就像是您正在寻找的。您必须为每个非单态维度提供一个偏移量,以重现Matlab的conv2结果。只支持“相同”选项的简单实现可以这样做 import numpy as np from scipy.ndimage.filters import convolve def
scipy.ndimage.convolve
在n维中执行此操作。看起来就像是您正在寻找的。您必须为每个非单态维度提供一个偏移量,以重现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
将numpy导入为np
从scipy.ndimage.filters导入卷积
def conv2(x,y,mode='same'):
"""
模拟Mathworks中的函数conv2。
用法:
z=conv2(x,y,mode='same')
待办事项:
-支持除“相同”以外的其他模式(参见conv2.m)
"""
如果不是(模式=‘相同’):
引发异常(“不支持模式”)
#添加单个维度
如果(len(x.shape)1和
y、 形状[i]>1):
原点=原点+(-1,)
其他:
原点=原点+(0,)
z=卷积(x,y,模式=常数,原点=原点)
返回z
虽然其他答案已经提到了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)
@aaa鲤鱼-没问题!无论如何,当使用
相同的
模式时,我认为它们实际上并不相同。SciPy中心与Matlab不同。Matlab说“如果有奇数行或奇数列,“中心”在开始处比结束处多留一行。”SciPy似乎做了相反的事情。SciPy.signal.convolve
?