How can I tell if a point is nearby a certain line

2019-01-18 00:42发布

I asked "How can I tell if a point belongs to a certain line?" before and I found a suitable answer so thank you very much.

Now, I would like to know how to tell if a certain point is close to my line.

7条回答
仙女界的扛把子
2楼-- · 2019-01-18 01:10

Here's a python function which does the trick. It should work in 2 or 3 dimensions (or more) and handles vertical and horizontal lines without special cases. If you set clipToSegment to true the returned point is clipped to the ends if the projected line extends beyond the supplied line segment.

def nearestPointOnLine(pt, r0, r1, clipToSegment = True):
    r01 = r1 - r0           # vector from r0 to r1 
    d = np.linalg.norm(r01) # length of r01
    r01u = r01 / d          # unit vector from r0 to r1
    r = pt - r0             # vector from r0 to pt
    rid = np.dot(r, r01u)   # projection (length) of r onto r01u
    ri = r01u * rid         # projection vector
    lpt = r0 + ri           # point on line

    if clipToSegment:       # if projection is not on line segment
        if rid > d:         # clip to endpoints if clipToSegment set
            return r1
        if rid < 0:
            return r0 

    return lpt

Usage: (distance of point [4,5] from the line segment from [2,4] to [4,6])

r0 = np.array([2,4])
r1 = np.array([4,6])
rpt = np.array([4,5])
pt = nearestPointOnLine(rpt, r0, r1, True)

dist = np.linalg.norm(rpt-pt)
print('dist', dist)
查看更多
登录 后发表回答