Transforming Shapely Polygon and MultiPolygon objects

by Chris Fonnesbeck   Last Updated July 12, 2019 18:22 PM

Is there an easy way of transforming Shapely objects (namely, Polygons and MultiPolygons) from one projection to another without having to dig around and extract coordinates by hand?

In fact, I don't even care if they are Shapely objects at this point, I just want to pass features and a projection, and get a reprojected set of features back.

Does this sort of functionality exist, or must it be hand coded?



Answers 3


While shapely doesn't natively understand coordinate systems, shapely.ops.transform() can do that along with pyproj. If pyproj.Proj can understand your both of your coordinate systems, then it can be made into a function that shapely can transform with.

From the shapely docs:

from functools import partial
import pyproj
from shapely.ops import transform

project = partial(
    pyproj.transform,
    pyproj.Proj(init='epsg:4326'), # source coordinate system
    pyproj.Proj(init='epsg:26913')) # destination coordinate system

g2 = transform(project, g1)  # apply projection
Alex Kerney
Alex Kerney
December 22, 2014 22:01 PM

While not a Shapely solution, using GeoPandas allows for relatively straightforward projection. For example, if we want to convert a shapefile to ESPG 4326:

import geopandas as gpd

HabModelEnviro = gpd.GeoDataFrame.from_file('data/HabModelEnviro.shp').replace({-999: None})

HabModelEnviroWGS84 = HabModelEnviro.to_crs({'proj':'longlat', 'ellps':'WGS84', 'datum':'WGS84'})
Chris Fonnesbeck
Chris Fonnesbeck
December 23, 2014 01:42 AM

If you're using pyproj2, it's much easier to use a Transformer. Here's an example:

import pyproj
from shapely.ops import transform

project = pyproj.Transformer.from_proj(
    pyproj.Proj(init='epsg:4326'), # source coordinate system
    pyproj.Proj(init='epsg:26913')) # destination coordinate system

# g1 is a shapley Polygon

g2 = transform(project.transform, g1)  # apply projection

This is also much faster, becase pyproj does not need to recreate the projection for every point.

Nick ODell
Nick ODell
July 12, 2019 17:26 PM

Related Questions



Cartesian / Meters issue while making ellipses

Updated August 31, 2017 21:22 PM

Transform Box from SR-ORG:6630 to WGS-84 in Python

Updated February 14, 2018 02:22 AM

Resolving CRS Error in PyProj

Updated June 28, 2019 10:22 AM