How to calculate a Gaussian kernel matrix efficiently in numpy?

前端 未结 12 2166
名媛妹妹
名媛妹妹 2020-11-29 20:54
def GaussianMatrix(X,sigma):
    row,col=X.shape
    GassMatrix=np.zeros(shape=(row,row))
    X=np.asarray(X)
    i=0
    for v_i in X:
        j=0
        for v_j i         


        
12条回答
  •  有刺的猬
    2020-11-29 21:09

    I myself used the accepted answer for my image processing, but I find it (and the other answers) too dependent on other modules. Therefore, here is my compact solution:

    import numpy as np
    
    def gkern(l=5, sig=1.):
        """\
        creates gaussian kernel with side length l and a sigma of sig
        """
    
        ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)
        xx, yy = np.meshgrid(ax, ax)
    
        kernel = np.exp(-0.5 * (np.square(xx) + np.square(yy)) / np.square(sig))
    
        return kernel / np.sum(kernel)
    

    Edit: Changed arange to linspace to handle even side lengths

提交回复
热议问题