我試圖在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