我还是python的新手。我需要帮助通过简单的距离计算来计算折线的长度:
distance = sqrt( (x1 - x2)**2 + (y1 - y2)**2 )
例如我的输入csv看起来像这样。
id x y sequence
1 1.5 2.5 0
1 3.2 4.9 1
1 3.6 6.6 2
1 4.4 5.0 3
2 2.0 4.5 0
2 3.5 6.0 1
我有'id'和'sequence'(行顶点的序列号)。怎么读csv文件?如果当前'id'与前一行'id'具有相同的值,则执行距离计算:sqrt((x [i] - x [i-1])** 2 +(y [i] - y [i -1])** 2)。之后,按“id”分组,并将它们的“距离”值相加。
输出csv如下所示:
id distance
1 ?
2 ?
提前致谢。
答案 0 :(得分:1)
折线:
两点之间的距离以及点与折线之间的距离:
def lineMagnitude (x1, y1, x2, y2):
lineMagnitude = math.sqrt(math.pow((x2 - x1), 2)+ math.pow((y2 - y1), 2))
return lineMagnitude
#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def DistancePointLine (px, py, x1, y1, x2, y2):
#http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
LineMag = lineMagnitude(x1, y1, x2, y2)
if LineMag < 0.00000001:
DistancePointLine = 9999
return DistancePointLine
u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
u = u1 / (LineMag * LineMag)
if (u < 0.00001) or (u > 1):
#// closest point does not fall within the line segment, take the shorter distance
#// to an endpoint
ix = lineMagnitude(px, py, x1, y1)
iy = lineMagnitude(px, py, x2, y2)
if ix > iy:
DistancePointLine = iy
else:
DistancePointLine = ix
else:
# Intersecting point is on the line, use the formula
ix = x1 + u * (x2 - x1)
iy = y1 + u * (y2 - y1)
DistancePointLine = lineMagnitude(px, py, ix, iy)
return DistancePointLine
有关详细信息,请访问:http://www.maprantala.com/2010/05/16/measuring-distance-from-a-point-to-a-line-segment/