python - 将一个点捕捉到一条线的最近部分?

标签 python python-2.7 math trigonometry snapping

我有一个带有 Python 2.7 的工单管理系统。


系统有线有点:

Line Vertex 1: 676561.00, 4860927.00
Line Vertex 2: 676557.00, 4860939.00

Point 100: 676551.00, 4860935.00
Point 200: 676558.00, 4860922.00

我想将点对齐到线的最近部分。

Snapping can be defined as:

Moving a point so that it coincides exactly with the closest part of a line.

enter image description here


似乎有两种不同的数学场景在起作用:

一个。线的最近部分是沿线的位置,其中点垂直于线

B.或者,线的最近部分只是最近的顶点

enter image description here


是否可以使用 Python 2.7(和标准 2.7 库)将一个点捕捉到一条线的最近部分?

最佳答案

这是一个 extremely helpful资源。

import collections
import math

Line = collections.namedtuple('Line', 'x1 y1 x2 y2')
Point = collections.namedtuple('Point', 'x y')


def lineLength(line):
  dist = math.sqrt((line.x2 - line.x1)**2 + (line.y2 - line.y1)**2)
  return dist


## See http://paulbourke.net/geometry/pointlineplane/
## for helpful formulas

## Inputs
line = Line(0.0, 0.0, 100.0, 0.0)
point = Point(50.0, 1500)

## Calculations
print('Inputs:')
print('Line defined by: ({}, {}) and ({}, {})'.format(line.x1, line.y1, line.x2, line.y2))
print('Point "P": ({}, {})'.format(point.x, point.y))

len = lineLength(line)
if (len == 0):
  raise Exception('The points on input line must not be identical')

print('\nResults:')
print('Length of line (calculated): {}'.format(len))

u = ((point.x - line.x1) * (line.x2 - line.x1) + (point.y - line.y1) * (line.y2 - line.y1)) / (
    len**2)

# restrict to line boundary
if u > 1:
  u = 1
elif u < 0:
  u = 0

nearestPointOnLine = Point(line.x1 + u * (line.x2 - line.x1), line.y1 + u * (line.y2 - line.y1))
shortestLine = Line(nearestPointOnLine.x, nearestPointOnLine.y, point.x, point.y)

print('Nearest point "N" on line: ({}, {})'.format(nearestPointOnLine.x, nearestPointOnLine.y))
print('Length from "P" to "N": {}'.format(lineLength(shortestLine)))

关于python - 将一个点捕捉到一条线的最近部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60574855/

相关文章:

python - Beautiful Soup (bs4) 如何只匹配一个,而且只有一个,css 类

python - 如何在 Python 中将嵌套列表转换为一维列表?

python - 结果不正确的异常数学?

algorithm - 做一个算法,但我的智商太低了

python - 使用 buildout 安装 OpenERP 服务器时出现问题!

python - 在 int 值之后对 str 进行排序(Python、JSON)

python装饰函数调用

Python 属性返回属性对象

python - 断言一个元素不存在 python Selenium

c# - 如何预测船舶与人体在二维影响范围内的相遇