我有一些坐标,我想在多边形内部创建一些随机坐标。
coords = np.random.rand(20, 2)* 2
我创建了随机坐标,但是它们在我的多边形之外。
poly= Polygon([(22.794525711443953, 39.431753895579845), (22.797156635193346,39.43552620818886), (22.79643512096834,39.4363589771401), (22.79243347988472,39.43454099778662), (22.794525711443953, 39.431753895579845)])
def point_inside_polygon(x,y,poly):
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
coords = np.random.rand(20, 2)* 2
print(coords)
答案 0 :(得分:0)
One way would be to just generate random coordinates and test if they lie into the polingon using skimage.measure.points_in_poly.
However, this could lead to useless computation and non-deterministic execution times.
A more smart way to do this is to draw your polygon on a numpy array using skimage.draw.polygon
from skimage.draw import polygon()
import numpy as np
max_size = 50 # Assuming it's square
max_vertices = 6 # length of your coord vector
coords = np.random.randint(0,high=max_size, size=[2, max_vertices])
# Here you got all the coordinates laying inside the polygon
rr, cc = skimage.draw.polygon(coords)
# Now you have to pick an element from rr and the corresponding from cc
# The simplest way is to pick its position in rr or cc
random_index = np.random.choice(list(range(len(rr))))
random_point = (rr[random_index], cc[random_index])
For the last section there are multiple choices, this is quite simple if you just want to pick coordinates using a uniform distribution.
If your data is not an image, or you need to use floats without approximations, a way to go would be to subdivide your polygon into triangles, picking a random triangle and then sampling inside that. You can refer to this post for further information.