Last active
February 22, 2024 21:26
-
-
Save ChocopieKewpie/fb08254ee82834fc36c90d0cef7f259b to your computer and use it in GitHub Desktop.
Generating Voronoi in a Polygon
This file contains hidden or 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
import geopandas as gpd | |
from shapely.ops import voronoi_diagram | |
from shapely.ops import unary_union | |
from shapely.geometry import shape | |
import random | |
def generate_voronoi_plot(df, n_points): | |
# Read GeoDataFrame from file | |
# Extract geometry for clipping | |
clip_df = df.loc[0, 'geometry'] | |
# Sample points and create Voronoi diagram | |
points = df['geometry'].sample_points(n_points) | |
points = [shape(geometry) for geometry in points] | |
mp = unary_union(points) | |
vor = gpd.GeoDataFrame(gpd.GeoSeries(voronoi_diagram(mp, envelope=clip_df))).set_geometry(0).explode() | |
# Clip Voronoi diagram | |
vor = gpd.clip(vor, clip_df, keep_geom_type=True).set_crs(df.crs.to_epsg()) | |
# Generate random values | |
def generate_random(): | |
return random.randint(0, 1) | |
# Use the assign method to create a new column filled with random values | |
vor = vor.assign(val=[generate_random() for _ in range(len(vor))]) | |
vor=vor.dissolve('val') | |
return vor | |
# Plot the Voronoi diagram | |
# Call the function with the file path | |
df=gpd.read_file('input.gpkg') #Only tested with a geopackage that contains only 1 polygon | |
n_points=75 | |
shapes=generate_voronoi_plot(df, n_points) | |
shapes.to_file('output.gpkg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably pass a .dissolve() at the end to make it easier for benchmarking later