如何有效地计算偏移距离高斯图 numpy

How to calculate shifted distance gaussian map efficiently numpy

def build_gaussian_map(s, point, sigma=25):
    x, y = point[0], point[1]
    gmap = np.zeros(s)
    for row in range(s[0]):
        for col in range(s[1]):
            gmap[row][col] = 1 / (2 * np.pi * sigma * sigma) * np.exp(-((x - row) * (x - row) + (y - col) * (y - col)) / (2 * sigma * sigma))
    return gmap

s - 二维数组形状

point - 点坐标

我正在计算以图像的某个点为中心的距离高斯图point。我可以使用矩阵运算以某种方式做到这一点吗? 结果图示例:

def gaussian_map(shape, point, sigma=20):
    a = np.arange(shape[0])
    b = np.arange(shape[1])
    x_grid, y_grid = np.meshgrid(a, b)
    return 1 / (2 * np.pi * sigma * sigma) * np.exp(- ((x_grid - point[0]) * (x_grid - point[0]) + (y_grid - point[1]) * (y_grid - point[1])) / (2 * sigma * sigma))

想出了这个功能。好像有效果

import numpy as np

def build_gaussian_map(s, point, sigma=25):
    x, y = point[0], point[1]
    gmap = np.zeros(s)
    for row in range(s[0]):
        for col in range(s[1]):
            gmap[row][col] = 1 / (2 * np.pi * sigma * sigma) * np.exp(-((x - row) * (x - row) + (y - col) * (y - col)) / (2 * sigma * sigma))
    return gmap


def build_gaussian_map2(shape, point, sigma=25):
    x, y = point[0], point[1]
    row, col = np.indices(shape)
    gmap = 1 / (2 * np.pi * sigma * sigma) * np.exp(-((x - row) * (x - row) + (y - col) * (y - col)) / (2 * sigma * sigma))
    return gmap


def main():
    s = (1000, 1000)
    result1 = build_gaussian_map(s, (100, 100))
    result2 = build_gaussian_map2(s, (100, 100))
    assert np.all(result1 == result2)

main()

分析结果:

    24                                           def main():
    25         1          3.0      3.0      0.0      s = (1000, 1000)
    26         1    6126705.0 6126705.0     98.2      result1 = build_gaussian_map(s, (100, 100))
    27         1     105593.0 105593.0      1.7      result2 = build_gaussian_map2(s, (100, 100))