Search code examples
pythonvtk

Save .vtk voxelized file in Python


I have a 3D matrix data from a txt file representing voxels. I already represented them in vtk as a structured grid:

grid = vtk.vtkExplicitStructuredGrid()

Everything working fine. Adding color functions, actors, renderer, window... But now I want to save it as a .vtk file to read it with other applications and I don't know how. I tried:

exporter = vtk.vtkVRMLExporter()
exporter.SetRenderWindow(window)
exporter.SetFileName("sample.vtk")
exporter.Write()
exporter.Update()

But it creates a file almost empty, just with metadata and not voxels data. I tried change it for: vtkVTKExporter and didn't work too.

I also tried to use other functions calling the "grid" but didn't even created the file:

vtkXMLUnstructuredGridWriter
vtkXMLPolyDataWriter
vtkXMLUnstructuredGridWriter

And finally I tried to use:

writer = vtk.vtkStructuredPointsWriter()
windowto_image_filter = vtk.vtkWindowToImageFilter()
windowto_image_filter.SetInput(window)
windowto_image_filter.SetScale(1)  # image quality
windowto_image_filter.SetInputBufferTypeToRGBA()
writer.SetFileName('sample2.vtk')
writer.SetInputConnection(windowto_image_filter.GetOutputPort())
writer.Write()

But leads to an error.

Is there a way to save it as a .vtk file in binary with all the represented information? And also, is there a way to save the image in the vtk window created as a .jpg or .png like a screenshot. Thanks!


Solution

  • Saving grid with data: use a writer (exporter are mean to save "what is visible now", and not the underlying data).

    With vtkStructuredGrid, use vtkXMLStructureGridWriter to have a .vts file, or vtkDataSetWriter to produce legacy .vtk file. Then call writer.SetInputData(grid)

    To save screenshot, you can use vtkPNGWriter on the output of your vtkWindowToImageFilter, as describe in this example