如何平滑数组的x1,3和x3,2元素,
x = np.array([[0,0,0,0,0],[0,0,0,1,0],[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0]]) 用两个宽度分别为1和2的二维高斯函数?本质上,我需要一个函数,它允许我用不同宽度的高斯数组来平滑单个“类似点”的数组元素,这样我就可以得到一个值平滑变化的数组。
发布于 2015-11-09 19:42:19
我对你提出的问题和你发表的评论感到有点困惑。在我看来,你想使用scipy.ndimage.filters.gaussian_filter,但我不明白你说的是什么意思:
...每个像素具有不同sigma值的高斯函数。..。
实际上,由于您使用的是二维数组x,因此高斯滤波器将有两个参数。规则是:每个维度一个sigma值,而不是每个像素一个sigma值。
下面是一个简短的示例:
import matplotlib.pyplot as pl
import numpy as np
import scipy as sp
import scipy.ndimage
n = 200 # widht/height of the array
m = 1000 # number of points
sigma_y = 3.0
sigma_x = 2.0
# Create input array
x = np.zeros((n, n))
i = np.random.choice(range(0, n * n), size=m)
x[i / n, i % n] = 1.0
# Plot input array
pl.imshow(x, cmap='Blues', interpolation='nearest')
pl.xlabel("$x$")
pl.ylabel("$y$")
pl.savefig("array.png")
# Apply gaussian filter
sigma = [sigma_y, sigma_x]
y = sp.ndimage.filters.gaussian_filter(x, sigma, mode='constant')
# Display filtered array
pl.imshow(y, cmap='Blues', interpolation='nearest')
pl.xlabel("$x$")
pl.ylabel("$y$")
pl.title("$\sigma_x = " + str(sigma_x) + "\quad \sigma_y = " + str(sigma_y) + "$")
pl.savefig("smooth_array_" + str(sigma_x) + "_" + str(sigma_y) + ".png")以下是初始数组:

以下是sigma_x和sigma_y的不同值的一些结果




这允许正确地考虑scipy.ndimage.filters.gaussian_filter的第二个参数的影响。
然而,根据前面的引用,您可能更感兴趣的是为每个像素分配不同的权重。在本例中,scipy.ndimage.filters.convolve是您要查找的函数。下面是相应的示例:
import matplotlib.pyplot as pl
import numpy as np
import scipy as sp
import scipy.ndimage
# Arbitrary weights
weights = np.array([[0, 0, 1, 0, 0],
[0, 2, 4, 2, 0],
[1, 4, 8, 4, 1],
[0, 2, 4, 2, 0],
[0, 0, 1, 0, 0]],
dtype=np.float)
weights = weights / np.sum(weights[:])
y = sp.ndimage.filters.convolve(x, weights, mode='constant')
# Display filtered array
pl.imshow(y, cmap='Blues', interpolation='nearest')
pl.xlabel("$x$")
pl.ylabel("$y$")
pl.savefig("smooth_array.png")以及相应的结果:

我希望这能对你有所帮助。
https://stackoverflow.com/questions/33548639
复制相似问题