Created
March 8, 2023 08:47
-
-
Save lucgiffon/3a3bbeaa50d1250d78c0f0d31512e12f to your computer and use it in GitHub Desktop.
Generate random element in geoseries polygon Python
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 random | |
from shapely.geometry import Point | |
def generate_random(number: int, polygon: gpd.GeoSeries): | |
""" | |
Select random point in polygon based on an inscribed circle of the polygon. | |
Parameters | |
---------- | |
number | |
Number of random points | |
polygon | |
Geoseries | |
Returns | |
------- | |
List of shapely.geometry.Point objects | |
""" | |
cx = polygon.representative_point().x | |
cy = polygon.representative_point().y | |
dist_to_repr = polygon.exterior.distance(polygon.representative_point()) | |
points = [] | |
while len(points) < number: | |
r = dist_to_repr * 0.5 * np.sqrt(random.random()) | |
theta = random.random() * 2 * np.pi | |
x = cx + r * np.cos(theta) | |
y = cy + r * np.sin(theta) | |
pnt = Point(x, y) | |
if polygon.contains(pnt).values[0]: | |
points.append(pnt) | |
return points |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment