Python:沿着连接点集的线的等距点

时间:2018-07-25 06:30:01

标签: python python-3.x numpy matplotlib scipy

如numpy.linspace给出线性连接的两个点之间的等距点。我可以沿着连接一组点的直线获得等距点吗?

例如:

import numpy as np
npts = 10
xcoords, ycoords = [0,1], [0,1]
xquery = np.linspace(xcoords[0],xcoords[1], npts)
yquery = np.linspace(ycoords[0],ycoords[1], npts)

在这里,我需要在连接一组点的线上等距查询点

xcoords, ycoords = [0,1,5,8], [0,3,6,7]

2 个答案:

答案 0 :(得分:3)

按等长部分细分二维分段线:

import matplotlib.pyplot as plt
%matplotlib inline

from scipy.interpolate import interp1d
import numpy as np


x = [0, 1, 8, 2, 2]
y = [1, 0, 6, 7, 2]

# Linear length on the line
distance = np.cumsum(np.sqrt( np.ediff1d(x, to_begin=0)**2 + np.ediff1d(y, to_begin=0)**2 ))
distance = distance/distance[-1]

fx, fy = interp1d( distance, x ), interp1d( distance, y )

alpha = np.linspace(0, 1, 15)
x_regular, y_regular = fx(alpha), fy(alpha)

plt.plot(x, y, 'o-');
plt.plot(x_regular, y_regular, 'or');
plt.axis('equal');

result

答案 1 :(得分:1)

编辑:为明确起见,此答案仅在x方向上提供了等距的点。我对这个问题的误解

我相信您要寻找的是插值? scipy.interpolate的文档在这里:https://docs.scipy.org/doc/scipy-1.0.0/reference/tutorial/interpolate.html#d-interpolation-interp1d

但是为了快速展示您的示例,

from scipy.interpolate import interp1d
x=[0,1,5,8]
y=[0,3,6,7]
f=interp1d(x,y)

然后只需将要查询的新x点输入到f中即可(xnew不能超过x的最小/最大范围)

xnew=np.linspace(0,8,10)
ynew=f(xnew)

看看情节

import matplotlib.pyplot as plt
plt.plot(xnew,ynew,'ro',x,y,'x')
plt.show()