我试图在Scipy/Numpy中创建一个二维数组,其中每个值代表距离中心的欧几里得距离。它应该具有与三维阵列的前两个维度相同的形状(图像,通过scipy.misc.fromimage创建)。创建一个二维Numpy阵列与中心的欧几里得距离
这里有一个办法,工作原理:
def get_distance_1(y, x):
mid_x, mid_y = (scipy.array(image_array.shape[:2]) - 1)/float(2)
return ((y - mid_y) ** 2 + (x - mid_x) ** 2) ** 0.5
distances = scipy.fromfunction(get_distance_1, image_array.shape[:2])
这种方法是相当快的,但我很新的SciPy的,并想知道是否有做同样的事情更优雅,习惯的方法。我发现这个功能似乎很有前途,但我对如何适应这个问题感到不知所措。
def get_distance_2(y, x):
mid = ... # needs to be a array of the shape (rows, cols, 2)?
return scipy.spatial.distance.cdist(scipy.dstack((y, x)), mid)
只是为了澄清,我正在寻找的是这样的(一个6×6阵列)
[[ 3.53553391 2.91547595 2.54950976 2.54950976 2.91547595 3.53553391]
[ 2.91547595 2.12132034 1.58113883 1.58113883 2.12132034 2.91547595]
[ 2.54950976 1.58113883 0.70710678 0.70710678 1.58113883 2.54950976]
[ 2.54950976 1.58113883 0.70710678 0.70710678 1.58113883 2.54950976]
[ 2.91547595 2.12132034 1.58113883 1.58113883 2.12132034 2.91547595]
[ 3.53553391 2.91547595 2.54950976 2.54950976 2.91547595 3.53553391]]
同时检查HTTP:/ /stackoverflow.com/questions/17527340/more-efficient-way-to-calculate-distance-in-numpy(当数组变得非常大时,计算距离的不同方法的效率会变化 - 内存开始变得重要,而且解决方案是f astest不是显而易见的) - 为了更加清晰,阅读所有关于问题和已接受答案的评论 – usethedeathstar 2014-09-25 09:46:47