pythonlinepolygongeopandasshapely

Straighten a Polygon into a line with Geopandas/Shapely


I'm using Python. geopandas and shapelly to process the geometries of a road intersection.

The geojson has a list of Polygons that I want to straighten into Lines, something like this:

enter image description here

Does anyone know how to achieve that?


Solution

  • The library pygeoops uses shapely under the hood to calculate a centerline of a polygon: pygeoops.centerline. It also supports geopandas GeoSeries as input.

    You can use the parameters of centerline to finetune the removal of short branches, the simplify of the result,... to optimize the "cleaning" of the result.

    Sample script:

    import pygeoops
    import shapely
    
    poly = shapely.from_wkt("POLYGON ((0 0, 0 8, -2 10, 4 10, 2 8, 2 2, 10 2, 10 0, 0 0))")
    centerline = pygeoops.centerline(poly)
    
    # Centerlines for polygons in a geopandas GeoDataFrame
    gdf = gpd.GeoDataFrame([{"name": "L-shape", "geometry": poly}], crs="epsg:31370")
    gdf.geometry = pygeoops.centerline(gdf.geometry)
    

    Result:

    enter image description here

    Disclaimer: I'm the developer of pygeoops