关于conv2(A,B,'same')
功能已有一些答案(例如:2D Convolution in Python similar to Matlab's conv2),但我无法找到有关conv2(h1,h2,A,'same')
的任何内容。
引用MATLAB文档:
C = conv2(h1,h2,A)首先沿着行将矢量h1与矢量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图像。
答案 0 :(得分:3)
您可能需要以下内容:
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)