【问题标题】:Discrete Convex Hull离散凸包
【发布时间】:2018-11-21 09:28:41
【问题描述】:

在python中,给定n x n网格中的m个随机点,我如何计算一个(大致)凸包,其中只能使用离散网格上的点而不是连续点来创建包?

像 scipy.spatial 这样的模块只给出连续的凸包,其中连接顶点的线是纯代数的,但我想要一个边界是离散的近似凸包。

【问题讨论】:

    标签: python discrete-mathematics convex-hull convex


    【解决方案1】:

    你仍然可以使用 qhull + 一些后期处理:

    import numpy as np
    from scipy.spatial import ConvexHull
    
    # https://stackoverflow.com/a/47705495/7207392
    def connect2(ends):
        d0, d1 = np.diff(ends, axis=0)[0]
        if np.abs(d0) > np.abs(d1): 
            return np.c_[np.arange(ends[0, 0], ends[1,0] + np.sign(d0), np.sign(d0), dtype=np.int32),
                         np.full(np.abs(d0)+1, ends[0, 1]) if d1==0 else
                         np.arange(ends[0, 1] * np.abs(d0) + np.abs(d0)//2,
                                   ends[0, 1] * np.abs(d0) + np.abs(d0)//2 + (np.abs(d0)+1) * d1, d1, dtype=np.int32) // np.abs(d0)]
        else:
            return np.c_[np.full(np.abs(d1)+1, ends[0, 0]) if d0==0 else
    np.arange(ends[0, 0] * np.abs(d1) + np.abs(d1)//2,
                                   ends[0, 0] * np.abs(d1) + np.abs(d1)//2 + (np.abs(d1)+1) * d0, d0, dtype=np.int32) // np.abs(d1),
                         np.arange(ends[0, 1], ends[1,1] + np.sign(d1), np.sign(d1), dtype=np.int32)]
    
    def dch(points):
        ch = ConvexHull(points)
        n = len(ch.vertices)
        return np.concatenate([connect2(points[ch.vertices[[i, (i+1)%n]]])[:-1] for i in range(n)], axis=0)
    
    points = np.argwhere(np.random.random((24, 24)) < 0.03)
    import pylab
    pylab.plot(*dch(points).T, 'bo')
    pylab.plot(*points.T, 'rd')
    pylab.show()
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2014-07-19
        • 2017-04-21
        • 2017-04-29
        • 2018-07-07
        • 2019-08-22
        • 2017-02-24
        • 1970-01-01
        • 2014-06-29
        • 2020-12-21
        相关资源
        最近更新 更多