一、效果
1.1.流形曲面
1.2.离散网格
在三维空间中的四个三角形
二、完整代码
import vtkmodules.all as vtk
import numpy as np
# 0.构造数据
vs = np.array([[-1, 1, -1], # 顶点坐标
[-1, 0, 0],
[-1, -1, -1],
[0, 0.5, 0],
[0, -0.5, 0],
[0.5, 0, -1]], dtype=np.float32) # 0.5 -0.5
faces = np.array([[4, 1, 3], [4, 1, 2], [0, 3, 1], [3, 5, 4]], dtype=np.int16) # 三角网格
c = np.array([[1, 1, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]) * 255 # 颜色
# 1.vtk创建PolyData
points = vtk.vtkPoints() # 顶点
for v in vs:
points.InsertNextPoint(v)
polys = vtk.vtkCellArray() # 三角
for f in faces:
polys.InsertNextCell(3, f)
cellColor = vtk.vtkUnsignedCharArray() # 存储颜色
cellColor.SetNumberOfComponents(3) # RGB三通道
for tmp in c:
cellColor.InsertNextTuple(tmp)
cube = vtk.vtkPolyData() # 分别添加到PolyData
cube.SetPoints(points)
cube.SetPolys(polys)
cube.GetCellData().SetScalars(cellColor)
# 1.5细分
l = vtk.vtkLinearSubdivisionFilter() # 先linear
l.SetInputData(cube)
l.SetNumberOfSubdivisions(1)
l.Update()
loop = vtk.vtkLoopSubdivisionFilter() # 后loop
loop.SetInputConnection(l.GetOutputPort())
loop.SetNumberOfSubdivisions(5)
loop.Update()
# 2.创建Mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetColorModeToDefault()
# mapper.SetInputData(cube) # 离散网格
mapper.SetInputConnection(loop.GetOutputPort()) # 细分之后的 近似曲面
# 3.创建Actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)
#actor.GetProperty().SetEdgeColor(0, 0, 0)
#actor.GetProperty().SetEdgeVisibility(1) # 显示边
# 4.创建Renderer
renderer = vtk.vtkRenderer()
renderer.SetBackground(1, 1, 1) # 背景白色
renderer.AddActor(actor) # 将actor加入
renderer.ResetCamera() # 调整显示
# 5.渲染窗口
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
renWin.Render()
# 6.交互
renWinInteractor = vtk.vtkRenderWindowInteractor()
renWinInteractor.SetRenderWindow(renWin)
renWinInteractor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
renWinInteractor.Start()
参考链接
- https://zhuanlan.zhihu.com/p/115081182 (可视化:第一个VTK例子)
- https://zhuanlan.zhihu.com/p/336743251 (VTK图像处理(二)–vtkPolyData数据处理)
- https://blog.csdn.net/shenziheng1/article/details/54836856 (VTK修炼之道45:图形进阶_vtkPolyData属性数据)