【问题标题】:Convex Hull and SciPy凸包和 SciPy
【发布时间】:2013-01-21 09:46:06
【问题描述】:

我正在尝试使用 scipy (0.10.1) 快速破解来可视化凸包。

我可以使用以下代码获得凸包:

vecs = [[-0.094218, 51.478927], [-0.09348,  51.479364], [-0.094218, 51.478927],
        ...
        [-0.094218, 51.478927], [-0.094321, 51.479918], [-0.094218, 51.478927],
        [-0.094222, 51.478837], [-0.094241, 51.478388], [-0.094108, 51.478116],
        [-0.09445,  51.480279], [-0.094256, 51.478028], [-0.094326, 51.500511]]
hull = scipy.spatial.Delaunay(vecs).convex_hull

生成的数组如下所示:

[[56,  9], [16,  1], [56,  1], [55,  9], [53, 55], [53, 16]]

数字是顶点索引。我的问题是它们没有排序。我需要它们按 CW 或 CCW 顺序排列,以便在 KML 中轻松可视化它们。

有没有简单的方法让 scipy.spatial 计算正确的顺时针顺序?

【问题讨论】:

    标签: python geometry scipy computational-geometry convex-hull


    【解决方案1】:

    所以这段代码似乎可以解决问题,但可能更简单...... 本质上,我首先从船体中收集顶点数。然后我计算平均值,重新定位数据集并按与平均值的角度对其进行排序。

    ps = set()
    for x, y in hull:
        ps.add(x)
        ps.add(y)
    ps = numpy.array(list(ps))
    center = vecs[ps].mean(axis=0)
    A = vecs[ps] - center
    h = vecs[ps[numpy.argsort(numpy.arctan2(A[:,1], A[:,0]))]]
    

    【讨论】:

      【解决方案2】:

      我发现了一个不错的方法,但它需要 scipy 0.11.0 (sparse.csgraph)

      这是一个完整的示例,实际排序是“sort hull ...”注释后面的 2 线。

      import numpy as np
      import scipy as sp
      
      # random point cloud and hull
      X = np.random.randint(0,200,(30,2))
      hull = sp.spatial.qhull.Delaunay(X).convex_hull
      
      # sort hull indices using (sparse) adjacency matrix graph stuff
      g = sp.sparse.csr_matrix((np.ones(hull.shape[0]),hull.T), shape=(hull.max()+1,)*2)
      sorted_hull = sp.sparse.csgraph.depth_first_order(g,hull[0,0],directed=False)[0]
      
      # display with matplotlib
      from matplotlib import pyplot as plt
      plt.plot(X[:,0],X[:,1],'.')
      plt.plot(X[sorted_hull,0],X[sorted_hull,1])
      

      【讨论】:

        【解决方案3】:

        scipy.spatial.ConvexHull 的当前开发文档 (0.13.0.dev) 中,有一个 vertices 属性,在 2D 中是逆时针方向的。

        【讨论】:

          猜你喜欢
          • 2015-10-12
          • 2020-02-16
          • 2014-09-04
          • 1970-01-01
          • 2017-07-04
          • 1970-01-01
          • 2017-03-17
          • 1970-01-01
          • 2018-11-07
          相关资源
          最近更新 更多