Evaluate the probability density of Gaussian distribution on a square grid

3.4k Views Asked by At

I need to generate an image mask of dimensions m × n corresponding to a two-dimensional Gaussian with center at µ = (i, j) and σ^2 = 25, using NumPy.

After searching on the net, I found this documentation which looks promising. However, there are a few problems:

  • Generated matrix is not a mask (binary)
  • Covariance (σ^2) is given as a matrix and not as an integer

Perhaps using some mathematical properties, this could be transformed into what I want, but I can't see it because I'm not really good at maths.

1

There are 1 best solutions below

5
On BEST ANSWER

numpy.random.multivariate_normal will give you samples drawn from a multivariate Gaussian distribution with mean 0 and variance 1. You want to compute the probability density function (PDF) for this distribution, not draw samples from it.

The easiest thing to do is use the scipy.stats.multivariate_normal.pdf function, as follows:

m, n = 100, 100
lims = (-3, 3) # support of the PDF
xx, yy = np.meshgrid(np.linspace(*lims, m), np.linspace(*lims, n))
points = np.stack((xx, yy), axis=-1)
mean = (1, 2) # Whatever your (i, j) is
covariance = 25.0
pdf = scipy.stats.multivariate_normal.pdf(points, mean, covariance)

pdf now gives the height of the Gaussian function at each of the points in the plane between -3 and 3 on both the x- and y-axes.

You can apply this window to whatever images you want, by just doing image * pdf.

EDITS:

Thanks to CrazyIvan for pointing out the pdf function takes a grid of points directly. Also note that np.linspace(*lims, m) uses Python3-specific tuple-unpacking. If you have an older version, just do np.linspace(lims[0], lims[1], m).