Reading GIFTI file in Python

Hi,

I’m currently trying to develop an extension for 3D Slicer to read, import and convert GIFTI images. I’m developing this module in Python and I’m currently using nibabel to read the gifti files (both containing surfaces - .surf.gii or labels - label.gii) (Neuroimaging in Python — NiBabel 5.1.0 documentation). As ITK is already installed within 3D Slicer, from a conversation that I had with Andras Lasso, I was wondering if it’s possible to read GIFTI files using ITK in Python. I was reading the documentation from SimpleITK but I didn’t find anything useful as I don’t see that GIFTI is supported here: Reading and Writing for Images and Transforms — SimpleITK 1.2.0.dev documentation

So does anyone know if it’s possible to read GIFTI files using ITK in Python? Thanks in advance for any help.
-Mauricio

I’ve tried asking bing chat about this and it created this code that works well in 3D Slicer (after pip-installing itk):

import itk

MeshType = itk.Mesh[itk.F, 3]
reader = itk.MeshFileReader[MeshType].New()
meshIO = itk.GiftiMeshIO.New()
reader.SetMeshIO(meshIO)
reader.SetFileName("/path/to/mymesh.gii")
reader.Update()
mesh = reader.GetOutput()

writer = itk.MeshFileWriter[MeshType].New()
writer.SetFileName("/path/to/mymesh.vtk")
writer.SetInput(mesh)
writer.Update()

A few questions remain:

  • Is the GIFTI reader available in SimpleITK? (SimpleITK is already bundled with Slicer, so it would be nice to use it instead of installing an additional Python package)
  • Is there a converter from ITK mesh (itk.itkMeshBasePython.itkMeshF3) type to VTK mesh (vtkmodules.vtkCommonDataModel.vtkPolyData) so that we can visualize the mesh using VTK without file writing&reading?

ITKMeshToPolyData is meant to work with vtk.js. Potentially look at the code there, this post, or this code.

1 Like

Thank you @dzenanz (and sorry for the slow response). Your examples indicate that there is no ITK/VTK mesh converter available in Python, but it could be implemented similarly as it was done in C++ and for JavaScript.

Just for future reference, such conversion between ITK image ↔ VTK image already exist in ITK Python wrapping extras, so if somebody implements ITK mesh ↔ VTK polydata conversion then it could be added to the same place.

1 Like

Bing did a pretty good job!]

But we can also be simpler / more pythonic:

import itk

mesh = itk.meshread('/path/to/mymesh.gii')
itk.meshwrite(mesh, '/path/to/mymesh.vtk')

which is outlined in this documentation. This also includes a a reference to numpy.ndarray / itk.Mesh conversion. itk.PolyData and vtkPolyData could be implemented in a simple function where @lassoan suggests in the same way.