向一个线段Python Shapely投射一个点

问题描述 投票:3回答:1

我有一个由两个点定义的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)

任何人都知道当该点在该段之外时该怎么做?

python gis point projection shapely
1个回答
3
投票

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

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

其中.表示点积,| |表示欧几里德范数。因此,来自dP(x)的距离u是:

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.
© www.soinside.com 2019 - 2024. All rights reserved.