The Wayback Machine - https://web.archive.org/web/20240828110613/https://www.geeksforgeeks.org/how-to-generate-2-d-gaussian-array-using-numpy/
Open In App

How to generate 2-D Gaussian array using NumPy?

Last Updated : 19 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, let us discuss how to generate a 2-D Gaussian array using NumPy. To create a 2 D Gaussian array using the Numpy python module.

Functions used:

  • numpy.meshgrid()– It is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing. 

Syntax:

numpy.meshgrid(*xi, copy=True, sparse=False, indexing=’xy’)
 

Syntax:

numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) 
 

  • numpy.exp()– this mathematical function helps the user to calculate the exponential of all the elements in the input array.

Syntax:

numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None)
 

Example 1:

Python3




# Importing Numpy package
import numpy as np
 
# sigma(standard deviation) and muu(mean) are the parameters of gaussian
 
 
def gaussuian_filter(kernel_size, sigma=1, muu=0):
 
    # Initializing value of x,y as grid of kernel size
    # in the range of kernel size
 
    x, y = np.meshgrid(np.linspace(-1, 1, kernel_size),
                       np.linspace(-1, 1, kernel_size))
    dst = np.sqrt(x**2+y**2)
 
    # lower normal part of gaussian
    normal = 1/(2, 0 * np.pi * sigma**2)
 
    # Calculating Gaussian filter
    gauss = np.exp(-((dst-muu)**2 / (2.0 * sigma**2))) * normal
 
 
kernel_size=5
gaussian = gaussian_filter(kernel_size)
print("gaussian filter of{} X {} :".format(kernel_size,kernel_size))
print(gaussian)


Output:

gaussian filter of5 X 5 :
[[0.00291502 0.01306423 0.02153928 0.01306423 0.00291502]
[0.01306423 0.05854983 0.09653235 0.05854983 0.01306423]
[0.02153928 0.09653235 0.15915494 0.09653235 0.02153928]
[0.01306423 0.05854983 0.09653235 0.05854983 0.01306423]
[0.00291502 0.01306423 0.02153928 0.01306423 0.00291502]]

Example 2:

Python3




# Importing Numpy package
import numpy as np
 
# sigma(standard deviation) and muu(mean) are the parameters of gaussian
 
 
def gaussuian_filter(kernel_size, sigma=1, muu=0):
 
    # Initializing value of x,y as grid of kernel size
    # in the range of kernel size
 
    x, y = np.meshgrid(np.linspace(-2, 2, kernel_size),
                       np.linspace(-2, 2, kernel_size))
    dst = np.sqrt(x**2+y**2)
 
    # lower normal part of gaussian
    normal = 1/(2, 0 * np.pi * sigma**2)
 
    # Calculating Gaussian filter
    gauss = np.exp(-((dst-muu)**2 / (2.0 * sigma**2))) * normal
 
 
kernel_size = 3
gaussian = gaussian_filter(kernel_size=3)
print("gaussian filter of{} X {} :".format(kernel_size, kernel_size))
print(gaussian)


Output:

gaussian filter of3 X 3 :
[[0.05854983 0.09653235 0.05854983]
[0.09653235 0.15915494 0.09653235]
[0.05854983 0.09653235 0.05854983]] 


Previous Article
Next Article

Similar Reads

Mahotas – Edges using Difference of Gaussian for binary image
In this article we will see how we can edges of the binary image in mahotas with the help of DoG algorithm. In imaging science, difference of Gaussians (DoG) is a feature enhancement algorithm that involves the subtraction of one blurred version of an original image from another, less blurred version of the original. In order to do this we will use
2 min read
Generate a Vandermonde Matrix of the Legendre Polynomial with Float Array of Points in Python using NumPy
In this article, we will be looking at the approach to generating a Vandermonde matrix of the Legendre polynomial with a float array of points in Python using NumPy. Example: Array: [-1.57 0.58 -3.57 1.44 2.75] Result: [[ 1.000000e+00 -1.570000e+00 3.197350e+00] [ 1.000000e+00 5.800000e-01 4.600000e-03] [ 1.000000e+00 -3.570000e+00 1.861735e+01] [
3 min read
Python - Inverse Gaussian Distribution in Statistics
scipy.stats.invgauss() is an inverted gauss continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : a : shape parameter c : special case of gengauss. Default equals to c = -1 Code #1 : Creating Inv
2 min read
Python - Normal Inverse Gaussian Distribution in Statistics
scipy.stats.norminvgauss() is a Normal Inverse Gaussian continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location parameter
2 min read
Python - Reciprocal Inverse Gaussian Distribution in Statistics
scipy.stats.recipinvgauss() is a reciprocal inverse Gaussian continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probability x : quantiles loc : [optional]location para
2 min read
Mahotas - Gaussian filtering
In this article we will see how we can do Gaussian filtering in mahotas. For this we are going to use the fluorescent microscopy image from a nuclear segmentation benchmark. We can get the image with the help of command given below mahotas.demos.nuclear_image() A Gaussian filter is a linear filter. It's usually used to blur the image or to reduce n
2 min read
Visualizing the Bivariate Gaussian Distribution in Python
The Gaussian distribution(or normal distribution) is one of the most fundamental probability distributions in nature. From its occurrence in daily life to its applications in statistical learning techniques, it is one of the most profound mathematical discoveries ever made. This article will ahead towards the multi-dimensional distribution and get
6 min read
Python - Gaussian fit
What is normal or Gaussian distribution? When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve, also called the Gaussian or normal distribution. It is named after the German mathematician Carl Friedrich Gauss. Some common e
4 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Generate five random numbers from the normal distribution using NumPy
In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distrib
2 min read
Generate a Vandermonde matrix of the Legendre series in Python using NumPy
In this article, we will be looking toward the approach to generating a Vandermonde matrix of the Legendre series in Python using NumPy. Example: Array: [-1 2 -3 4 -5] Result: [[ 1. -1. 1. ] [ 1. 2. 5.5] [ 1. -3. 13. ] [ 1. 4. 23.5] [ 1. -5. 37. ]]NumPy.legvander() To generate a pseudo Vandermonde matrix of the Legendre polynomial with an array, th
3 min read
Generate a Vandermonde matrix of given degree using NumPy in Python
In this article, we will cover generating a Vandermonde matrix of a given degree in Python using NumPy. In algebra, a Vandermonde matrix is an m*n matrix that has the terms of a geometric progression in each row. The matrix generated will be of the form : [1 x11 x12 ........ x1(n-1) ................... ................... 1 xm1 xm2 ........ xm(n-1)
3 min read
Generate Chebyshev series with given complex roots using NumPy in Python
In this article, we will cover how to generate the Chebyshev series with given complex roots in Python using NumPy. Example Input: (4+5j) Output: [9.5-40.j 0. +0.j 0.5 +0.j] Explanation: An array of Chebyshev series.chebyshev.chebfromroots() method In python, the Chebyshev module provides many functions like chebfromroots to perform arithmetic, and
2 min read
Generate a Pseudo Vandermonde matrix of the Hermite_e polynomial using NumPy in Python
In this article, we will be generating a Pseudo Vandermonde matrix of the Hermite_e polynomial using NumPy in Python. Example 1: Generating a Pseudo Vandermonde matrix using hermite_e.hermevander() function We use the hermite_e.hermevander() function in the Numpy module of python to construct a Vandermonde matrix of the Hermite_e polynomial. The ps
4 min read
Generate a Hermite_e series with given roots using NumPy in Python
In this article, we will cover how to raise a Hermite_e series to power in Python using NumPy. hermite_e.hermefromroots() function We use the hermite_e.hermefromroots() function present in the NumPy module of python to construct a Hermite_e series with the given roots. A 1-D array of coefficients is returned by the following function. we will get a
2 min read
Generate Random Numbers From The Uniform Distribution using NumPy
Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. Syntax: numpy.random.uniform(low = 0.0, high = 1.0, size = None
1 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
NumPy ndarray.imag() Method | Get Imaginary Part in NumPy Array
The ndarray.imag() method returns the imaginary part of the complex number in the NumPy array. Note: Remember resulting data type for the imaginary value is 'float64'. Example C/C++ Code # import the important module in python import numpy as np # make an array with numpy gfg = np.array([1 + 2j, 2 + 3j]) # applying ndarray.imag() method geeks = np.
1 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
Generate a matrix product of two NumPy arrays
We can multiply two matrices with the function np.matmul(a,b). When we multiply two arrays of order (m*n) and (p*q ) in order to obtained matrix product then its output contains m rows and q columns where n is n==p is a necessary condition. Syntax: numpy.matmul(x1, x2, /, out=None, *, casting='same_kind', order='K', dtype=None, subok=True[, signatu
2 min read
Python | Numpy numpy.resize()
With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing. Parameters: new_shape : [tuple of ints, or n ints] Shape of resized array refcheck : [bool, optio
2 min read
Python | Numpy numpy.transpose()
With the help of Numpy numpy.transpose(), We can perform the simple function of transpose within one line by using numpy.transpose() method of Numpy. It can transpose the 2-D arrays on the other hand it has no effect on 1-D arrays. This method transpose the 2-D numpy array. Parameters: axes : [None, tuple of ints, or n ints] If anyone wants to pass
2 min read
Python | Numpy numpy.ndarray.__lt__()
With the help of numpy.ndarray.__lt__() method of Numpy, We can find that which element in an array is less than the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__lt__($self, value, /) Return: self<value Example #1 : In this example we can see that
1 min read
Python | Numpy numpy.ndarray.__gt__()
With the help of numpy.ndarray.__gt__() method of Numpy, We can find that which element in an array is greater then the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__gt__($self, value, /) Return: self>value Example #1 : In this example we can see th
1 min read
Python | Numpy numpy.ndarray.__le__()
With the help of numpy.ndarray.__le__() method of Numpy, We can find that which element in an array is less than or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__le__($self, value, /) Return: self<=value Example #1 : In this example we
1 min read
Python | Numpy numpy.ndarray.__ge__()
With the help of numpy.ndarray.__ge__() method of Numpy, We can find that which element in an array is greater then or equal to the value which is provided in the parameter. It will return you numpy array with boolean type having only values True and False. Syntax: ndarray.__ge__($self, value, /) Return: self>=value Example #1 : In this example
1 min read
Practice Tags :