python – 仅沿一个轴平滑2D数组
发布时间:2020-12-20 11:44:34 所属栏目:Python 来源:网络整理
导读:我想知道是否有人可以帮助我将 the smoothing example in the SciPy cookbook扩展到2D问题. 该脚本非常适用于平滑1D功能,并且它们还为两个轴上的2D平滑提供代码(即模糊图像). 但是,我想将此函数应用于2D数据集,但仅沿一个轴(x方向).我可以循环执行此操作,方
我想知道是否有人可以帮助我将
the smoothing example in the SciPy cookbook扩展到2D问题.
该脚本非常适用于平滑1D功能,并且它们还为两个轴上的2D平滑提供代码(即模糊图像). 但是,我想将此函数应用于2D数据集,但仅沿一个轴(x方向).我可以循环执行此操作,方法是检查y中的每个切片,应用1D卷积,然后重建阵列.但这似乎是糟糕的编码技术. 因此,我想知道如何在2D中做到这一点?我想我需要制作一个2D内核,权重只沿一个方向变化,但我不知道该怎么做,或者使用哪个卷积函数(numpy.convolve,scipy.signal.convolve,scipy.ndimage.filters .convolve1d等) 解决方法
也许最简单的选择是使用
scipy.ndimage.filters 中的一个1D过滤器:
from scipy import ndimage from scipy.misc import lena img = lena() # a uniform (boxcar) filter with a width of 50 boxcar = ndimage.uniform_filter1d(img,50,1) # a Gaussian filter with a standard deviation of 10 gauss = ndimage.gaussian_filter1d(img,10,1) 你也可以使用这样的过滤器的非1D版本:ndimage.gaussian_filter(img,(0,10))(即,对于你不想平滑的轴,将过滤器宽度设置为0). 要使任意内核平滑,可以使用 import numpy as np kern = np.hanning(50) # a Hanning window with width 50 kern /= kern.sum() # normalize the kernel weights to sum to 1 hanning = ndimage.convolve1d(img,kern,1) 以下是各种输出的外观: from matplotlib import pyplot as plt fig,ax = plt.subplots(2,2,figsize=(8,8)) ax[0,0].imshow(img) ax[0,0].set_title('Original') ax[0,1].imshow(boxcar) ax[0,1].set_title('Boxcar filter (width = 50)') ax[1,0].imshow(gauss) ax[1,0].set_title(r'Gaussian filter ($sigma$= 10)') ax[1,1].imshow(hanning) ax[1,1].set_title(r'Hanning window (width = 50)') for aa in ax.flat: aa.set_axis_off() fig.tight_layout() plt.show() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |