在另一条直线的一点画定长的垂线

Draw perpendicular line of fixed length at a point of another line

我有两个点A (10,20) 和B (15,30)。这些点生成直线 AB。我需要在 Python 中的 B 点上绘制一条长度为 6(每个方向 3 个单位)的垂直线 CD。

我已经使用以下代码获得了 AB 线的一些属性:

from scipy import stats
x = [10,15]
y = [20,30]
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

如何计算C和D的位置。我需要它们的X和Y值。

C 和 D 的值将用于使用 Shapely 库完成另一个 objective。

如果slope是AB的斜率,那么CD的斜率就是-1/slope。这等于垂直变化超过水平变化:dy/dx = -1/slope。这给出了 dx = -slope*dx。根据勾股定理,你有 3**2 = dy**2+dx**2。替换 dx,您将得到

3**2 = (-slope*dy)**2+dy**2
3**2 = (slope**2 + 1)*dy**2
dy**2 = 3**2/(slope**2+1)
dy = math.sqrt(3**2/(slope**2+1))

那么就可以获得dx = -slope*dy。最后,您可以使用 dxdy 来获取 C 和 D。因此代码为:

import math
dy = math.sqrt(3**2/(slope**2+1))
dx = -slope*dy
C[0] = B[0] + dx
C[1] = B[1] + dy
D[0] = B[0] - dx
D[1] = B[1] - dy

(注意math.sqrtreturns虽然只有一个数,但一般有正负平方根之分,C对应正平方根,D对应负平方根)

您可能应该使用向量来计算点的位置。

  • 创建 vector AB
  • 计算其normalized perpendicular
  • 将这个加减 3 倍到 B

在简单、可重复使用的帮助下 Vector class,计算很简单,读起来像英文:

找到与点 B 距离 3 的垂直于 AB 的点:
P1 = B + (B-A).perp().normalized() * 3 P2 = B + (B-A).perp().normalized() * 3

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def dot(self, other):
        return self.x * other.x + self.y * other.y
    def norm(self):
        return self.dot(self)**0.5
    def normalized(self):
        norm = self.norm()
        return Vector(self.x / norm, self.y / norm)
    def perp(self):
        return Vector(1, -self.x / self.y)
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    def __str__(self):
        return f'({self.x}, {self.y})'


A = Vector(10, 20)
B = Vector(15, 30)

AB = B - A  
AB_perp_normed = AB.perp().normalized()
P1 = B + AB_perp_normed * 3
P2 = B - AB_perp_normed * 3

print(f'Point{P1}, and Point{P2}')

输出:

Point(17.683281572999746, 28.658359213500127), and Point(12.316718427000252, 31.341640786499873)

既然你有兴趣使用Shapely,我能想到的最简单的获得垂直线的方法是使用parallel_offset方法获得两条平行线到AB,并连接它们的端点:

from shapely.geometry import LineString

a = (10, 20)
b = (15, 30)
cd_length = 6

ab = LineString([a, b])
left = ab.parallel_offset(cd_length / 2, 'left')
right = ab.parallel_offset(cd_length / 2, 'right')
c = left.boundary[1]
d = right.boundary[0]  # note the different orientation for right offset
cd = LineString([c, d])

CD坐标:

>>> c.x, c.y
(12.316718427000252, 31.341640786499873)
>>> d.x, d.y
(17.683281572999746, 28.658359213500127)