如何在多边形内生成随机坐标?

2024-04-26 00:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些坐标,我想在多边形内创建一些随机坐标。你知道吗

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)

Tags: ifnprandomcoords多边形maxinsidepoly
1条回答
网友
1楼 · 发布于 2024-04-26 00:16:13

一种方法是生成随机坐标并使用skimage.measure.points_in_poly测试它们是否位于polingon中。你知道吗

但是,这可能会导致无用的计算和不确定的执行时间。你知道吗

更聪明的方法是使用skimage.draw.polygon在numpy数组上绘制多边形

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])

对于最后一部分,有多种选择,如果您只想使用均匀分布拾取坐标,那么这非常简单。你知道吗

如果您的数据不是图像,或者您需要使用不带近似值的浮点,一种方法是将多边形细分为三角形,随机选取一个三角形,然后在其中进行采样。有关详细信息,请参阅this post。你知道吗

相关问题 更多 >