在vs中配置好vtk之后,新建项目,然后加入如下代码。
#include "stdafx.h"
#include <vtkAutoInit.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkRenderingFreeType);
VTK_MODULE_INIT(vtkInteractionStyle);
#include "vtkVolume16Reader.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkMarchingCubes.h"
#include "vtkStripper.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkCamera.h"
//#include "vtkBoxWidget.h"
#include "vtkPolyData.h"
#include <iostream>
#include "vtkContourFilter.h"
#include "vtkPolyDataWriter.h"
#include "vtkSTLWriter.h"
#include "vtkDICOMImageReader.h"
#include "vtkOBJExporter.h"
int main()
{
//读取二维切片数据序列
vtkSmartPointer<vtkDICOMImageReader> reader;
reader = vtkSmartPointer<vtkDICOMImageReader>::New();//读取Dicom图片
reader->SetDataByteOrderToLittleEndian();
reader->SetDirectoryName("D:\\document\\measurement\\DICOM");
reader->Update();
//抽取等值面为骨头的信息
vtkMarchingCubes *boneExtractor = vtkMarchingCubes::New();
boneExtractor->SetInputConnection(reader->GetOutputPort());
boneExtractor->SetValue(0, 500); //设置提取的等值信息
//剔除旧的或废除的数据单元,提高绘制速度
vtkStripper *boneStripper = vtkStripper::New(); //三角带连接
boneStripper->SetInputConnection(boneExtractor->GetOutputPort());
//建立映射
vtkPolyDataMapper *boneMapper = vtkPolyDataMapper::New();
boneMapper->SetInputConnection(boneStripper->GetOutputPort());
//建立角色
vtkActor *bone = vtkActor::New();
bone->SetMapper(boneMapper);
bone->GetProperty()->SetDiffuseColor(.1, .94, .52);
bone->GetProperty()->SetSpecular(.3);
bone->GetProperty()->SetSpecularPower(20);
//定义绘制器
vtkRenderer *aRenderer = vtkRenderer::New();
//定义绘制窗口
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(aRenderer);
//定义窗口交互器
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
//创建一个camera
vtkCamera *aCamera = vtkCamera::New();
aCamera->SetViewUp(0, 0, -1);
aCamera->SetPosition(0, 1, 0);
aCamera->SetFocalPoint(0, 0, 0);
aRenderer->AddActor(bone);
aRenderer->SetActiveCamera(aCamera);
aRenderer->ResetCamera();
aCamera->Dolly(1.5);
aRenderer->SetBackground(0, 0, 0);
aRenderer->ResetCameraClippingRange();
//保存VTK文件
//vtkSmartPointer<vtkPolyDataWriter> vtkWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
//vtkWriter->SetInputData(boneExtractor->GetOutput());
//vtkWriter->SetFileName("test.vtk");
//vtkWriter->Write();
/*
以下测试保存为obj格式的文件
*/
vtkSmartPointer<vtkOBJExporter> porter = vtkSmartPointer<vtkOBJExporter>::New();
porter->SetFilePrefix("D:\\download\\PolyDataWriter");
porter->SetInput(renWin);
porter->Write();
iren->Initialize();
iren->Start();
reader->Delete();
iren->Delete();
return 0;
}