【问题标题】:Efficient numpy euclidean distance calculation for each element每个元素的高效 numpy 欧几里得距离计算
【发布时间】:2021-09-15 02:10:23
【问题描述】:

我有一个形状为 512x512 的 numpy 数组和这个范围内的中心点。现在我想用中心点到数组元素的欧几里德距离填充数组。

例如:Center=[10,10] -> array[0,0]=sqrt((0-10)^2+(0-10)^2)...

我已经有了工作代码:

def calc_euclidean_distance(center, point):
   return np.sqrt((center[0] - point[0]) ** 2 + (center[1] - point[1]) ** 2)

target = np.zeros([512, 512])
center = np.array([10, 376]) #example

for iterrow, row in enumerate(target):
   for itercol, i in enumerate(row):
      target[iterrow, itercol] = self.calc_euclidean_distance(center, [iterrow, itercol])

但这真的很慢,也可能非常“非pythonic”。我想不出更好的方法,现在要求接受教育。

【问题讨论】:

    标签: python arrays numpy matrix


    【解决方案1】:

    我相信这可以满足您的要求:

    w, h = (512, 512)
    cx, cy = (10, 376)
    xcoords, ycoords = np.meshgrid(np.arange(w), np.arange(h))
    target = np.sqrt((xcoords - cx)**2 + (ycoords - cy)**2)
    

    【讨论】:

    • 效果很好,并且(显然)是一个很好的加速。不知道 np.meshgrid。很有帮助,谢谢
    猜你喜欢
    • 2015-09-23
    • 2010-11-26
    • 2014-05-08
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多