Created
April 25, 2012 22:16
-
-
Save migurski/2493940 to your computer and use it in GitHub Desktop.
Polygonize a bag of lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import argv | |
from shapely.ops import polygonize | |
from shapely.geometry import asShape, LineString | |
import json | |
if __name__ == '__main__': | |
input = argv[1] | |
input = json.load(open(input)) | |
lines = [] | |
for feat in input['features']: | |
shape = asShape(feat['geometry']) | |
geoms = hasattr(shape, 'geoms') and shape.geoms or [shape] | |
for part in geoms: | |
coords = list(part.coords) | |
for (start, end) in zip(coords[:-1], coords[1:]): | |
lines.append(LineString([start, end])) | |
areas = polygonize(lines) | |
output = dict(type='FeatureCollection', features=[]) | |
for (index, area) in enumerate(areas): | |
feature = dict(type='Feature', properties=dict(index=index)) | |
feature['geometry'] = area.__geo_interface__ | |
output['features'].append(feature) | |
json.dump(output, open(argv[2], 'w')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment