我正在尝试使用docs中描述的匀称cut
函数将简单的线串切成10个片段:
def cut(line, distance):
# Cuts a line in two at a distance from its starting point
if distance <= 0.0 or distance >= line.length:
return [shapely.geometry.LineString(line)]
coords = list(line.coords)
for i, p in enumerate(coords):
pd = line.project(shapely.geometry.Point(p))
if pd == distance:
return [
shapely.geometry.LineString(coords[:i+1]),
shapely.geometry.LineString(coords[i:])]
if pd > distance:
cp = line.interpolate(distance)
return [
shapely.geometry.LineString(coords[:i] + [(cp.x, cp.y)]),
shapely.geometry.LineString([(cp.x, cp.y)] + coords[i:])]
我使用另一个函数来调用上述函数,因为cut
函数仅根据插值点将一条线分为两段:
def split_linestring(linestring, split_length):
#cuts a linestring in length/split_length number of segments
length = linestring.length
result_list = []
if length>split_length:
while length > split_length:
two_segment_list = cut(linestring,split_length)
length = two_segment_list[1].length
result_list.append(two_segment_list[0])
#print two_segment_list[0].length
linestring = two_segment_list[1]
result_list.append(two_segment_list[1])
else:
result_list.append(linestring)
return result_list
我编写了以下小型测试来检查线串对象的输出列表及其各自的长度:
A = shapely.geometry.Point(0, 0)
B = shapely.geometry.Point(2, 0)
AB = shapely.geometry.LineString([A, B])
split_length =Decimal('0.2')
#split_length = 0.2
r = split_linestring(AB, split_length)
for item in r:
print item.length
输出列表看起来不错,但最后一个线串的长度接近零:
0.2
0.2
0.2
0.2
0.2
0.2
0.2
0.2
0.2
0.2
2.22044604925e-16
我怀疑这是四舍五入错误,但是很难追踪到哪里或原因。如何整齐地将我的行划分为10个相等的部分,并且没有尾随的接近零的线串?