Created
February 15, 2020 00:56
-
-
Save underchemist/dab01991bbde83c375f3a83e562fa2fd to your computer and use it in GitHub Desktop.
Segmentize shapely polygons
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
""" 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