首页 > 解决方案 > 尝试使用 numpy 实现 2d 图像卷积会抛出 ValueError: 操作数不能一起广播

问题描述

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

我在 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)

但是当我使用einsumnumpy 的方法将子矩阵与过滤器相乘时,如下所示:

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方法应该不是问题,对吧?我真的很感激你能提供的任何帮助,因为几个小时以来我一直在试图了解问题所在

标签: pythonnumpyconvolutionnumpy-einsum

解决方案


推荐阅读