如何用Python生成2D高斯?

时间:2011-10-07 13:05:27

标签: python gaussian

我可以用random.gauss(mu, sigma)函数生成高斯数据,但是如何生成2D高斯?有没有这样的功能?

6 个答案:

答案 0 :(得分:44)

如果您可以使用numpy,则有numpy.random.multivariate_normal(mean, cov[, size])

例如,要获得10,000个2D样本:

np.random.multivariate_normal(mean, cov, 10000)

其中mean.shape==(2,)cov.shape==(2,2)

答案 1 :(得分:15)

由于标准的二维高斯分布只是两个1D高斯分布的乘积,如果两个轴之间没有相关性(即协变矩阵是对角线),只需调用{{1}两次。

random.gauss

答案 2 :(得分:13)

我想使用指数函数添加近似值。这直接生成2d矩阵,其包含可移动的对称2d高斯。

我应该注意到,我在scipy邮件列表档案中找到了这个代码并对其进行了一些修改。

import numpy as np

def makeGaussian(size, fwhm = 3, center=None):
    """ Make a square gaussian kernel.

    size is the length of a side of the square
    fwhm is full-width-half-maximum, which
    can be thought of as an effective radius.
    """

    x = np.arange(0, size, 1, float)
    y = x[:,np.newaxis]

    if center is None:
        x0 = y0 = size // 2
    else:
        x0 = center[0]
        y0 = center[1]

    return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)

作为参考和增强功能,它作为主旨here托管。拉请求欢迎!

答案 3 :(得分:0)

import numpy as np

# define normalized 2D gaussian
def gaus2d(x=0, y=0, mx=0, my=0, sx=1, sy=1):
    return 1. / (2. * np.pi * sx * sy) * np.exp(-((x - mx)**2. / (2. * sx**2.) + (y - my)**2. / (2. * sy**2.)))

x = np.linspace(-5, 5)
y = np.linspace(-5, 5)
x, y = np.meshgrid(x, y) # get 2D variables instead of 1D
z = gaus2d(x, y)

2D Gaussian function的简单实现和示例。这里sx和sy是在x和y方向上的扩展,mx和my是中心坐标。

答案 4 :(得分:0)

我们可以尝试仅使用numpy方法np.random.normal来生成2D高斯分布。 示例代码为np.random.normal(mean, sigma, (num_samples, 2))

通过均值= 0和sigma 20得出的样本如下所示:

np.random.normal(0, 20, (10,2))

>>array([[ 11.62158316,   3.30702215],
   [-18.49936277, -11.23592946],
   [ -7.54555371,  14.42238838],
   [-14.61531423,  -9.2881661 ],
   [-30.36890026,  -6.2562164 ],
   [-27.77763286, -23.56723819],
   [-18.18876597,  41.83504042],
   [-23.62068377,  21.10615509],
   [ 15.48830184, -15.42140269],
   [ 19.91510876,  26.88563983]])

因此,我们在2d数组中得到10个样本,均值= 0,sigma = 20

答案 5 :(得分:0)

如果有人找到这个线程并且正在寻找更通用的东西(就像我一样),我已经修改了@giessel 的代码。下面的代码将允许不对称和旋转。

import numpy as np

def makeGaussian2(x_center=0, y_center=0, theta=0, sigma_x = 10, sigma_y=10, x_size=640, y_size=480):
    # x_center and y_center will be the center of the gaussian, theta will be the rotation angle
    # sigma_x and sigma_y will be the stdevs in the x and y axis before rotation
    # x_size and y_size give the size of the frame 

    theta = 2*np.pi*theta/360
    x = np.arange(0,x_size, 1, float)
    y = np.arange(0,y_size, 1, float)
    y = y[:,np.newaxis]
    sx = sigma_x
    sy = sigma_y
    x0 = x_center
    y0 = y_center

    # rotation
    a=np.cos(theta)*x -np.sin(theta)*y
    b=np.sin(theta)*x +np.cos(theta)*y
    a0=np.cos(theta)*x0 -np.sin(theta)*y0
    b0=np.sin(theta)*x0 +np.cos(theta)*y0

    return np.exp(-(((a-a0)**2)/(2*(sx**2)) + ((b-b0)**2) /(2*(sy**2))))