How to generate 2D gaussian with Python?

后端 未结 6 896
囚心锁ツ
囚心锁ツ 2020-12-24 06:42

I can generate Gaussian data with random.gauss(mu, sigma) function, but how can I generate 2D gaussian? Is there any function like that?

6条回答
  •  [愿得一人]
    2020-12-24 07:32

    import numpy as np
    
    # define normalized 2D gaussian
    def gaus2d(x=0, y=0, mx=0, my=0, sx=1, sy=1):
        return 1. / (2. * np.pi * sx * sy) * np.exp(-((x - mx)**2. / (2. * sx**2.) + (y - my)**2. / (2. * sy**2.)))
    
    x = np.linspace(-5, 5)
    y = np.linspace(-5, 5)
    x, y = np.meshgrid(x, y) # get 2D variables instead of 1D
    z = gaus2d(x, y)
    

    Straightforward implementation and example of the 2D Gaussian function. Here sx and sy are the spreads in x and y direction, mx and my are the center coordinates.

提交回复
热议问题