沿多边形边界随机采样点

2024-04-08

I am trying to randomly sample points on a polygon boundary made of arbitrary number of points. The polygon consist of a set of x,y coordinates. I would like to keep the original vertices of the polygon as well as add the randomly sampled points, and preserve the shape of the polygon as much as possible. As shown in this example, given an orginal polygon (blue vertices, left), I want a randomly sampled polygon with N=25 points along the original polygon's boundary (red vertices, right). enter image description here

下面的代码是我尝试使用样条插值来执行此操作,但插值的结果最终会显着扭曲多边形的形状(使其更圆),特别是如果多边形一开始就有少量顶点。

def single_parametric_interpolate(obj_x_loc,obj_y_loc,numPts=50):
    '''
    Interpolate a single given bounding box obj_x_loc,obj_y_loc
    return a new set of coordinates interpolated on numPts 
    '''
    tck, u =splprep(np.array([obj_x_loc,obj_y_loc]),s=0,per=1)
    u_new = np.linspace(u.min(),u.max(),numPts)
    new_points = splev(u_new, tck,der=0)
    return new_points

有没有更好的方法来进行这种类型的采样,并且不会扭曲多边形的最终形状?


你可以计算周长p多边形的形状(边长之和)。选择一个角,得到一个随机数r in [0,p[然后“走”这段距离r沿着例如的周边逆时针方向并在那里放置一个点。

def single_parametric_interpolate(obj_x_loc,obj_y_loc,numPts=50):
    n = len(obj_x_loc)
    vi = [[obj_x_loc[(i+1)%n] - obj_x_loc[i],
         obj_y_loc[(i+1)%n] - obj_y_loc[i]] for i in range(n)]
    si = [np.linalg.norm(v) for v in vi]
    di = np.linspace(0, sum(si), numPts, endpoint=False)
    new_points = []
    for d in di:
        for i,s in enumerate(si):
            if d>s: d -= s
            else: break
        l = d/s
        new_points.append([obj_x_loc[i] + l*vi[i][0],
                           obj_y_loc[i] + l*vi[i][1]])
    return new_points
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

沿多边形边界随机采样点 的相关文章

随机推荐