一种方法是使用interpolate
方法,该方法返回沿着线指定距离的点。您只需要先以某种方式生成一个距离列表即可。从Roy2012的答案中使用输入线条示例:
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)
shapely
的 substring
操作: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)
points = [line.interpolate(distance) for distance in distances] + [line.boundary[1]]
翻转了轴。我认为你需要使用boundary[0]
。 - Lewis Morris