项目中需要将分割结果的STL转换成Mask,以方便用户对其进行必要的调整。
vtkPolyData 转 vtkImageData 的方法见VTK官网中有相关的例子。
需要注意的几点:
1、转换后结果的数据类型和参考数据相同,如下代码中的maskImage;
2、 vtkPolyData 的数据原点(mask转polydata时)与 maskImage必须相同;
void Stl2Mask()
{
double spacing[3] = {0.71875,0.71875,1.0};
double origin[3] = { -172.64,-315.14,-355 };
int dim[3] = { 512,512,295 };
origin[0] = -dim[0] * spacing[0] * 0.5;
origin[1] = -dim[1] * spacing[1] * 0.5;
origin[2] = -dim[2] * spacing[2] * 0.5;
// 创建参考vtkImageData
vtkNew<vtkImageData> maskImage;
maskImage->SetSpacing(spacing);
maskImage->SetDimensions(dim);
maskImage->SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1);
maskImage->SetOrigin(origin);
maskImage->AllocateScalars(VTK_UNSIGNED_CHAR, 1);
void *ptrMak = maskImage->GetScalarPointer();
memset(ptrMak, 255, dim[0] * dim[1] * dim[2]);
// 读STL文件
vtkNew<vtkSTLReader> reader;
reader->SetFileName("P:\\肺.stl");
reader->Update();
// polygonal data --> image stencil:
vtkNew<vtkPolyDataToImageStencil> pol2stenc;
pol2stenc->SetInputData(reader->GetOutput());
pol2stenc->SetOutputOrigin(origin);
pol2stenc->SetOutputSpacing(spacing);
pol2stenc->SetOutputWholeExtent(maskImage->GetExtent());
pol2stenc->Update();
// cut the corresponding white image and set the background:
vtkNew<vtkImageStencil> imgstenc;
imgstenc->SetInputData(maskImage);
imgstenc->SetStencilConnection(pol2stenc->GetOutputPort());
imgstenc->ReverseStencilOff();
imgstenc->SetBackgroundValue(0);
imgstenc->Update();
// 保存
vtkImageData* outData = imgstenc->GetOutput();
void *ptrMak1 = outData->GetScalarPointer();
FILE* pFile = fopen("P:\\11\\mask.img", "wb+");
if (!pFile)
return;
fwrite(ptrMak1, 1, dim[0] * dim[1] * dim[2], pFile);
fclose(pFile);
}
1、STL
2、转换后的MASK