Skip to main content
 首页 » 编程设计

python之numpy.convolve 中的形状不匹配

2025年05月04日6yjmyzz

错误信息:

operands could not be broadcast together with shapes (603) (613) 

我该怎么办?
两个列表的长度是否需要相同?
或者我应该用零填充它吗?

这是我的代码:

def gaussian_smooth1(img, sigma):  
    ''' 
    Do gaussian smoothing with sigma. 
    Returns the smoothed image. 
    ''' 
    result = np.zeros_like(img) 
 
    #get the filter 
    filter = gaussian_filter(sigma) 
 
    #get the height and width of img 
    width = len(img[0]) 
    height = len(img) 
 
    #smooth every color-channel 
    for c in range(3): 
        #smooth the 2D image img[:,:,c] 
        #tip: make use of numpy.convolve 
        for x in range(height): 
            result[x,:,c] = np.convolve(filter,img[x,:,c]) 
        for y in range(width): 
            result[:,y,c] = np.convolve(filter,img[:,y,c]) 
    return result 

请您参考如下方法:

问题的出现是因为你没有指定正确的mode。
在文档中阅读它:
numpy.convolve

numpy.convolve 的默认值是 mode='full'。

This returns the convolution at each point of overlap, with an output shape of (N+M-1,).

N 是输入数组的大小,M 是过滤器的大小。所以输出大于输入。

相反,您想使用 np.convolve(filter,img[...],mode='same')。

也看看 scipy.convolve允许使用 FFT 进行二维卷积。