如何确定点是否在某一线附近?

我之前问过“ 我怎么能判断一个点是否属于某条线? ”我找到了合适的答案,所以非常感谢你。

现在,我想知道如何确定某个点是否接近我的线。

您需要计算到线的直角距离 。 然后你必须定义“关闭”是什么,并测试它是否在该距离内。

你想要的等式是:

d = | V ^^·R | =(|(X_2-X_1)(Y_1-y_0) - (X_1-X_0)(Y_2-Y_1)|)/(SQRT((X_2-X_1)^ 2 +(y_2- Y_1)^ 2))。

@Alan Jackson的答案几乎是完美的 – 但他的第一个(也是最多的投票)评论表明端点没有得到正确处理。 要确保点位于线段上,只需创建一个区段为对角线的框,然后检查该点是否包含在其中。 这是伪代码

给定线ab,包括点a和b,以及点p,有问题:

int buffer = 25;//this is the distance that you would still consider the point nearby Point topLeft = new Point(minimum(ax, bx), minimum(ay, by)); Point bottomRight = new Point(maximum(ax, bx), maximum(ay, by)); Rect box = new Rect(topLeft.x - buffer, topLeft.y - buffer, bottomRight.x + buffer, bottomRight.y + buffer); if (box.contains(p)) { //now run the test provided by Alan if (test) return true; } return false; 

谷歌是你的朋友: 点线距离(二维) 。 您可以在底部使用等式,然后就可以了。

基本上,你想要做的是找到法线 – 也就是垂直于你的线的线 – 与你的点和线相交,然后计算沿着这条线的距离。

离附近有多近?

某些几何体将为您提供所需的答案,您只需要了解以下步骤即可。

假设你的形状是y = mx + b,那么到你的点的最短距离将是垂直于你的起始线的线(m1 = -1 / m),与你所讨论的点相交。

从那里计算交叉点和相关点之间的距离。

计算最接近该点的线上的点。

假设线段是a和b,并且该点是p。

 float vAPx = px - ax; float vAPy = py - ay; float vABx = bx - ax; float vABy = by - ay; float sqDistanceAB = a.distanceSq(b); float ABAPproduct = vABx*vAPx + vABy*vAPy; float amount = ABAPproduct / sqDistanceAB; if (amount > 1) amount = 1; if (amount < 0) amount = 0; 

它给你'数量',你在A和B之间的线段有多远(正确有界)。

  float nx = (amount * (bx - ax)) + ax; float ny = (amount * (by - ay)) + ay; 

给你点(nx,ny)。

 if (p.distance(nx,ny) > threshold) reject; 

这将在线段结束之后正常工作,因为它将“数量”保持在0和1之间。

如果你不希望它有界线段摆脱金额的界限。 其余的代码仍然可以工作,计算A和B之前和之后的位置。

还有一个问题声称这个问题是重复的,但是,它要求一个不同的东西,因此我的解决方案解决了点的位置,然后只解决了欧几里德距离(实际上解决了两个问题)。

a.distanceSq(b)也可以作为vABx vABx + vABy vABy来完成,因为我们已经完成了这些操作。

这是一个python函数,可以解决这个问题。 它应该工作在2维或3维(或更多),并处理垂直和水平线,没有特殊情况。 如果将clipToSegment设置为true,则如果投影线超出提供的线段,则返回的点将被剪裁到末尾。

 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 

用法:(从[2,4]到[4,6]的线段的点[4,5]的距离)

 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)