【问题标题】:How to get equally spaced points on a line in Shapely如何在Shapely的线上获得等距点
【发布时间】:2020-07-20 06:54:29
【问题描述】:

我正在尝试(大致)将线的点平均间隔到预定义的距离。

距离之间有一定的公差是可以的,但尽可能接近是可取的。

我知道我可以手动遍历行中的每个点并检查 p1 与 p2 的距离,并在需要时添加更多点。

但我想知道是否有人知道是否有办法通过 shapely 来实现这一点,因为我已经在 LineString 中有坐标。

【问题讨论】:

    标签: python shapely


    【解决方案1】:

    一种方法是使用interpolate 方法返回沿线指定距离处的点。您只需要先以某种方式生成距离列表。以Roy2012's answer的输入行为例:

    import numpy as np
    from shapely.geometry import LineString
    from shapely.ops import unary_union
    
    line = LineString(([0, 0], [2, 1], [3, 2], [3.5, 1], [5, 2]))
    

    指定距离分割:

    distance_delta = 0.9
    distances = np.arange(0, line.length, distance_delta)
    # or alternatively without NumPy:
    # points_count = int(line.length // distance_delta) + 1
    # distances = (distance_delta * i for i in range(points_count))
    points = [line.interpolate(distance) for distance in distances] + [line.boundary[1]]
    multipoint = unary_union(points)  # or new_line = LineString(points)
    


    请注意,由于距离是固定的,因此您可能会在行尾遇到问题,如图所示。根据您的需要,您可以包含/排除添加线端点的[line.boundary[1]] 部分,或使用distances = np.arange(0, line.length, distance_delta)[:-1] 排除倒数第二个点。

    另外,请注意,我使用的 unary_union 应该比在循环内调用 object.union(other) 更有效,如另一个答案所示。

    分割成固定点数:

    n = 7
    # or to get the distances closest to the desired one:
    # n = round(line.length / desired_distance_delta)
    distances = np.linspace(0, line.length, n)
    # or alternatively without NumPy:
    # distances = (line.length * i / (n - 1) for i in range(n))
    points = [line.interpolate(distance) for distance in distances]
    multipoint = unary_union(points)  # or new_line = LineString(points)
    

    【讨论】:

    • 哇,太完美了。
    • 我刚刚意识到points = [line.interpolate(distance) for distance in distances] + [line.boundary[1]] 翻转了轴。我想你需要boundry[0]
    • @LewisMorris “翻转轴”是什么意思?我无法用给定的示例重现该问题。我也不确定将boundary[1] 更改为boundary[0] 将如何解决问题,因为boundary[0] 应该已经包含在内,因为distances 的第一个值为零。
    【解决方案2】:

    你可以使用shapelysubstring操作:

    from shapely.geometry import LineString
    from shapely.ops import substring
    
    line = LineString(([0, 0], [2, 1], [3,2], [3.5, 1], [5, 2]))
    
    mp = shapely.geometry.MultiPoint()
    for i in np.arange(0, line.length, 0.2):
        s = substring(line, i, i+0.2)
        mp = mp.union(s.boundary)
    

    该数据的结果如下所示。每个圆圈都是一个点。

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多