How to generate 2D gaussian with Python?

后端 未结 6 894
囚心锁ツ
囚心锁ツ 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:07

    I'd like to add an approximation using exponential functions. This directly generates a 2d matrix which contains a movable, symmetric 2d gaussian.

    I should note that I found this code on the scipy mailing list archives and modified it a little.

    import numpy as np
    
    def makeGaussian(size, fwhm = 3, center=None):
        """ Make a square gaussian kernel.
    
        size is the length of a side of the square
        fwhm is full-width-half-maximum, which
        can be thought of as an effective radius.
        """
    
        x = np.arange(0, size, 1, float)
        y = x[:,np.newaxis]
    
        if center is None:
            x0 = y0 = size // 2
        else:
            x0 = center[0]
            y0 = center[1]
    
        return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / fwhm**2)
    

    For reference and enhancements, it is hosted as a gist here. Pull requests welcome!

提交回复
热议问题