【发布时间】:2018-04-21 00:13:42
【问题描述】:
我在两个 XY 点 (p1 和 p2) 和第三个 XY 点 (p3) 之间有一条线/向量,它位于该线之外。根据this post,我知道如何获得该点到线的距离。但我实际上正在寻找的是该线上的一个点(p4),它与第三点(p3)的最小距离(d)。我找到了this post,但我觉得这不是正确的解决方案。也许 Numpy 或 Python 中包含一些东西?
根据@allo,我尝试了以下方法。您可以将我的代码下载为Python file 或Jupyter Notebook(均为Python3)。
points = [[1, 1], [3, 1], [2.5, 2], [2.5, 1]]
import matplotlib.pyplot as plt
%matplotlib inline
fig, ax = plt.subplots()
fig.set_size_inches(6,6)
x, y = zip(*points[:2])
l1, = ax.plot(x,y, color='blue')
scatter1 = ax.scatter(x=x,y=y, color='blue', marker='x', s=80, alpha=1.0)
x, y = zip(*points[2:])
l2, = ax.plot(x,y, color='red')
scatter2 = ax.scatter(x=x,y=y, color='red', marker='x', s=80, alpha=1.0)
p1 = Vector2D(*points[0])
p2 = Vector2D(*points[1])
p3 = Vector2D(*points[2])
p1p2 = p2.sub_vector(p1)
p1p3 = p3.sub_vector(p1)
angle_p1p2_p1p3 = p1p2.get_angle_radians(p1p3)
length_p1p3 = p1p3.get_length()
length_p1p2 = p1p2.get_length()
p4 = p1.add_vector(p1p2.multiply(p1p3.get_length()/p1p2.get_length()).multiply(math.cos(p1p2.get_angle_radians(p1p3))))
#p4 = p1 + p1p2 * length(p1p3)/length(p1p2)*cos(angle(p1p2, p1p3))
p4 = p1.add_vector(p1p2.multiply(length_p1p3/length_p1p2*math.cos(angle_p1p2_p1p3)))
p4
这导致 p4 = (1.8062257748298551, 1.0) 但显然应该是 (2.5, 1.0)。
【问题讨论】:
-
lines和pt是如何存储的?
-
看看shapely
-
这些点在 Pandas 数据框中存储为经度和纬度列,而我也可以将其转换为三列 XYZ。感谢您对匀称的提示。会去看看。
-
那么,最接近的 pt
p4将是现有数据框中的点之一,我们只需要找到它?
标签: python python-3.x numpy