# How to calculate a Gaussian kernel matrix efficiently in numpy?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to calculate a Gaussian kernel matrix efficiently in numpy in Python. So Here I am Explain to you all the possible Methods here.

## How to calculate a Gaussian kernel matrix efficiently in numpy?

1. How to calculate a Gaussian kernel matrix efficiently in numpy?

I myself used the accepted answer for my image processing, but I find it (and the other answers) too dependent on other modules.

2. calculate a Gaussian kernel matrix efficiently in numpy

I myself used the accepted answer for my image processing, but I find it (and the other answers) too dependent on other modules.

## Method 1

I myself used the accepted answer for my image processing, but I find it (and the other answers) too dependent on other modules. Therefore, here is my compact solution:

```import numpy as np

def gkern(l=5, sig=1.):
"""\
creates gaussian kernel with side length `l` and a sigma of `sig`
"""
ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)
gauss = np.exp(-0.5 * np.square(ax) / np.square(sig))
kernel = np.outer(gauss, gauss)
return kernel / np.sum(kernel)
```

Edit: Changed arange to linspace to handle even side lengths

## Method 2

You may simply gaussian-filter a simple 2D dirac function, the result is then the filter function that was being used:

```import numpy as np
import scipy.ndimage.filters as fi

def gkern2(kernlen=21, nsig=3):
"""Returns a 2D Gaussian kernel array."""

# create nxn zeros
inp = np.zeros((kernlen, kernlen))
# set element at the middle to one, a dirac delta
inp[kernlen//2, kernlen//2] = 1
# gaussian-smooth the dirac, resulting in a gaussian filter mask
return fi.gaussian_filter(inp, nsig)```

## Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.