Alpha中的Alpha形状

时间:2014-10-10 16:23:59

标签: python numpy convex-hull convex concave-hull

除了CGAL python绑定之外,python中的3维中是否存在“alpha形状”函数?

或者,有没有办法将下面的例子扩展到3D?

2D示例:draw a smooth polygon around data points in a scatter plot, in matplotlib

我目前正在使用此ConvexHull示例计算音量,但就我的目的而言,由于“凸”约束,音量会膨胀。

谢谢,

2 个答案:

答案 0 :(得分:2)

我写了一些代码来查找alpha形状的表面。我希望这会有所帮助。

from scipy.spatial import Delaunay
import numpy as np
from collections import defaultdict

def alpha_shape_3D(pos, alpha):
    """
    Compute the alpha shape (concave hull) of a set of 3D points.
    Parameters:
        pos - np.array of shape (n,3) points.
        alpha - alpha value.
    return
        outer surface vertex indices, edge indices, and triangle indices
    """

    tetra = Delaunay(pos)
    # Find radius of the circumsphere.
    # By definition, radius of the sphere fitting inside the tetrahedral needs 
    # to be smaller than alpha value
    # http://mathworld.wolfram.com/Circumsphere.html
    tetrapos = np.take(pos,tetra.vertices,axis=0)
    normsq = np.sum(tetrapos**2,axis=2)[:,:,None]
    ones = np.ones((tetrapos.shape[0],tetrapos.shape[1],1))
    a = np.linalg.det(np.concatenate((tetrapos,ones),axis=2))
    Dx = np.linalg.det(np.concatenate((normsq,tetrapos[:,:,[1,2]],ones),axis=2))
    Dy = -np.linalg.det(np.concatenate((normsq,tetrapos[:,:,[0,2]],ones),axis=2))
    Dz = np.linalg.det(np.concatenate((normsq,tetrapos[:,:,[0,1]],ones),axis=2))
    c = np.linalg.det(np.concatenate((normsq,tetrapos),axis=2))
    r = np.sqrt(Dx**2+Dy**2+Dz**2-4*a*c)/(2*np.abs(a))

    # Find tetrahedrals
    tetras = tetra.vertices[r<alpha,:]
    # triangles
    TriComb = np.array([(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)])
    Triangles = tetras[:,TriComb].reshape(-1,3)
    Triangles = np.sort(Triangles,axis=1)
    # Remove triangles that occurs twice, because they are within shapes
    TrianglesDict = defaultdict(int)
    for tri in Triangles:TrianglesDict[tuple(tri)] += 1
    Triangles=np.array([tri for tri in TrianglesDict if TrianglesDict[tri] ==1])
    #edges
    EdgeComb=np.array([(0, 1), (0, 2), (1, 2)])
    Edges=Triangles[:,EdgeComb].reshape(-1,2)
    Edges=np.sort(Edges,axis=1)
    Edges=np.unique(Edges,axis=0)

    Vertices = np.unique(Edges)
    return Vertices,Edges,Triangles

答案 1 :(得分:0)

您正在寻找“凹面船体”。 marching cube algorithm可用于查找这种船体。您可以找到a full example here

局限性:如果您的数据来自于体积数据集,或者您具有可以轻松转换为体积数据集(类似体素)的点云,则此方法效果很好。例如,使用scipy cKDTree之类的空间索引器,可以使用一组密集的点相对容易地完成此操作,但是如果您的云比较稀疏,您可能最终会挠头以取得好结果点。