python - 如何在 python 中平滑具有不同高斯函数的二维数组的元素?

标签 python arrays smoothing

如何平滑数组的 x[1,3] 和 x[3,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的二维高斯函数?本质上,我需要一个函数,它允许我使用不同宽度的高斯平滑单个“点状”数组元素,这样我就可以得到一个具有平滑变化值的数组。

最佳答案

我对你提出的问题和你发表的评论有点困惑。在我看来,您想使用 scipy.ndimage.filters.gaussian_filter但我不明白你的意思:

[...] gaussian functions with different sigma values to each pixel. [...]

事实上,由于您使用二维数组 x,因此高斯滤波器将具有 2 个参数。规则是:每个维度一个 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")

这是初始数组:

enter image description here

以下是 sigma_xsigma_y 不同值的一些结果:

enter image description here

enter image description here

enter image description here

enter image description here

这允许正确考虑 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")

以及对应的结果:

enter image description here

希望对您有所帮助。

关于python - 如何在 python 中平滑具有不同高斯函数的二维数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548639/

相关文章:

Python Launcher 没有响应 Pygame

python - 字典顺序导致输入结果改变?

ios - indexPath.row 没有从数组中获取数据

javascript - 将字符串连接到数组的每个对象

nlp - 愚蠢的退避实现说明

iphone - 在 opengl 中平滑不起作用

python - 如何删除重复条目但保留第一行选定列值和最后一行选定列值?

java - 二元运算符编译错误的错误操作数类型

python-3.x - 我应该如何使用单变量样条曲线来拟合特定形状的数据?

python - 如何找到两个 Django 查询集的联合?