关于conv2(A,B,'same')
函数已经有了一些答案(例如,这里:2D Convolution in Python similar to Matlab's conv2),但是我找不到关于conv2(h1,h2,A,'same')
的任何信息。
引用MATLAB文档:
C = conv2(h1,h2,A)首先将A与向量h1沿行进行卷积,然后对向量h2沿列进行卷积。 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图片。
最佳答案
您可能想要类似:
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's documentation of
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)