【图像处理】python生成二维isotropic(各向同性)、anisotropic(各向异性) 高斯核

Motivation

需要自己做个各向异性的高斯核来处理图像,查了下没有看到特别好的实现,于是自己动手写了一个。

代码

实现比较简单,生成高斯核的部分借鉴了外网的一篇博客。如果要产生一个椭圆形的分布(各向不同性),直接在对应的轴上做下采样就好了。设置了比较多的参数,注释解释的很详细,直接参考就好了。

import os
import numpy as np
from scipy import io as sio


def gaussian_2d(muu=0.0, sigma=1, start=-2, end=2, num=15, sf_x=1, sf_y=1, save=True, path=os.path.dirname(__file__), kname="kernel_default.mat"):
    """
    :param muu: Mean of gaussian.
    :param sigma: Standard deviation of gaussian.
    :param start: Start value for np.linespace().
    :param end: End value for np.linespace().
    :param num: Number of samples to generate. Default is 15. Must be non-negative.
    :param sf_x: Scale factor of downsampling to creat anisotropic gaussian.
    :param sf_y: Scale factor of downsampling to creat anisotropic gaussian.
    :param save: If True, save the kernel. Otherwise, not.
    :param path: Path to save dir "Kernels" and .mat file.
    :param kname: Name of generated kernel.
    :return: Generated kernel
    """
    x, y = np.meshgrid(np.linspace(start, end, num), np.linspace(start, end, num))
    dst = np.sqrt(x * x + y * y)
    # Calculating Gaussian array
    kernel = np.exp(-((dst - muu) ** 2 / (2.0 * sigma ** 2)))[::sf_x, ::sf_y]
    if save:
        if "Kernels" not in os.listdir(path):
            os.mkdir(os.path.join(path, "Kernels"))
        path = os.path.join(path, "Kernels")
        sio.savemat(os.path.join(path, kname), {"Kernel": kernel})

    return kernel

参考链接

生成高斯核的部分参考这篇博客:https://www.geeksforgeeks.org/how-to-generate-2-d-gaussian-array-using-numpy/

禁止私自转载

你可能感兴趣的:(图像处理,python,计算机视觉,深度学习)