Do you want to use the Gaussian kernel, for example, to smooth images? If so, there is a gaussian_filter() function in scipy:
Updated Answer
This should work - although it is still not 100% accurate, it is trying to account for the mass of probability in each grid cell. I think that using the probability density at the midpoint of each cell is slightly less accurate, especially for small cores. See Example https://homepages.inf.ed.ac.uk/rbf/HIPR2/gsmooth.htm .
def gkern(kernlen=21, nsig=3): """Returns a 2D Gaussian kernel.""" x = np.linspace(-nsig, nsig, kernlen+1) kern1d = np.diff(st.norm.cdf(x)) kern2d = np.outer(kern1d, kern1d) return kern2d/kern2d.sum()
We test it using the example in Figure 3 at the link:
gkern(5, 2.5)*273
gives
array([[ 1.0278445 , 4.10018648, 6.49510362, 4.10018648, 1.0278445 ], [ 4.10018648, 16.35610171, 25.90969361, 16.35610171, 4.10018648], [ 6.49510362, 25.90969361, 41.0435344 , 25.90969361, 6.49510362], [ 4.10018648, 16.35610171, 25.90969361, 16.35610171, 4.10018648], [ 1.0278445 , 4.10018648, 6.49510362, 4.10018648, 1.0278445 ]])
The original (accepted) answer below is incorrect. The square root is not needed, and the interval definition is incorrect.
import numpy as np import scipy.stats as st def gkern(kernlen=21, nsig=3): """Returns a 2D Gaussian kernel array.""" interval = (2*nsig+1.)/(kernlen) x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1) kern1d = np.diff(st.norm.cdf(x)) kernel_raw = np.sqrt(np.outer(kern1d, kern1d)) kernel = kernel_raw/kernel_raw.sum() return kernel