[英]Finding the intersection point between line and piecewise linear curves
我有兩條曲線,一條是一條線,例如y = x / 4,另一條是我與線段連接的點集(例如: x = [1, 2.5, 3.4, 5.8, 6]
, y = [2, 4, 5.8, 4.3, 4]
,它在2D平面中形成5個點,形成分段線性曲線),我應該找到這兩條曲線之間的交點。 我應該首先形成此分段線性曲線,然后找到相交點。 幸運的是,我發現我可以使用numpy.polyfit
來找到每個線段的多項式系數,如下所示:
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 6] # in my primary problem i dont have just 5 points and i have approximately 200 points !
y = [0, 0, 3, -1, 2]
x = np.array(x)
y = np.array(y)
a = [np.polyfit(x[i:(i+2)], y[i:(i+2)], 1) for i in range(len(x)-1)]
plt.plot(x, y, 'o')
plt.show()
但是現在我真的很困惑如何使用這些系數來找到兩個圖形之間的相交點! (在我的主要問題中,我只有5個點,而我大約有200個點!)解決此問題的一種方法是使用(( Solve ))命令檢查線段與線段的交點,但這非常耗時,此命令不適用於第(( segment ))行。
沒有理由應該恰好有一個交點。 以您的示例為例,如果您采用了$ y = 1 $,則將有三個交集;如果您采用了$ y = -2 $,則將不會有交集;如果您采用了$ y = 0 $,則將無窮大許多。
為了找到它們,一種方法是考慮連接x
和y
元素的每個線段,並且已經找到了它們的斜率和相交,並擴展了要在實線上定義的線段。 現在,例如,使用此問題中的過程之一,找到給定線與擴展線之間的交點。 如果有0個交集,則原始未擴展線段也有0個交集,如果有1個交集,則如果x值位於定義該線段的x值范圍內,則未擴展的那個線段將具有1個交集(且0否則),並且如果有無限多個相交,則線段上的每個點都將位於相交處。 對每個線段重復該過程。
def get_intersection(line1, line2):
"""Returns the intersection, if any, between two lines, None if the lines are equal, and
the empty array if the lines are parallel.
Args:
line1 (numpy.array): [slope, intercept] of the first line.
line2 (numpy.array): [slope, intercept] of the second line.
Taken from https://stackoverflow.com/a/42727584/5085211.
"""
if (np.array_equal(line1, line2)):
return None
if line1[0] == line2[0]:
return np.empty(0)
l1 = np.insert(line1, 1, -1)
l2 = np.insert(line2, 1, -1)
x, y, z = np.cross(l1, l2)
return np.hstack([x, y]) / z
line_of_interest = [0.25, 0] # y = x/4
for i in range(len(x)-1):
p = get_intersection(a[i], line_of_interest)
if np.array_equal(p, []):
continue
elif np.array_equal(p, None):
print('Entire line segment between {0} and {1}'.format(x[i], x[i+1]))
elif x[i] <= p[0] and p[0] < x[i+1]:
print(p)
# Prints:
# [ 0. 0.]
# [ 1.09090909 0.27272727]
# [ 3.11111111 0.77777778]
# [ 5.6 1.4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.