| 1 |
import logging |
| 2 |
import sys |
| 3 |
|
| 4 |
from shapely.geometry import mapping, shape |
| 5 |
|
| 6 |
import fiona |
| 7 |
|
| 8 |
logging.basicConfig(stream=sys.stderr, level=logging.INFO) |
| 9 |
|
| 10 |
with fiona.open('docs/data/test_uk.shp', 'r') as source: |
| 11 |
|
| 12 |
# **source.meta is a shortcut to get the crs, driver, and schema |
| 13 |
# keyword arguments from the source Collection. |
| 14 |
with fiona.open( |
| 15 |
'with-shapely.shp', 'w', |
| 16 |
**source.meta) as sink: |
| 17 |
|
| 18 |
for f in source: |
| 19 |
|
| 20 |
try: |
| 21 |
geom = shape(f['geometry']) |
| 22 |
if not geom.is_valid: |
| 23 |
clean = geom.buffer(0.0) |
| 24 |
assert clean.is_valid |
| 25 |
assert clean.geom_type == 'Polygon' |
| 26 |
geom = clean |
| 27 |
f['geometry'] = mapping(geom) |
| 28 |
sink.write(f) |
| 29 |
|
| 30 |
except Exception as e: |
| 31 |
# Writing uncleanable features to a different shapefile |
| 32 |
# is another option. |
| 33 |
logging.exception("Error cleaning feature %s:", f['id']) |
| 34 |
|