Friday, 16 November 2007

Code: The Distance from Point to Line Segment

上周提到的“点到线段的距离”问题,我的Python Code是这样的:

import math

def p2s( a, b, p ):
dX = b[0] - a[0]
dY = b[1] - a[1]
segmentLen = math.sqrt( dX * dX + dY * dY )
halfLen = segmentLen / 2

pX = p[0] - a[0]
pY = p[1] - a[1]
if segmentLen < 1E-6:
return math.sqrt( pX * pX + pY * pY )

newX = abs( ( pX * dX + pY * dY ) / segmentLen - halfLen )
newY = abs( - pX * dY + pY * dX ) / segmentLen

if newX > halfLen:
newX = newX - halfLen
return math.sqrt( newX * newX + newY * newY )
else:
return newY

a = ( 1, 1 )
b = ( 4, 5 )
p = ( 0, 5 )

print p2s( a, b, p )

3 Comments:

At 14 January, 2008 23:22, Anonymous Anonymous said...

thanks :)

 
At 14 May, 2009 07:22, Anonymous Anonymous said...

Big thanks to you :-) That what i
wanted, you saved my night-dreams
;-)

 
At 13 July, 2011 09:50, Anonymous distance measurement said...

thanks for sharing the code.I really interested to learn on how to measure the distance from point to line segment.

 

Post a Comment

<< Home