我正在寻找最快的方法来计算从图像中某个原点到每个其他点的距离。现在,我所拥有的是这样的:
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])
有没有更快的方法?我看到了this answer,但不确定如何应用。
最佳答案
让我们来玩一些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