python计算点与多边形距离的代码是什么
时间: 2024-05-06 08:21:13 浏览: 49
以下是计算点与多边形距离的 Python 代码示例:
```
import math
def point_to_line_distance(point, line):
# 计算点到线段的距离
px, py = point
x1, y1 = line[0]
x2, y2 = line[1]
dx = x2 - x1
dy = y2 - y1
if dx == dy == 0:
# 线段退化为点
return math.hypot(px - x1, py - y1)
t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy)
if t < 0:
# 超出线段左端点
return math.hypot(px - x1, py - y1)
elif t > 1:
# 超出线段右端点
return math.hypot(px - x2, py - y2)
else:
# 投影点在线段内
proj_x = x1 + t * dx
proj_y = y1 + t * dy
return math.hypot(px - proj_x, py - proj_y)
def point_to_polygon_distance(point, polygon):
# 计算点到多边形的距离
min_dist = float("inf")
for i in range(len(polygon)):
line = [polygon[i], polygon[(i+1)%len(polygon)]]
dist = point_to_line_distance(point, line)
if dist < min_dist:
min_dist = dist
return min_dist
# 使用示例
point = (2, 2)
polygon = [(0, 0), (4, 0), (4, 4), (0, 4)]
print(point_to_polygon_distance(point, polygon))
```
阅读全文