如何用NumPy生成二维高斯阵列

如何用NumPy生成二维高斯阵列

在这篇文章中,让我们讨论如何使用NumPy生成一个二维高斯数组。使用Numpy python模块创建一个二维高斯数组。

使用的函数:

  • numpy.Meshgrid() – 它用于在两个给定的一维数组中创建一个矩形网格,代表笛卡尔索引或矩阵索引。

语法:

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

  • numpy.linspace() – 均匀地返回数字空间(w.r.t interval)。

语法:

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

  • numpy.exp() – 这个数学函数帮助用户计算输入数组中所有元素的指数。

语法:

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

示例 1:

# 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)

输出:

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]]

示例 2:

# 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)

输出:

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程