<p>如果您愿意为此使用库,请查看<code>shapely</code>:<a href="https://github.com/Toblerity/Shapely" rel="noreferrer">https://github.com/Toblerity/Shapely</a></p>
<p>举个简单的例子(<code>points.txt</code>包含您在问题中链接到的数据):</p>
<pre><code>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)
</code></pre>
<p>作为一个交互式示例(这也会绘制所需的线段):</p>
<pre><code>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()
</code></pre>
<p><img src="https://i.stack.imgur.com/TM4xW.png" alt="enter image description here"/></p>
<p>注意,我添加了<code>ax.axis('equal')</code>。<code>shapely</code>在数据所在的坐标系中操作。如果没有等轴图,视图将被扭曲,尽管<code>shapely</code>仍将找到最近的点,但在显示中它看起来不太正确:</p>
<p><img src="https://i.stack.imgur.com/fEnH6.png" alt="enter image description here"/></p>