如何将3D vtkDataSet转换为numpy数组?

时间:2012-10-05 22:42:31

标签: python numpy vtk

我正在尝试阅读一系列DICOM文件并将其渲染为3D模型。我已经完成了这个。但是我也希望能够在渲染之前删除某些切片。这是我迷失的地方。我无法找到一种方法来访问每个加载的文件并删除我想要的文件。我已经读过我可以将数据集转换为numpy数组。但是我不知道如何做到这一点。

    reader = vtkDICOMImageReader()
    reader.SetDirectoryName('loads a directory of DICOM files')
    reader.Update()

    imageDataGeometryFilter = vtkImageDataGeometryFilter()
    imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort())
    imageDataGeometryFilter.Update()

    mapper = vtkPolyDataMapper()
    mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort())

    '''Here is where I want to take my vtkDataSet and convert it into a numpy array.
       Once in array form I can remove data that I do not want (ie DICOM slices).
       Then I want to convert it back into a vtkDataSet to continue program.
    '''



    actor = vtkActor()
    actor.SetMapper(mapper)

    ren = vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(0.1,0.3,0.1)

    renWin = vtkRenderWindow()
    renWin.AddRenderer(ren)

    interactor = vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renWin)

    renWin.Start()

    interactor.Initialize()
    interactor.Start()

1 个答案:

答案 0 :(得分:4)

    pixelspace = reader.GetPixelSpacing()
    spacing = image.GetSpacing()

    vtk_data = image.GetPointData().GetScalars()

    numpy_data = numpy_support.vtk_to_numpy(vtk_data)

    numpy_data = numpy_data.reshape(dims[0], dims[1], dims[2])
    numpy_data = numpy_data.transpose(2,1,0)

    dims = numpy_data.shape

    dataImporter = vtkImageImport()
    dataImporter.SetDataScalarTypeToFloat() 
    dataImporter.SetNumberOfScalarComponents(1)
    dataImporter.SetDataExtent(0, dims[2]-1, 0, dims[1]-1, 0, dims[0]-1)
    dataImporter.SetWholeExtent(0, dims[2]-1, 0, dims[1]-1, 0, dims[0]-1)
    dataImporter.SetDataSpacing(spacing[0],spacing[1],spacing[2])
    dataImporter.CopyImportVoidPointer(numpy_data, numpy_data.nbytes)