如何在 Shapely 中的一条线上获得等间距的点

How to get equally spaced points on a line in Shapely

我正在尝试(大致)均等地 space 一条直线的点到预定义的距离。

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

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

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

可以使用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)

此数据的结果如下。每个圆圈是一个点。

一种方法是使用 interpolate method that returns points at specified distances along the line. You just have to generate a list of the distances somehow first. Taking the input line example from :

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)


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

此外,请注意循环内的 unary_union I'm using should be more efficient than calling 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)