使用Python在网格上生成均匀分布的点吗?

时间:2018-10-31 20:21:57

标签: python pandas

我正在尝试在多边形内绘制n个均匀间隔的点,该点是下面在Google地图上显示的站点。现在,我已经使用gmplot做到了这一点。

Google Map

我的目标是在多边形内部创建点网格。

我最近的方法是使用np.meshgrid,然后从网格中选择随机点。以下是我用来获取积分的代码。但是结果不是我所期望的。

def random_points_within(poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    x = (np.linspace(min_x,max_x,1000))
    y=  (np.linspace(min_y,max_y,1000))
    xx,yy = np.meshgrid(x,y,sparse=True)
    xx=xx[0]
    points = []

    while len(points) < num_points:
        random_point = Point([random.choice(xx), random.choice(yy)])
        if (random_point.within(poly)):
            points.append(list(random_point.coords))
    print(min_x,max_x,max_y,min_y)
    return points
    #poly is a polygon created by the edges for the site

更新:

尝试遍历网格上的所有点,最终得到下面的图像。

def random_points_within(poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    x = (np.linspace(min_x,max_x,num_points))
    y=  (np.linspace(min_y,max_y,num_points))
    xx,yy = np.meshgrid(x,y,sparse=True)
    xx = xx.reshape((np.prod(xx.shape),))
    yy = yy.reshape((np.prod(yy.shape),))
    points = []

    for (x,y) in zip(xx,yy):
       random_point = Point([x, y])
       if (random_point.within(poly)):
          points.append(list(random_point.coords))
    print(min_x,max_x,max_y,min_y)
    return points,xx,yy

输出:

enter image description here

有没有办法得到均匀分布的点?

1 个答案:

答案 0 :(得分:1)

由于我无法最好地访问多边形对象,所以我只能做一个猜测:

def random_points_within(poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    x = (np.linspace(min_x,max_x,num_points))
    y=  (np.linspace(min_y,max_y,num_points))
    xx,yy = np.meshgrid(x,y,sparse=True)
    xx = xx.reshape((np.prod(xx.shape),))
    yy = yy.reshape((np.prod(yy.shape),))
    points = []

    for x in xx:
       for y in yy:
           random_point = Point([x, y])
           if (random_point.within(poly)):
              points.append(list(random_point.coords))
    print(min_x,max_x,max_y,min_y)
    return points,xx,yy

与程序相比,我所做的唯一更改是它同时在xx和yy上循环,因此您将覆盖区域而不是一行。