gpt4 book ai didi

python - 找到从点到复杂曲线的最小距离

转载 作者:太空狗 更新时间:2023-10-29 16:53:57 24 4
gpt4 key购买 nike

我有一条复杂的曲线定义为表格中的一组点,如下所示(完整表格为 here ):

#  x   y
1.0577 12.0914
1.0501 11.9946
1.0465 11.9338
...

如果我用命令绘制这张表:

plt.plot(x_data, y_data, c='b',lw=1.)
plt.scatter(x_data, y_data, marker='o', color='k', s=10, lw=0.2)

我得到以下信息:

enter image description here

我在其中手动添加了红点和线段。我需要的是一种为每个点计算这些段的方法,即:一种找到从该 2D 空间中的给定点到插值曲线的最小距离的方法

我不能使用到数据点本身的距离(生成蓝色曲线的黑点),因为它们的间隔不相等,有时它们很近,有时它们相距很远,这深深地影响了我的结果更进一步。

由于这不是一条表现良好的曲线,我不确定我能做什么。我试过用 UnivariateSpline 插入它但它返回的拟合度很差:

# Sort data according to x.
temp_data = zip(x_data, y_data)
temp_data.sort()
# Unpack sorted data.
x_sorted, y_sorted = zip(*temp_data)

# Generate univariate spline.
s = UnivariateSpline(x_sorted, y_sorted, k=5)
xspl = np.linspace(0.8, 1.1, 100)
yspl = s(xspl)

# Plot.
plt.scatter(xspl, yspl, marker='o', color='r', s=10, lw=0.2)

enter image description here

我也尝试增加插值点的数量,但结果一团糟:

# Sort data according to x.
temp_data = zip(x_data, y_data)
temp_data.sort()
# Unpack sorted data.
x_sorted, y_sorted = zip(*temp_data)

t = np.linspace(0, 1, len(x_sorted))
t2 = np.linspace(0, 1, 100)
# One-dimensional linear interpolation.
x2 = np.interp(t2, t, x_sorted)
y2 = np.interp(t2, t, y_sorted)
plt.scatter(x2, y2, marker='o', color='r', s=10, lw=0.2)

enter image description here

任何想法/指示将不胜感激。

最佳答案

如果您愿意为此使用库,请查看shapely:https://github.com/Toblerity/Shapely

举个简单的例子(points.txt 包含您在问题中链接到的数据):

import shapely.geometry as geom
import numpy as np

coords = np.loadtxt('points.txt')

line = geom.LineString(coords)
point = geom.Point(0.8, 10.5)

# Note that "line.distance(point)" would be identical
print(point.distance(line))

作为一个交互式示例(这也绘制了您想要的线段):

import numpy as np
import shapely.geometry as geom
import matplotlib.pyplot as plt

class NearestPoint(object):
def __init__(self, line, ax):
self.line = line
self.ax = ax
ax.figure.canvas.mpl_connect('button_press_event', self)

def __call__(self, event):
x, y = event.xdata, event.ydata
point = geom.Point(x, y)
distance = self.line.distance(point)
self.draw_segment(point)
print 'Distance to line:', distance

def draw_segment(self, point):
point_on_line = line.interpolate(line.project(point))
self.ax.plot([point.x, point_on_line.x], [point.y, point_on_line.y],
color='red', marker='o', scalex=False, scaley=False)
fig.canvas.draw()

if __name__ == '__main__':
coords = np.loadtxt('points.txt')

line = geom.LineString(coords)

fig, ax = plt.subplots()
ax.plot(*coords.T)
ax.axis('equal')
NearestPoint(line, ax)
plt.show()

enter image description here

请注意,我添加了 ax.axis('equal')shapely 在数据所在的坐标系中运行。没有等轴图, View 会扭曲,虽然 shapely 仍会找到最近的点,但它赢了'在显示中看起来很正确:

enter image description here

关于python - 找到从点到复杂曲线的最小距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19101864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com