Skip to main content
 首页 » 编程设计

python之点到多边形的距离(在内部时)

2025年05月04日11leader

我正在尝试找到一种有效的方法来计算 python 中从一个点到最近的多边形边缘的距离。我认为 shapely 非常适合这个,但它只计算点在多边形之外时的距离。我想到了 opencv,它有一个内置函数,但它需要整数坐标(我不能离散化我的数据)。不保证多边形是凸的。

请您参考如下方法:

使用 Polygon 的 .boundary 属性返回 LinearRings 的 LineString,然后使用 .distance 属性。如果您只需要外环而不需要任何内环(如果存在),也可以使用 .exterior 属性。例如

from shapely import wkt 
poly = wkt.loads('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))') 
pt = wkt.loads('POINT(20 20)') 
 
# The point is in the polygon, so the distance will always be 0.0 
poly.distance(pt)  # 0.0 
 
# The distance is calculated to the nearest boundary 
poly.boundary.distance(pt)  # 4.47213595499958 
 
# or exterior ring 
poly.exterior.distance(pt)  # 4.47213595499958 

此示例中 .boundary 和 .exterior 的结果相同,但其他示例可能会有所不同。