[英]Python - Find intersection between lines spanned by several points
我認為這是一個相當基本的問題,我無法找到一個優雅的解決方案。 想象一下,我在二維空間中有兩條相當復雜的線(例如B樣條),它們由兩個維矩陣(n,2)跨越,其中n(行)是沿線的點數,兩列分別對應於x和y坐標。 更多信息:
我想找到這些線相交的點。 就我的目的而言,將這兩條線在每兩個連續點之間線性化就足夠了。
不幸的是,到目前為止我能提出的每個解決方案都是非常低效的(例如,使用兩個嵌套的for循環並檢查一行上的兩個點的每個段與另一行上的每個段)。 必須有一種更優雅的方式來做到這一點。
是否有任何類型的功能可以簡化這種例程的實現?
PS:下面你可以找到我上面描述的系統的圖示。
感謝大家的回復,特別是Dschoni的相關出版物參考,以及Piinthesky的評論給了我解決方案的想法:
我們將兩個線點的X坐標連接成一個公共向量,然后為兩條線中的每一條插入Y坐標。 因為我們現在在相同的X位置有點,我們可以相互減去Y值。 在點之間,差異的符號發生變化,線相交。 謝謝大家的幫助!
這是我的解決方案代碼:
import pickle
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
# Load data series
X1 = pickle.load(open("X1.p","rb"))
Y1 = pickle.load(open("Y1.p","rb"))
X2 = pickle.load(open("X2.p","rb"))
Y2 = pickle.load(open("Y2.p","rb"))
# Convert X vectors to lists, and merge them
X1_list = list(X1)
X2_list = list(X2)
in_first = set(X1_list)
in_second = set(X2_list)
in_second_but_not_in_first = in_second - in_first
result = X1_list + list(in_second_but_not_in_first)
X_joint = np.asarray(result) # Revert to array
# Create interpolated functions
line_1 = interp1d(X1, Y1, kind='linear', fill_value='extrapolate')
line_2 = interp1d(X2, Y2, kind='linear', fill_value='extrapolate')
# Create joint Ys
Y1_joint = line_1(X_joint)
Y2_joint = line_2(X_joint)
# Calculate difference in Y
difference = Y1_joint-Y2_joint
# Plot the original data series
f, axarr = plt.subplots(2)
axarr[0].plot(X1, Y1,'b')
axarr[0].plot(X2, Y2,'r')
# Plot the difference values
axarr[1].plot(X_joint,difference)
axarr[1].plot([min(X_joint),max(X_joint)],[0,0],'k')
# The intersections are where the difference graph dips below or rises above zero
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.