该脚本非常适用于平滑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()
标签:smoothing,convolution,python,numpy,scipy
来源: https://codeday.me/bug/20190727/1557872.html