![](/img/trans.png)
[英]Efficient way to calculate distance matrix given latitude and longitude data in Python
[英]Efficient way to calculate distance to value in matrix in python
我有一個圖像,想為每個非零值像素計算它到最近的零值像素的距離。 我嘗試這樣做的方式如下:
import numpy as np
from scipy.spatial.distance import cdist
from skimage import io
im=io.imread('imagepath')
#getting array where elements are 0
a,b = np.where(im == 0)
# create a list with (row,column)
x = list(zip(a, b))
#getting array where elements are non zero
r, c =np.where(im!=0)
#create a list with (row, column) of all non 0 values
#note coordinates are in y, x format
obj = list(zip(r,c))
dist_dict={}
#calculating for each pixel of the object
for o in obj:
d = (cdist(np.array([o]), x, metric='euclidean')).min()
dist_dict.update({o:d})
我相信這應該可行,但是速度很慢。 對於單個像素,計算距離大約需要 0.2 秒。 對於大約 50.000 像素大的物體,因此每張圖像需要大約三個小時的計算時間,這是根本不可行的。 我在這里看到的一個問題是我只是遍歷所有非零像素。 有沒有一種方法不是從數組的開頭而是從當前坐標開始搜索,直到找到零值? 或者還有其他建議可以加快這個過程嗎?
您可以使用scipy.ndimage.morphology.distance_transform_edt找到最近的背景點(值 0),歐氏距離最小到輸入像素。
from scipy import ndimage
import pprint
def nearest_zero(image):
" Finds closest background (zero) element for each element in image "
# Find closest zero elements in the inverted image (same as closest non-zero for image)
edt = ndimage.distance_transform_edt(image, return_indices=False)
# Create dictionary of indexes
return {(r,c):edt[r][c] for r in range(image.shape[0]) for c in range(image.shape[1]) if image[r][c]}
使用示例
image = np.array(([0,50,75,15,0],
[2,0,111,10,15],
[0,112,25,110,115],
[0,10,110,115,0],
[15,12,115,0,0]))
d = nearest_zero(image)
pp = pprint.PrettyPrinter(indent=4)
print('Original Image')
print(image)
print('\nDictionary of Distances to closest background pixel for each non-background pixel')
pp.pprint(sorted(d.items(), key=lambda x: x[0]))
輸出
Original Image
[[ 0 50 75 15 0]
[ 2 0 111 10 15]
[ 0 112 25 110 115]
[ 0 10 110 115 0]
[ 15 12 115 0 0]]
Dictionary of Distances to closest background pixel for each non-background pixel
[ ((0, 1), 1.0),
((0, 2), 1.4142135623730951),
((0, 3), 1.0),
((1, 0), 1.0),
((1, 2), 1.0),
((1, 3), 1.4142135623730951),
((1, 4), 1.0),
((2, 1), 1.0),
((2, 2), 1.4142135623730951),
((2, 3), 1.4142135623730951),
((2, 4), 1.0),
((3, 1), 1.0),
((3, 2), 1.4142135623730951),
((3, 3), 1.0),
((4, 0), 1.0),
((4, 1), 1.4142135623730951),
((4, 2), 1.0)]
性能測試
結果:SciPy 快了約 100 倍
測試數據生成——隨機圖像(大小 250x250 = 62、500 像素)
import random
size = 250
z = [random.randrange(0, 255) for r in range(size) for c in range(size)]
image = np.array(z).reshape(size, size)
測試圖像中的數字零
print(np.count_nonzero(image==0)) # 62262
timeit 使用原始帖子中的方法
11.6 s ± 89.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
which is an average of 1.8e-04 seconds per non-zero point
timeit 使用 SciPy 方法
119 ms ± 17.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Which is an average of 1.9e-06
因此 SciPy 快約 100 倍
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.