如何使用 numpy.linalg.solve 给定点坐标找到两条线相交的位置?

问题描述 投票:0回答:2

所以我尝试使用 numpy.linalg.solve() 仅使用一些端点坐标来查找两条线彼此相交的位置。如果一行的坐标是:

(x1, y1)
(x2, y2)
。我试过:

import numpy as np
a = np.array([[y2-y1],[x1-x2]])
b = np.array([(x1*y2)-(y1*x2)])

np.linalg.solve(a,b)

但是我认为方程式不正确并且它返回以下错误:

numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square

所以我真的不确定该怎么做,有人可以帮我吗?

python numpy linear-algebra
2个回答
3
投票

以下这些答案清楚地解释了这个问题背后的方程及其众所周知的分析解决方案(基于克莱默规则和行列式),可以构建一个简单的线性系统

A x = b
以使用np .linalg.solve 根据要求:

import numpy as np

# Given these endpoints coordinates
# Line 1 passing through points p1 (x1,y1) and p2 (x2,y2)
p1 = [0, 0]
p2 = [1, 1]

# Line 2 passing through points p3 (x3,y3) and p4 (x4,y4)
p3 = [0, 1]
p4 = [1, 0]

# Line 1 dy, dx and determinant
a11 = (p1[1] - p2[1])
a12 = (p2[0] - p1[0])
b1 = (p1[0]*p2[1] - p2[0]*p1[1])

# Line 2 dy, dx and determinant
a21 = (p3[1] - p4[1])
a22 = (p4[0] - p3[0])
b2 = (p3[0]*p4[1] - p4[0]*p3[1])

# Construction of the linear system
# coefficient matrix
A = np.array([[a11, a12],
              [a21, a22]])

# right hand side vector
b = -np.array([b1,
               b2])
# solve
try:
    intersection_point = np.linalg.solve(A,b)
    print('Intersection point detected at:', intersection_point)
except np.linalg.LinAlgError:
    print('No single intersection point detected')

给出了那些给定点的预期输出:

>>> Intersection point detected at: [0.5 0.5]

0
投票
import numpy as np

data = np.array([
    #  segment1               segment2
    # [[x1, y1], [x2, y2]],  [[x1, y1], [x2, y2]]
    [[0, 0], [1, 1], [0, 1], [1, 0]],
    [[0, 0], [1, 1], [1, 0], [1, 1]],
    [(0, 1), (0, 2), (1, 10), (2, 10)],
    [(0, 1), (1, 2), (0, 10), (1, 9)],
    [[0, 0], [0, 1], [0, 2], [1, 3]],
    [[0, 1], [2, 3], [4, 5], [6, 7]],  
    [[1, 2], [3, 4], [5, 6], [7, 8]],
])

def intersect(data):
    L = len(data)
    x1, y1, x2, y2 = data.reshape(L * 2, -1).T
    R = np.full([L, 2], np.nan)
    X = np.concatenate([
        (y2 - y1).reshape(L * 2, -1), 
        (x1 - x2).reshape(L * 2, -1)], 
        axis=1
    ).reshape(L, 2, 2)
    B = (x1 * y2 - x2 * y1).reshape(L, 2)
    I = np.isfinite(np.linalg.cond(X))
    R[I] = np.matmul(np.linalg.inv(X[I]), B[I][:,:,None]).squeeze(-1)
    return R

intersect(data)

array([[ 0.5,  0.5],
       [ 1. ,  1. ],
       [ 0. , 10. ],
       [ 4.5,  5.5],
       [ 0. ,  2. ],
       [ nan,  nan],
       [ nan,  nan]])
© www.soinside.com 2019 - 2024. All rights reserved.