Fastest computation of distances in rectangular array

时间:2015-09-14 15:50:40

标签: python performance numpy distance

I'm looking for the fastest way to compute a lot of distances from some origin in a an image to every other point. Right now, what I have is something like this:

origin = [some_val,some_other_val]
y,x = np.mgrid[:image.shape[0],:image.shape[1]].astype(float)    
r = np.hypot(y-origin[0],x-origin[1])

Is there a faster way? I saw this answer, but I'm not sure how to apply it.

2 个答案:

答案 0 :(得分:3)

让我们来一些broadcasting -

m,n= image.shape
r = np.sqrt((np.arange(m)[:,None]-origin[0])**2 + (np.arange(n)-origin[1])**2)

运行时测试并验证结果

定义函数 -

In [115]: def broadcasting_based(origin,image_shape):
     ...:     m,n= image_shape
     ...:     return np.sqrt((np.arange(m)[:,None]-origin[0])**2 + (np.arange(n)-origin[1])**2)
     ...: 
     ...: 
     ...: def original_approach(origin,image_shape):
     ...:     y,x = np.mgrid[:image_shape[0],:image_shape[1]].astype(float)    
     ...:     return np.hypot(y-origin[0],x-origin[1])
     ...: 

案例#1:

In [116]: origin = np.array([100,200])

In [117]: np.allclose(broadcasting_based(origin,[500,500]),original_approach(origin,[500,500]))
Out[117]: True

In [118]: %timeit broadcasting_based(origin,[500,500])
100 loops, best of 3: 3.28 ms per loop

In [119]: %timeit original_approach(origin,[500,500])
10 loops, best of 3: 21.2 ms per loop

案例#2:

In [123]: origin = np.array([1000,2000])

In [124]: np.allclose(broadcasting_based(origin,[5000,5000]),original_approach(origin,[5000,5000]))
Out[124]: True

In [125]: %timeit broadcasting_based(origin,[5000,5000])
1 loops, best of 3: 460 ms per loop

In [126]: %timeit original_approach(origin,[5000,5000])
1 loops, best of 3: 2.96 s per loop

答案 1 :(得分:2)

除了其他答案之外,你绝对应该回答你是否需要距离的问题,或者如果只用距离的平方来解决你的问题。例如。如果你想知道最近的那个,这可以用方块完美地完成。

这样可以为每个点对节省一个昂贵的平方根计算。