我正在使用Numpy研究图像处理,并面临使用卷积过滤的问题.
我想卷一个灰度图像.(使用较小的2d阵列卷积2d阵列)
有没有人有想法改进我的方法?
我知道scipy支持convolve2d,但我只想使用Numpy来创建一个convolve2d.
首先,我在子矩阵中制作了一个二维数组.
a = np.arange(25).reshape(5,5) # original matrix
submatrices = np.array([
[a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
[a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
[a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
Run Code Online (Sandbox Code Playgroud)
子矩阵似乎很复杂,但我正在做的事情如下图所示.
接下来,我将每个子矩阵乘以一个过滤器.
conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
Run Code Online (Sandbox Code Playgroud)
并总结了他们.
np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
#array([[ 6, 7, 8],
# [11, 12, 13],
# [16, 17, 18]])
Run Code Online (Sandbox Code Playgroud)
因此这种行为可以称为我的convolve2d.
def my_convolve2d(a, conv_filter):
submatrices = np.array([
[a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
[a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
[a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
return …Run Code Online (Sandbox Code Playgroud)