[英]Efficient numpy euclidean distance calculation for each element
我有一個形狀為 512x512 的 numpy 數組和一個在此范圍內的中心點。 現在我想用中心點到數組元素的歐幾里德距離填充數組。
例如:Center=[10,10] -> array[0,0]=sqrt((0-10)^2+(0-10)^2)...
我已經有工作代碼:
def calc_euclidean_distance(center, point):
return np.sqrt((center[0] - point[0]) ** 2 + (center[1] - point[1]) ** 2)
target = np.zeros([512, 512])
center = np.array([10, 376]) #example
for iterrow, row in enumerate(target):
for itercol, i in enumerate(row):
target[iterrow, itercol] = self.calc_euclidean_distance(center, [iterrow, itercol])
但這真的很慢,而且可能非常“非pythonic”。 我想不出更好的方法,現在要求教育。
我相信這可以滿足您的需求:
w, h = (512, 512)
cx, cy = (10, 376)
xcoords, ycoords = np.meshgrid(np.arange(w), np.arange(h))
target = np.sqrt((xcoords - cx)**2 + (ycoords - cy)**2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.