convert nifti file to vtk polydata file

I used to convert nifti file to .vtk file but what I noticed that there are many versions.
I need # vtk DataFile Version 3.0 but this code gives me # vtk DataFile Version 4.2 .

import vtk
import sys

reader = vtk.vtkNIFTIImageReader()
reader.SetFileName(sys.argv[1])
reader.Update()
print (reader)

contour=vtk.vtkMarchingCubes()  
contour.SetInputData(reader.GetOutput())
contour.ComputeNormalsOn()
contour.ComputeGradientsOn()
contour.SetValue(0,0.1)
contour.Update()
 
# Write in vtk
triangle = vtk.vtkTriangleFilter()
triangle.SetInputConnection(contour.GetOutputPort())
triangle.PassVertsOff()
triangle.PassLinesOff()
 
decimation=vtk.vtkQuadricDecimation()
decimation.SetInputConnection(triangle.GetOutputPort())
 
clean=vtk.vtkCleanPolyData()
clean.SetInputConnection(triangle.GetOutputPort())
 
triangle2 = vtk.vtkTriangleFilter()
triangle2.SetInputConnection(clean.GetOutputPort())
triangle2.PassVertsOff()
triangle2.PassLinesOff()

#save .vtk polydata
writer = vtk.vtkPolyDataWriter()
writer.SetFileTypeToASCII()
writer.SetInputConnection(contour.GetOutputPort())
writer.SetFileName("1.vtk")
writer.Write()

what I get after runnig this code :
80367805_557148228180036_6815696929305919488_n
but what I need is 80358453_747858695691280_844619938827075584_n

if you have noticed : the 4.2 file has 9 numbers as points but the other one 3.0 has only 3 which I have this error <<Details: cannot copy sequence with size 9 to array axis with dimension 3 >> when I want to display the image.
could someone help me !!

The format of how points are written did not change. In both cases, many point coordinates are written to the file, separated by spaces or newline characters. You should implement the file parser in a way that does not assume that a certain number of values are present in a line.

sorry, could you explain more please !! Iā€™m beginner in coding python and vtk

The code snippet that you included should work fine. The generated files look valid, too.

If some software has trouble reading the file then fix that software yourself (by changing the VTK file parser so that it does not assume any particular number of values in a line) or ask the developers of that software to fix it.

Another option is to not use the legacy VTK file format anymore but use VTP, PLY, STL, OBJ, or other mesh file formats that VTK can write and that other software can read.

1 Like

sorry but when I want to calculate the curvature
this is the error : vtkCurvatures (0x27685d0): No points/cells to operate on