我有一个带有 Python 2.7 的工单管理系统。
- 在系统中,只能使用standard Python 2.7 library 中包含的库。 (无法导入其他库)。
系统有线有点:
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.
似乎有两种不同的数学场景在起作用:
一个。线的最近部分是沿线的位置,其中点垂直于线。
B.或者,线的最近部分只是最近的顶点。
是否可以使用 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/