Python中是否有等效于MATLAB的conv2(h1,h2,A,'same')?
关于 conv2(A,B,'same')
这个函数,网上已经有一些答案了(比如这里: 在Python中进行类似于Matlab的2D卷积),但我找不到关于 conv2(h1,h2,A,'same')
的相关内容。
引用一下MATLAB的文档:
C = conv2(h1,h2,A) 这个操作是先用向量 h1 对矩阵 A 进行行卷积,然后再用向量 h2 对矩阵 A 进行列卷积。C 的大小是这样决定的:如果 n1 是 h1 的长度,n2 是 h2 的长度,那么 mc = max([ma+n1-1,ma,n1]),nc = max([na+n2-1,na,n2])。
有没有办法在Python(或者numpy、scipy等)中实现这种操作呢?
背景:
我想实现以下功能:
h1 = [ 0.05399097 0.24197072 0.39894228 0.24197072 0.05399097]
h2 = [ 0.10798193 0.24197072 -0. -0.24197072 -0.10798193]
A = img[:,:,1]
C = conv2(h1, h2, A, 'same')
其中 img 是一张 RGB 图像。
1 个回答
4
你可能想要的是这样的:
def conv2(v1, v2, m, mode='same'):
"""
Two-dimensional convolution of matrix m by vectors v1 and v2
First convolves each column of 'm' with the vector 'v1'
and then it convolves each row of the result with the vector 'v2'.
"""
tmp = np.apply_along_axis(np.convolve, 0, m, v1, mode)
return np.apply_along_axis(np.convolve, 1, tmp, v2, mode)
在 MATLAB的 conv2
文档 中应用这个例子:
A = np.zeros((10, 10))
A[2:8, 2:8] = 1
x = np.arange(A.shape[0])
y = np.arange(A.shape[1])
x, y = np.meshgrid(x, y)
u = [1, 0, -1]
v = [1, 2, 1]
Ch = conv2(u, v, A, 'same')
Cv = conv2(v, u, A, 'same')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.figure()
ax = plt.gca(projection='3d')
ax.plot_surface(x, y, Ch)
plt.figure()
ax = plt.gca(projection='3d')
ax.plot_surface(x, y, Cv)