python - 离散凸包

标签 python discrete-mathematics convex-hull convex

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

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

最佳答案

您仍然可以使用 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()

enter image description here

关于python - 离散凸包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50809434/

相关文章:

regex - 我如何构建这个有限自动机?

c++ - OpenCV C++ cv::convexityDefects 错误

python - Django 单元测试和模拟请求模块

python - 如何在多索引 Pandas 中按次日值填充缺失值?

python - pycharm """:return :"""in a Python documentation string

python - 使用Psychopy和/或PyGame在Python中播放声音

algorithm - 哥伦布序列

discrete-mathematics - 完整新手的一阶逻辑(书籍推荐)?

geopandas - 如何将凸包顶点转换为 geopandas 多边形

algorithm - 是否有用于查找复杂多边形凸包的线性时间算法?