[vtkusers] vtk_to_numpy: how to get a vtk_array?

Paul massivemonkeymayhem at gmail.com
Mon Mar 23 11:27:23 EDT 2009

Looks like this:

import numpy
from vtk.util import numpy_support

# Reorder the data and flatten it so that it comes out in the order that VTK
expects
# NOTE that we need to keep this numpy array stored so that python doesn't
do garbage cleanup on it
# and thereby trash the VTK array as well unexpectedly (causes segfaults)

# Create a bunch of data into a numpy array. Here I use the ordering
Data[x,y,z]
Data =
numpy.array([[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]]],'f')

# Need to transpose x and z coordinate because VTK's data ordering is
different
flat_data_array = Data.transpose(2,1,0).flatten();

vtk_data_array = numpy_support.numpy_to_vtk(self.data_array)

points = image.GetPointData()
points.SetScalars(vtk_data_array)

image = vtk.vtkImageData()
image.SetDimensions(Data.shape)
image.Update()

Make sure you keep flat_data_array alive in your namespace somewhere,
because it actually shares memory with the corresponding VTK Array. If
Python does garbage cleanup on flat_data_array then you'll lose the VTK
array, and possibly your mind.

Back the other way:

vtk_data = image.GetPointData().GetScalars()
numpy_data = numpy_support.vtk_to_numpy(vtk_data)

dims = image.GetDimensions()

numpy_data = numpy_data.reshape(dims, dims, dims)
numpy_data = numpy_data.transpose(2,1,0)

numpy_data[x,y,z]...

Paul

On Mon, Mar 23, 2009 at 12:36 PM, Mathias Franzius
<Mathias.Franzius at web.de>wrote:

> Dear ng,
>
> I want to render offscreen into a numpy array. So far it works with writing
> to disk with a vtkWindowToImageFilter and an ImageWriter and then reloading
> it with PIL and converting via scipy.misc.fromimage.
> However, the vtk.util.vtk_to_numpy seems much more straight-forward and
> efficient.
> My problem is: how do I get the rendered image in vtk_data format? Now I
> use the renderWindow like this:
> fil = vtk.vtkWindowToImageFilter()
> fil.SetInput(renderWindow);
>
> Thanks!
>   Mathias
> _______________________________________________________________________
> DSL zum Nulltarif + 20 Euro Extraprämie bei Online-Bestellung über die
>
> _______________________________________________
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>
> Please keep messages on-topic and check the VTK FAQ at:
> http://www.vtk.org/Wiki/VTK_FAQ
>