文章目录
- 初步认识
- 构造函数和属性
- 实战-画个球
 
初步认识
对于熟悉matplotlib三维画图的人来说,最常用的应该是plot_surface,但这个函数的绘图逻辑是,将xy平面映射到z轴,所以没法一次性绘制球,只能把球分成两半,上半球和下半球分别绘制。
如果想一次性绘制封闭图形,则可通过tri_surface,其绘图逻辑便是将图形拆分成一个个三角面,然后在对这些三角面进行绘制。所以,将一个曲面拆分成三角面,便构成了一个非常现实的问题,德劳内三角剖分便是建立在这个问题背景之下的。
scipy.spatial中提供了Delaunay类,下面以二维散点为例,来初步认识一下。
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
pts = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])
tri = Delaunay(pts)
plt.triplot(pts[:,0], pts[:,1], tri.simplices)
plt.plot(pts[:,0], pts[:,1], 'o')
plt.show()
效果如下

构造函数和属性
Delaunay的构造函数如下
Delaunay(points, furthest_site=False, incremental=False, qhull_options=None)
各参数含义为
- points输入散点
- furthest_site为- True时,计算最远点
- incremental为- True时,允许增量添加点
- qhull_options为- qhull参数,具体可参考qhull
在Delaunay对象中,有下面几个必须知道的常用属性
- points即输入的点集
- simplices三角面顶点在点集中的序号
- neighbors三角面相邻三角面的序号
- equations三角面方程
实战-画个球
想要画个球,第一步是要得到一个球
# N为点数
def getBall(N):
    pts = []
    while len(pts) < N:
        while True:
            u = np.random.uniform(-1, 1)
            v = np.random.uniform(-1, 1)
            r2 = u**2 + v**2
            if r2 < 1:
                break
        x = 2*u*np.sqrt(1-r2)
        y = 2*v*np.sqrt(1-r2)
        z = 1 - 2*r2
        pts.append((x,y,z))
    return np.vstack(pts)
下面测试一下
pts = getBall(200)
ax = plt.subplot(projection='3d')
ax.scatter(pts[:,0], pts[:,1], pts[:,2])
plt.show()  

接下来将这些随机点生成三角面,并进行绘图
tri = Delaunay(pts)
ax = plt.subplot(projection='3d')
for i in tri.simplices:
    ax.plot_trisurf(pts[i, 0], pts[i, 1], pts[i,2])
plt.show()
效果如下

 看上去花花绿绿的这些三角形,便是通过德劳内三角剖分得到的,其equations属性可以查看这些三角面的方程参数
>>> tri.equations
array([[-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16],
       [-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16],
       [-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16],
       ...,
       [-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16],
       [-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16],
       [-2.35739179e-16, -1.64155539e-15, -1.54600295e-15,
        -1.00000000e+00,  2.41181971e-16]])
``



















