簡體   English   中英

如何在 3d 空間中找到段中最近的點

[英]How to find nearest point in segment in a 3d space

我正在解決一個聽起來像這樣的算法問題:

給定一個三維空間和其中的線段。 找到與所有線段距離最小的點。 示例輸入:在第一行中N - 段數,在給定每個段的開頭和結尾的接下來的N行中: x1 y1 z1 x2 y2 z2

我知道它是什么類型的給定問題(幾何中位數)並且我已經知道如何找到點和線段之間的最小距離( 笛卡爾距離這里提供的一個很好的代碼),但是我需要的是一個點(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]。 但是在其他情況下我們如何找到最近的點呢?

從您的最后一段我了解到您需要在最接近另一點的線段中找到一個點。

此函數返回最近點和距離:

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)

它也比您擁有的代碼更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM