Skip to content

Instantly share code, notes, and snippets.

@nvkelso
Forked from migurski/polygonize.py
Created September 27, 2012 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvkelso/3792177 to your computer and use it in GitHub Desktop.
Save nvkelso/3792177 to your computer and use it in GitHub Desktop.
Polygonize a bag of lines
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