本文介绍了2D高斯函数无法产生正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个返回大小为nx x nynp.array的函数,该函数包含均值mu和sd sig的居中高斯分布.下面的代码在某些情况下可以工作,但在许多情况下却无法工作-什么地方出了问题或应该写些什么来得到我所需要的?

I would like to write a function that returns an np.array of size nx x ny that contains a centered gaussian distribution with mean mu and sd sig. The code below works in certain cases but in many not - what's wrong or what else should I write to get what I need?

import matplotlib.pyplot as plt
import numpy as np

def create2dGaussian(mu, sigma, nx, ny):
    x, y = np.meshgrid(np.linspace(-nx / 2.0, +nx / 2.0, nx), np.linspace(-ny / 2.0, +ny / 2.0, ny))
    d = np.sqrt(x * x + y * y)
    g = np.exp(-((d - mu) ** 2 / (2.0 * sigma ** 2)))

    # just for debugging:
    np.set_printoptions(precision=1, suppress=True)
    print(g.shape)
    print(g)
    plt.imshow(g, cmap='jet', interpolation='nearest')
    plt.colorbar()
    plt.show()

    return g

以下是一些带有注释的测试用例:

Here are some test cases with comments:

from create2dGaussian import create2dGaussian

create2dGaussian(1, 10, 25, 25) # seems to work
create2dGaussian(1, 5, 25, 25) # the middle is not quite the peak anymore
create2dGaussian(1, 1, 25, 25) # the above problem more clearly visible
create2dGaussian(1, 1, 5, 5) # here it is extrem as the middle is now only 0.6

create2dGaussian(5, 10, 25, 25) # mean is still 1 and not 5

推荐答案

在您的建议中,均值与混淆.在一维情况下,说它居中就是在说它的均值是0.对于2D高斯,可以说有两种均值,定义为对xy的期望.再次说它居中就是说他们都是0.

There is a confusion with the mean in what you propose. In the 1D case, saying it is centered is exactly saying its mean is 0. For a 2D gaussian there are so to speak two means, defined as the expectation of x and of y. Again saying it is centered is exactly saying they are both 0.

总而言之,您的密度不是居中的2D高斯密度,应为

To summarize, your density is not the density of a centered 2D gaussian, which should be

exp(-((x**2 +y**2) / (2.0 * sigma ** 2)))

如果高斯位于(xm, ym)的中心,则密度为

If the gaussian is centered at (xm, ym) then the density is

exp(-(((x-xm)**2 +(y-ym)**2) / (2.0 * sigma ** 2)))

但是,没有像中心均值的高斯那样具有均值mu的东西.

But there is no such thing as a centered gaussian with mean mu.

这篇关于2D高斯函数无法产生正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 05:34