How to calculate a Gaussian kernel matrix efficiently in numpy?

前端 未结 12 2283
名媛妹妹
名媛妹妹 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:03

    If you are a computer vision engineer and you need heatmap for a particular point as Gaussian distribution(especially for keypoint detection on image)

    def gaussian_heatmap(center = (2, 2), image_size = (10, 10), sig = 1):
        """
        It produces single gaussian at expected center
        :param center:  the mean position (X, Y) - where high value expected
        :param image_size: The total image size (width, height)
        :param sig: The sigma value
        :return:
        """
        x_axis = np.linspace(0, image_size[0]-1, image_size[0]) - center[0]
        y_axis = np.linspace(0, image_size[1]-1, image_size[1]) - center[1]
        xx, yy = np.meshgrid(x_axis, y_axis)
        kernel = np.exp(-0.5 * (np.square(xx) + np.square(yy)) / np.square(sig))
        return kernel
    

    The usage and output

    kernel = gaussian_heatmap(center = (2, 2), image_size = (10, 10), sig = 1)
    plt.imshow(kernel)
    print("max at :", np.unravel_index(kernel.argmax(), kernel.shape))
    print("kernel shape", kernel.shape)
    

    max at : (2, 2)

    kernel shape (10, 10)

    kernel = gaussian_heatmap(center = (25, 40), image_size = (100, 50), sig = 5)
    plt.imshow(kernel)
    print("max at :", np.unravel_index(kernel.argmax(), kernel.shape))
    print("kernel shape", kernel.shape)
    

    max at : (40, 25)

    kernel shape (50, 100)

提交回复
热议问题