【问题标题】:How to find nearest point in segment in a 3d space如何在 3d 空间中找到段中的最近点
【发布时间】:2020-11-03 12:48:44
【问题描述】:

我正在解决一个听起来像这样的算法问题:

给定一个三维空间和其中的片段。找到与所有线段距离最小的点。 示例输入:在第一行 N - 段数,在 N 下一行给出每个段的开始和结束: x1 y1 z1 x2 y2 z2

我知道它是什么类型的给定问题(几何中位数),并且我已经知道如何找到点和线段之间的最小距离(Cartesian distance 和一个很好的代码提供了here),但我需要什么- 是我找到距离的线段上的一个点 (x, y, z)。我需要知道它来近似我的结果。

这是我的代码

# 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

例如,从 [0, 0, 0] 点到线段的距离是已知的,我们可以说线段中离我们最近的点是 [1, 1, 1]。但是在其他情况下我们如何找到最近的点呢?

【问题讨论】:

  • 很遗憾,这个问题不包含答案。我需要找到最近距离的点的坐标
  • 请尝试以编程方式制定您的问题,使用您的输入数据结构、预期输出和一些伪代码来显示您认为应该可行但不可行的方法
  • 什么是minimal distance to all of the segments??最小距离和?还有什么?
  • @Andrii Syd 抱歉,这不是数学定义。当点位于线段上时,点到线段的最小距离为零。但是两个部分呢?三个?有必要定义一些接近度。

标签: python algorithm numpy geometry


【解决方案1】:

从您的最后一段中,我了解到您需要在段中找到最接近另一个点的点。

这个函数返回最近点和距离:

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)

它也比你拥有的代码更快。

【讨论】:

猜你喜欢
  • 2018-06-17
  • 2019-06-04
  • 2018-06-26
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2021-08-06
  • 2016-08-09
  • 2012-08-05
相关资源
最近更新 更多