2 回答

TA貢獻1895條經驗 獲得超3個贊
由于您已經在使用 numpy,請嘗試以矢量化方式重寫您的操作,而不是使用循環。
# choose appropriate dtype for better perf
dtype = np.float32
# take all indices in an array
indices = np.indices((ysize, xsize), dtype=dtype).T
points = np.array(list(lis.keys()), dtype=dtype)
# squared distance from all indices to all points
dist = (indices[..., np.newaxis] - points.T) ** 2
dist = dist.sum(axis=-2)
# squared circle radii
dist_thresh = np.array(list(lis.values()), dtype=dtype) ** 2
intersect = np.all(dist <= dist_thresh, axis=-1)
在我的機器上,這比 for 循環版本快 60 倍左右。
它仍然是一個蠻力版本,可能對所有坐標進行許多不必要的計算。問題中沒有給出圓圈,因此很難對它們進行推理。如果它們覆蓋的區域相對較小,那么如果考慮較小的區域,問題的解決速度會快得多(仍然是計算上的,而不是分析上的)。例如,代替測試所有坐標,可以使用圓的邊界框的交點,這可以顯著減少計算負載。
添加回答
舉報