Skip to content

Instantly share code, notes, and snippets.

@underchemist
Created February 15, 2020 00:56
Show Gist options
  • Save underchemist/dab01991bbde83c375f3a83e562fa2fd to your computer and use it in GitHub Desktop.
Save underchemist/dab01991bbde83c375f3a83e562fa2fd to your computer and use it in GitHub Desktop.
Segmentize shapely polygons
""" Segmentize an input shapely polygon
For an input polygon, generate a new polygon composed of n points
interpolated along the linear geometry of each vertex of the input
polygon
"""
import numpy as np
import shapely
import shapely.geometry
import shapely.ops
from more_itertools import pairwise
def segmentize_line(line, n):
step = line.length / n
starts = np.arange(0., line.length, step)
lines = [line.interpolate(start) for start in starts]
return shapely.geometry.LineString(lines)
def segmentize(polygon, n=200):
ext_ring = polygon.exterior
lines = shapely.geometry.MultiLineString(list(pairwise(ext_ring.coords)))
dense_lines = [segmentize_line(line, n=int(n/len(lines))) for line in lines]
coords = [coord for line in dense_lines for coord in line.coords]
linear_ring = shapely.geometry.LinearRing(coords)
return shapely.geometry.Polygon(linear_ring)
if __name__ == '__main__':
print('demo')
box = shapely.geometry.box(0, 0, 1, 1)
print(box)
dense_box = segmentize(box)
print(dense_box)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment