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

2024-10-06 11:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 函数元素宽度np数组array本质点状
1条回答
网友
1楼 · 发布于 2024-10-06 11:26:09

我对你提出的问题和你发表的评论有点困惑。在我看来,你似乎想使用^{},但我不明白你的意思是什么:

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

实际上,由于使用二维数组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")

以下是初始数组:

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

我希望这对你有帮助。

相关问题 更多 >