如何使用 numpy.linalg.solve 给定点坐标找到两条线相交的位置?
How to find where two lines intersect using numpy.linalg.solve given points coordinates?
所以我尝试使用 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
所以我不太确定该怎么做,有人可以帮我解决这个问题吗?
已按要求关注 these answers which gives clear explanations about the equations behind this problem and its well-known analytical resolution (based on Cramer's rule and determinants), it is possible to construct a simple linear system A x = b
in order to use 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]
所以我尝试使用 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
所以我不太确定该怎么做,有人可以帮我解决这个问题吗?
已按要求关注 these answers which gives clear explanations about the equations behind this problem and its well-known analytical resolution (based on Cramer's rule and determinants), it is possible to construct a simple linear system A x = b
in order to use 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]