gpt4 book ai didi

python - 点到线段的投影 Python Shapely

转载 作者:太空狗 更新时间:2023-10-30 02:53:34 32 4
gpt4 key购买 nike

我有一个由两点定义的 LineString,因此本质上是一条直线段,我想在其上投影一个点。我知道 .project.interpolate。但是,当该点位于线段“外部”时,我不想要线段上的最近点,但我想扩展该线段并绘制一条穿过该点并与(扩展)线段正交的线。我想要投影的坐标。

enter image description here

例如,如果点在线段“内”

from shapely.geometry import Point
from shapely.geometry import LineString
point = Point(0.2, 0.5)
dist = LineString([(0, 1), (1, 1)]).project(point)
list(LineString([(0, 1), (1, 1)]).interpolate(dist).coords)

有人知道当点在线段之外时该怎么办吗?

最佳答案

手动执行此操作可能最简单。如果将角度 x - u - v 表示为 alpha,则

cos(alpha) = (v - u).(x - u) / (|x - u|*|v - u|)

其中.表示点积,| | 表示欧氏范数。P(x)u 的距离 d 因此是:

d = cos(alpha)*|x - u| = (v - u).(x - u) / |v - u|

计算出 d 后,投影点 P(x) 便可轻松获得:

P(x) = u + d*(v - u)/|v - u|

实现:

import numpy as np
from shapely.geometry import Point
from shapely.geometry import LineString

point = Point(0.2, 0.5)
line = LineString([(0, 1), (1, 1)])

x = np.array(point.coords[0])

u = np.array(line.coords[0])
v = np.array(line.coords[len(line.coords)-1])

n = v - u
n /= np.linalg.norm(n, 2)

P = u + n*np.dot(x - u, n)
print(P) #0.2 1.

关于python - 点到线段的投影 Python Shapely,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061521/

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