Numpy to VTI

I want to convert a 3D numpy array into a .vti file (folder based), that is readable by this example. So far, I’ve used:

from pyevtk.hl import imageToVTK
import numpy as np

array =  np.ones((100, 100, 100))
imageToVTK('volume', pointData={'value' : array}) 

However, this throws an error when loaded into the above example. Specifically:

Uncaught RangeError: Invalid initial number of values for array (origin)
at VolumeViewer.js:2:32778
at Array.forEach ()
at dt (VolumeViewer.js:2:32723)
at [as setGetArray] (VolumeViewer.js:2:33747)
at Gm (VolumeViewer.js:2:534212)
at Object.n [as newInstance] (VolumeViewer.js:2:37342)
at e.parseXML (VolumeViewer.js:2:757473)
at e.parseAsArrayBuffer (VolumeViewer.js:2:754916)
at rS (VolumeViewer.js:2:770730)
at n.onload (VolumeViewer.js:2:772413)

How can I create the .vti file correctly ?

imageToVTK produce a valid VTI but the file is not guaranty to work with the JS reader due to Byte alignment. If you use the VTK XML writer, you should prefer the Appended format with zlib compression.

Could you give an example of how to use the VTK XML writer in that context? I can’t find examples or helpful docs. The only thing I found is this, which doesn’t tell me how to use it.

Those would be the methods to call on that writer.


Thank you! here’s the full code snipped that worked for me!

# Fill the image data with your numpy array
path = "/path/to/volume.npy"

numpy_array = np.load(path)  
dim = numpy_array.shape

# Create a VTK image data object
image_data = vtk.vtkImageData()
image_data.SetDimensions(dim[0], dim[1], dim[2])
image_data.AllocateScalars(vtk.VTK_FLOAT, 1)

vtk_array = numpy_support.numpy_to_vtk(numpy_array.ravel(), deep=True, array_type=vtk.VTK_FLOAT)

# Write the image data to a VTI file
writer = vtk.vtkXMLImageDataWriter()
1 Like