[vtkusers] Passing data between VTK and NumPy.

Robb Brown brownr at ucalgary.ca
Thu Sep 19 11:31:41 EDT 2002


This is done very nicely with vtkImageImport (Numpy to vtkImage) and 
vtkImageExport (vtkImage to Numpy).

Here's a Python function to take a vtkStructuredPoints (same as 
vtkImage) and convert it to a Numpy array (preserving the shape):

def VTKtoNumpy(vol):
	exporter = vtkImageExport()
	exporter.SetInput(vol)
	dims = exporter.GetDataDimensions()
	if (exporter.GetDataScalarType() == 3):
		type = UnsignedInt8
	if (exporter.GetDataScalarType() == 5):
		type = Int16
	a = zeros(reduce(multiply,dims),type)
	s = a.tostring()
	exporter.SetExportVoidPointer(s)
	exporter.Export()
	a = reshape(fromstring(s,type),(dims[2],dims[0],dims[1]))
	return a

Note that you have to translate the VTK scalar type into a Numeric 
type.  Inserting data into a vtkStructuredPoints is pretty much the 
same except using vtkImageImport.  This approach takes advantage of 
the fact that a Python string can substitute for a C void array.

For your application it sounds like you want to start with a Numpy 
array, slice out a 3D volume, use vtkImageImport to put that into a 
VTK data type and render it.  To change the slice just do another 
import and render again.


>Dear all,
>I'm using VTK to visualize 5D-data.
>However, VTK cannot handle 5D-data. I thought I had a solution but 
>there are still some things that I don't know how to solve.
>I can put all the data of the 5D-data and the dimensions into a long 
>1D vtkStructuredPoints.
>Later on I can reconstruct the 5D-dataset by using these dimensions.
>This 1D vtkStructuredPoints can be used as input in an instance of 
>vtkProgrammableFilter.
>Using the SetExecuteMethod I want to implement a method to select 
>some '3D-slices' of the 5D-dataset.
>The wat I want to implement the slicing is by using NumPy(A fast 
>Numerical Extension of python).
>The problem is that I don't know how to get the data from the 
>SetExecuteMethod into NumPy.
>Afaik know NumPy can read from strings and files.
>
>Do I need to convert the data into a string?
>Is there a way to 'say' to NumPy where in memory the 5D-dataset starts?
>Does someone has experience in using NumPy in combination with VTK?
>
>
>
>
>_______________________________________________
>This is the private VTK discussion list. Please keep messages 
>on-topic. Check the FAQ at: 
><http://public.kitware.com/cgi-bin/vtkfaq>
>Follow this link to subscribe/unsubscribe:
>http://public.kitware.com/mailman/listinfo/vtkusers


-- 
______________________________
Robb Brown
Seaman Family MR Research Centre
Calgary, Alberta, Canada



More information about the vtkusers mailing list