Skip to content

Instantly share code, notes, and snippets.

Created January 27, 2012 16:57
What would you like to do?
Mersh.txt requirements file for pip
# Example of using Fiona, pyproj, and Shapely together. Install all of them like this:
# $ pip install -r
import logging
import sys
from fiona import collection
from pyproj import Proj, transform
from shapely.geometry import mapping, shape
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
p_in = Proj(
with collection(
"with-pyproj-shapely.shp", "w", "ESRI Shapefile",
crs={'init': "epsg:27700", 'no_defs': True}
) as output:
p_out = Proj(
for f in input:
# Transform the feature geometries.
assert f['geometry']['type'] == "Polygon"
new_coords = []
for ring in f['geometry']['coordinates']:
x2, y2 = transform(p_in, p_out, *zip(*ring))
new_coords.append(zip(x2, y2))
f['geometry']['coordinates'] = new_coords
# Ensure that they are valid and "clean".
geom = shape(f['geometry'])
if not geom.is_valid:
clean = geom.buffer(0.0)
assert clean.is_valid
assert clean.geom_type == 'Polygon'
geom = clean
f['geometry'] = mapping(geom)
except Exception, e:
# Writing uncleanable features to a different shapefile
# is another option.
"Error transforming or cleaning feature %s:", f['id'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment