[英]How to find nearest point in segment in a 3d space
I am solving an algorithmic problem which sounds like this:我正在解决一个听起来像这样的算法问题:
Given a three-dimensional space and segments in it.给定一个三维空间和其中的线段。 Find the point with minimal distance to all of the segments.找到与所有线段距离最小的点。 Example input: in the first line N - the number of segments, in the N next lines given the begin and the end of each segment: x1 y1 z1 x2 y2 z2示例输入:在第一行中N - 段数,在给定每个段的开头和结尾的接下来的N行中: x1 y1 z1 x2 y2 z2
I know what kind of a given problem it is (a geometrical median) and I already know how to find the minimal distance between point and segment ( Cartesian distance and a nice code provided here ), but what I need - is a point (x, y, z) on a segment to which I found the distance.我知道它是什么类型的给定问题(几何中位数)并且我已经知道如何找到点和线段之间的最小距离( 笛卡尔距离和这里提供的一个很好的代码),但是我需要的是一个点(x , y, z) 在我找到距离的线段上。 I need to know it to approximate my result.我需要知道它来近似我的结果。
Here is the code I have这是我的代码
# finds distance between point and segment
def lineseg_dist(p, a, b):
d = np.divide(b - a, np.linalg.norm(b - a))
s = np.dot(a - p, d)
t = np.dot(p - b, d)
h = np.maximum.reduce([s, t, 0])
c = np.cross(p - a, d)
return np.hypot(h, np.linalg.norm(c))
#segment
seg = [[1, 1, 1], [2, 2, 2]]
lineseg_dist([0, 0, 0], np.array(seg[0]), np.array(seg[1])) #1.73205
For example distance from [0, 0, 0] point to segment is known and we can say that the closest point of the segment to us is [1, 1, 1].例如,从 [0, 0, 0] 点到线段的距离是已知的,我们可以说线段离我们最近的点是 [1, 1, 1]。 But how do we find the nearest point in other cases?但是在其他情况下我们如何找到最近的点呢?
From your last paragraph I understand you need to find a point in a segment that is closest to another point.从您的最后一段我了解到您需要在最接近另一点的线段中找到一个点。
This function returns both the closest point and the distance:此函数返回最近点和距离:
def closest_point_and_distance(p, a, b):
s = b - a
w = p - a
ps = np.dot(w, s)
if ps <= 0:
return a, np.linalg.norm(w)
l2 = np.dot(s, s)
if ps >= l2:
closest = b
else:
closest = a + ps / l2 * s
return closest, np.linalg.norm(p - closest)
It is also faster than the code you have.它也比您拥有的代码更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.