【问题标题】:Line-Line intersection in Python with numpyPython中与numpy的线-线交点
【发布时间】:2017-06-19 12:58:23
【问题描述】:

我有一个相对简单的问题,我知道答案,但我似乎无法使用 Python 和 Numpy 找到正确的实现。这个想法是,我有两条线,我需要找到虚拟交点(我使用了来自https://www.youtube.com/watch?v=kCyoaidiXAU&t=313s 的示例)。

两条线的形式为 r = r0 + t*V,其中 r0 为位置向量(线所经过的点),t 为变量,V 为方向向量。方向向量 V 可以简​​单地通过线的两个点找到向量,例如V = A - B。

这样,就可以将这一行表述为:
L1 = r0(已知点)+ t(未知变量)* V(方向向量)

现在,我可以很容易地手动找到 t,但我不知道如何告诉 Python。我尝试了 numpy.linalg.solve,但这给了我一个矩阵,而我需要一个值。

例如:

# Line A and Line B that intersect somewhere
A = LineString([(4., 0.), (4., -3.)])
B = LineString([(6., 2.), (10., 2.)])

# direction vectors for line A and B
v1 = (A[0].x - A[1].x, A[0].y, A[1].y) # --> [0,3]
v2 = (B[0].x - B[1].x, B[0].y, B[1].y) # --> [-4,0]

L1 = A[1] + x * v1
L2 = B[1] + y * v2

现在,我将通过为 x 求解 L1 来手动解决这个问题:

L1 = [4, 0] + x * [0, 3] = [4, 3x]
L2 = [6, 2] + y * [-4, 0] = [6-4y, 2]

# finding intersection point by solving L1 = L2
4 = 6-4y  &  3x = 2
y = 1/2   &   x = 2/3

但我不知道如何告诉 numpy/python 如何求解 x 和 y。

任何正确方向的帮助或指导将不胜感激。

【问题讨论】:

  • 您说“使用 numpy”,但我在这里看不到任何 numpy。你想要一个 numpy 解决方案吗?还是没有必要?
  • 如果可能没有,很好,但我已经尝试过 Numpy.linalg.solve,所以我认为 numpy 会有功能来做这样的事情..
  • 在一般情况下,您只需要手动解决它,即当您将所有数值(例如 [4,0])替换为您假设已知的变量(例如 [r0_x,r0_y ]) 这样做你会得到 y 作为你知道的几个变量的表达式。

标签: python numpy vector


【解决方案1】:

通过 A0 和 A1 的线具有参数方程(1-t)*A0 + t*A1,其中 t 是参数。 通过 B0 和 B1 的线具有参数方程(1-s)*A0 + s*A1,其中 s 是参数。设置这些相等,我们得到系统(A1-A0)t + (B0-B1)s == B0-A0。所以,右手边是 B0-A0,矩阵有 A1-A0 和 B0-B1 列。系统可以用np.linalg.solve解决。完整示例:

A = np.array([[4, 0], [4, -3]])
B = np.array([[6, 2], [10, 2]])
t, s = np.linalg.solve(np.array([A[1]-A[0], B[0]-B[1]]).T, B[0]-A[0])
print((1-t)*A[0] + t*A[1])
print((1-s)*B[0] + s*B[1])

两个打印命令都输出[4., 2.] 确认正确性。 (第二次打印实在是多余。)

【讨论】:

    【解决方案2】:

    这是我编写的一个函数,用于查找两条 3d 线之间的最近点

    import scipy.optimize
    #takes in two lines, the line formed by pt1 and pt2, and the line formed by pt3 and pt4, and finds their intersection or closest point
    def fourptsMeetat(pt1,pt2,pt3,pt4):
        #least squares method
        def errFunc(estimates):
            s, t = estimates
            x = pt1 + s * (pt2 - pt1) - (pt3 + t * (pt4 - pt3))
            return x
    
        estimates = [1, 1]
    
        sols = scipy.optimize.least_squares(errFunc, estimates)
        s,t = sols.x
    
        x1 =  pt1[0] + s * (pt2[0] - pt1[0])
        x2 =  pt3[0] + t * (pt4[0] - pt3[0])
        y1 =  pt1[1] + s * (pt2[1] - pt1[1])
        y2 =  pt3[1] + t * (pt4[1] - pt3[1])
        z1 =  pt1[2] + s * (pt2[2] - pt1[2])
        z2 = pt3[2] + t * (pt4[2] - pt3[2])
    
        x = (x1 + x2) / 2  #halfway point if they don't match
        y = (y1 + y2) / 2  # halfway point if they don't match
        z = (z1 + z2) / 2  # halfway point if they don't match
    
        return (x,y,z)
    

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多