J.G*_*alt 3 python geometry linear-algebra python-3.x
这里已经提出并回答了很多类似的问题,但浏览后没有一个完全解决我的问题。我正在寻找一种可靠的算法来找到每条由两个点指定的两条无限线的交点。就我而言,有两个并发症:
我目前的方法说明了基于斜率和截距的方法的缺点。这个问题可以通过实施一个旋转整个系统的步骤来部分规避,这样就没有线条是垂直的,但这看起来不太优雅。你知道更好的方法吗?
import numpy as np
# The intersection point of the example below should be (0,0)
# Vertices for the first line
p1_start = np.asarray([-5, 0])
p1_end = np.asarray([-3, 0])
# Vertices for the second line
p2_start = np.asarray([0, 4])
p2_end = np.asarray([0, 2])
# Calculate slope and intercept for the first line
m_1 = (p1_end[1]-p1_start[1])/(p1_end[0]-p1_start[0])
t_1 = p1_start[1] - m_1*p1_start[0]
# The slope and intercept are zero
print('First line')
print('slope = '+str(m_1))
print('intercept = '+str(t_1))
# Calculate slope and intercept for the second line
m_2 = (p2_end[1]-p2_start[1])/(p2_end[0]-p2_start[0])
t_2 = p2_start[1] - m_2*p2_start[0]
# The slope and intercept are infinite
print('Second line')
print('slope = '+str(m_2))
print('intercept = '+str(t_2))
# Find out where these points interset
# Doesn't work if one of the slopes is infinite
intersection_point_x = (t_2-t_1)/(m_1-m_2)
intersection_point_y = intersection_point_x*m_1 + t_1
print('Intersection point')
print(intersection_point_x)
print(intersection_point_y)
Run Code Online (Sandbox Code Playgroud)
按照AKX的解决方案,我将其链接线程中报告的解决方案改编为简短的 Python 片段:
import numpy as np
# The intersection point of the example below should be (0,0)
# Vertices for the first line
p1_start = np.asarray([-5, 0])
p1_end = np.asarray([-3, 0])
# Vertices for the second line
p2_start = np.asarray([0, 4])
p2_end = np.asarray([0, 2])
p = p1_start
r = (p1_end-p1_start)
q = p2_start
s = (p2_end-p2_start)
t = np.cross(q - p,s)/(np.cross(r,s))
# This is the intersection point
i = p + t*r
Run Code Online (Sandbox Code Playgroud)