python 二维点与由起点和终点指定的线段之间的最短距离。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 二维点与由起点和终点指定的线段之间的最短距离。相关的知识,希望对你有一定的参考价值。
"""
Shortest distance between a point and a line segment (using 2D-vectors)
=======================================================================
Ported to Python from javascript solution by @Grumdrig at http://bit.ly/1RW6etG
"""
from math import hypot
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
def distance(point1, point2):
"""
calculate distance between two 2-dimensional points
---------------------------------------------------
:param point1: Point(float, float)
:param point2: Point(float, float)
>>> distance(Point(1, 0), Point(0, 0))
1.0
>>> distance(Point(-30, 15), Point(20, 10))
50.24937810560445
"""
return hypot(point2.x - point1.x, point2.y - point1.y)
def dist_to_segment(point, start, end):
"""
Calculate shortest distance between 2-dimensional point and line segment
------------------------------------------------------------------------
:param point: Point(float, float) - point
:param start: Point(float, float) - start of line
:param end: Point(float, float) - end of line
>>> dist_to_segment(Point(1, 0), Point(0, 0), Point(1, 1))
0.7071067811865475
>>> dist_to_segment(Point(5, 4), Point(0, 0), Point(20, 10))
1.3416407864998738
>>> dist_to_segment(Point(30, 15), Point(0, 0), Point(20, 10))
11.180339887498949
>>> dist_to_segment(Point(-30, 15), Point(0, 0), Point(20, 10))
33.54101966249685
>>> dist_to_segment(Point(5, 1), Point(0, 0), Point(10, 0))
1.0
>>> dist_to_segment(Point(1, 5), Point(0, 0), Point(0, 10))
1.0
"""
length = distance(start, end)
if length == 0:
return distance(point, start)
pct = ((point.x - start.x) * (end.x - start.x) +
(point.y - start.y) * (end.y - start.y)) / length ** 2
if pct < 0:
return distance(point, start)
if pct > 1:
return distance(point, end)
return distance(point, Point(start.x + (end.x - start.x) * pct,
start.y + (end.y - start.y) * pct))
if __name__ == '__main__':
import doctest
doctest.testmod()
以上是关于python 二维点与由起点和终点指定的线段之间的最短距离。的主要内容,如果未能解决你的问题,请参考以下文章
POJ 1556 The Doors 线段交 dijkstra
最短路+线段交 POJ 1556 好题
线段线段
WebGL 高级技术
photoshop钢笔使用技巧?
德莱联盟 计算几何 线段相交