尝试使用numpy实现2d图像卷积抛出ValueError:操作数无法一起广播

2024-06-25 22:43:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现自己的算法,用特定的过滤器对图像进行卷积,并从thispost获得一些帮助。到目前为止,我所拥有的:

我的numpy图像与形状(510,510)

imageInArray = np.asarray(gray_image)
print(imageInArray.shape)

## it prints this
(512, 512)

我的卷积滤波器:

conv_filter = np.array([[0,1,0],[1,-4,1],[0,1,0]])
print(conv_filter.shape)
##prints this:
(3, 3)

然后根据过滤器内核大小将图像拆分为子矩阵,如下所示:

### split image in submatrices
def getsubmatrices(imgArray, partitioning_shape):
    view_shape = tuple(np.subtract(imgArray.shape, partitioning_shape) + 1) + partitioning_shape
    strides = imgArray.strides + imgArray.strides
    sub_matrices = np.lib.stride_tricks.as_strided(imgArray,view_shape,strides)    
    return sub_matrices

imgSubMatrices = getsubmatrices(imageInArray, conv_filter.shape)
print(imgSubMatrices.shape)
##prints an array of size (510, 510, 3, 3)

但是当我使用numpy的einsum方法将子矩阵与如下过滤器相乘时:

multiplied_subs = np.einsum('ij,ijkl>ijkl',conv_filter,imgSubMatrices)

我得到以下错误:

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,3)->(3,3,newaxis,newaxis) (510,510,3,3)->(510,510,3,3)
    

有人能帮我理解为什么这不起作用吗?既然我已经拆分了我的矩阵是3x3的子矩阵,那么使用einsum方法应该不会有问题,对吧?我真的很感激你能提供的任何帮助,因为我从几个小时以来一直在努力了解到底出了什么问题


Tags: 图像过滤器np矩阵filterprintsprintshape