Search code examples
pythonnumpygeometryshapelypoint-in-polygon

distance from point to polygon (when inside)


I'm trying to find an efficient way to compute the distance from a point to the nearest edge of a polygon in python. I thought shapely would be perfect for this, but it only computes the distance when the point is outside the polygon. I thought about opencv, which has a built in function, but it requires integer coordinates (I can't discretize my data). The polygon is not guaranteed to be convex.


Solution

  • Use the .boundary property of the Polygon to return a LineString of the LinearRings, then use the .distance property. You can also use the .exterior property if you want only the exterior ring, and not any of the interior rings (if they exist). E.g.

    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
    

    The result is the same for .boundary and .exterior with this example, but could change for other examples.