Search code examples
pythonnumpyvtkenthought

Trying to save vtk files with tvtk made from NumPy arrays


I'm trying to use tvtk (the package included with Enthought's Canopy) to turn some arrays into .vtk data that I can toss over to VisIt (mayavi complains on my OS (Mac OS X). I found what looked like the solution here (Exporting a 3D numpy to a VTK file for viewing in Paraview/Mayavi) but I'm not recovering the output that the author of the answer does and was wondering if anyone could tell me what I'm doing wrong. So I enter the commands in the Canopy notebook,

import numpy as np
from enthought.tvtk.api import tvtk, write_data

data = np.random.random((10,10,10))

grid = tvtk.ImageData(spacing=(10, 5, -10), origin=(100, 350, 200), 
                  dimensions=data.shape)
grid.point_data.scalars = np.ravel([], order='F')
grid.point_data.scalars.name = 'Test Data'

# Writes legacy ".vtk" format if filename ends with "vtk", otherwise
# this will write data using the newer xml-based format.
write_data(grid, '/Users/Epictetus/Documents/Dropbox/Work/vtktest.vtk')

which does create a vtk file, but unlike the output the author of the previous answer suggests, I just get a blank output,

# vtk DataFile Version 3.0
vtk output
ASCII
DATASET STRUCTURED_POINTS
DIMENSIONS 10 10 10
SPACING 10 5 -10
ORIGIN 100 350 200

Is it obvious what I'm doing wrong? File I/O has never been my forte...

Cheers!

-user2275987


Solution

  • Change the line

    grid.point_data.scalars = np.ravel([], order='F')
    

    to

    grid.point_data.scalars = data.ravel(order='F')
    

    Your grid doesn't have any data, and hence nothing is saved to the vtk file! :-)