Python VTK 绘制等高线初步
代码,
import vtk
def create_data():
points = vtk.vtkPoints()
for x in range(0, 10):
for y in range(0, 10):
points.InsertNextPoint(x, y, x + y)
polys = vtk.vtkCellArray()
for x in range(0, 9):
for y in range(0, 9 - x):
polys.InsertNextCell(4)
polys.InsertCellPoint(x * 10 + y)
polys.InsertCellPoint(x * 10 + y + 1)
polys.InsertCellPoint((x + 1) * 10 + y + 1)
polys.InsertCellPoint((x + 1) * 10 + y)
#dataset = vtk.vtkDataSet.GetData()
dataset = vtk.vtkPolyData()
#dataset = vtk.vtkImageData()
dataset.SetPoints(points)
#dataset.SetPolys(polys)
return dataset
def create_contours(input_data, value):
contourFilter = vtk.vtkContourFilter()
contourFilter.SetInputData(input_data)
contourFilter.SetValue(0, value)
contourFilter.Update()
return contourFilter.GetOutput()
def render_contours(contours):
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(contours)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
renderer.SetBackground(0, 0, 0)
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindow.SetSize(640, 480)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderWindow.Render()
renderWindowInteractor.Start()
if __name__ == '__main__':
data = create_data()
contours = create_contours(data, 50.0)
render_contours(contours)
运行,没绘制出来,只出来一个空的屏幕;
先大概看一下代码;
它首先是生成示例数据;往数据集里面加了点和线;
一开始它的代码是这样,dataset = vtk.vtkDataSet.GetData(),报错了;
然后改成, dataset = vtk.vtkPolyData(),不会报错,但没绘制东西;
如果是这样,dataset = vtk.vtkImageData(),也报错;
根据资料,vtk的python的数据集类型有如下几种,
vtkImageData,vtkPolyData,vtkRectilinearGrid,vtkStructuredGrid,vtkUnstructuredGrid,vtkUnstructuredPoints;
光有数据还不能绘制等高线,还要定义等值线过滤器,设置其数值,
contourFilter.SetInputData(input_data)
contourFilter.SetValue(0, value)
把输入数据设置给等值线过滤器,设置过滤器的数值;
一开始value设置的是50,没有绘制出来,一开始设置的点的数值范围是在10左右,把value改为10, 或15,也不会绘制;
其他的代码就是基本的渲染流程;
先初步了解一下,有时间继续;