Skip to main content
 首页 » 编程设计

python之我如何使用 Shapely 检测所有距离小于 N 米的点

2025年05月04日13dyllove98

假设我有一个点列表(坐标以米为单位):

points = [(1, 1), (2, 2), (-1, 3), ..., (1000, 1000)] 

我想使用 Shapely 库将 N 米半径内的所有点(来自 points)返回到某个指定的原点,例如 (3 , 3)。

更新:如果我执行:

import numpy as np 
points = [(1, 1), (2, 2), (3, 4), (100, 100), (5, 5), (1, 2)] 
points_array = np.array(points) 
print(points_array.shape)  # prints [n,2] where n is the number of points 
max_distance = 2 
origin = np.array([3, 3]) 
distance_array = np.sqrt((points_array - origin) ** 2) 
near_points = points_array[distance_array < max_distance] 
print('near points', near_points) 

我收到了

(6, 2) 
near points [2 2 3 4 2] 

这看起来有点奇怪,因为即使我得到 [(2, 2), (3, 4), 2=?]

请您参考如下方法:

大量数据的快速计算最好用 numpy 处理。不是从坐标创建形状对象并使用内置的距离函数,使用 numpy 数组计算距离要容易得多(对于点!,而不是多边形)。如果您想对线和多边形执行相同的操作并使用最近的距离,shapely 是您的 friend 。

import numpy as np 
points_array = np.array(points) 
print(points_array.shape)  # prints [n,2] where n is the number of points 
max_distance = 100 
origin = np.array([3, 3]) 

现在计算欧氏距离作为差的平方和 在轴 1(坐标)上

distance_array = np.sqrt(np.sum((points_array - origin) ** 2, 1)) 

并检索距离小于max_distance的点

near_points = points_array[distance_array < max_distance] 

为了在速度方面将 numpy 解决方案与其他答案进行比较,我对同一组 1e6 个随机点的答案进行了计时:

  • 上面的代码耗时 49 毫秒
  • Peter Collingridge 的优化解决方案:44 毫秒
  • vurmax 的列表解决方案(使用列表理解,见下文):2.88 秒(慢 60 倍)
  • 经过 Peter Collingridge 优化的列表解决方案:2.48s
  • Christian Sloper 的玩具造型解决方案:15.2 秒(慢 300 倍)
points_vurmax = [(x,y) for x,y in points_array  
                 if math.sqrt((x - origin[0])**2 + (y - origin[1])**2) < max_dist] 
points_vurmax2 = [(x,y) for x,y in points_array  
                  if (x - origin[0])**2 + (y - origin[1])**2 < max_dist ** 2]