[Insight-users] SimpleITK Images to Numpy & reciprocally

jeff witz witzjean at gmail.com
Fri Aug 3 11:02:15 EDT 2012


Hello,

I try to experiment Simple ITK and python.

I want to make several task :

1) Reading ITK,VTK (mhd,vtk) 2D images with 2 or more
NumberOfComponentsPerPixel,
2) Writing ITK,VTK (mhd,vtk) 2D images with 2 or more
NumberOfComponentsPerPixel,
3) Transform from an to an numarray, ITK,VTK (mhd,vtk) 2D images with
2 or more NumberOfComponentsPerPixel,

For now I succeed in 1) and Have bug with 2) & 3).

I can easily pass from an ITK buffer to a numpy array, but the
ordering is not the good one.
The shape is  : (NumberOfComponentsPerPixel,Xdim,Ydim)
So this problem can be sovled using :
tmp = sitk.GetArrayFromImage( image )
this work for any number of component.

So if i try to do the reverse operation
image=sitk.GetImageFromArray(tmp)
it doesn't work, indeed, if I ask for the NumberOfComponentsPerPixel,
I get 1. So I create a 3D image, THIS IS NOT WHAT I NEED.

So in order to solve this bug I made my own system for exporting and
importing itk image / numpy array

import SimpleITK as sitk
import numpy as np

dataDir='./'
image = sitk.ReadImage ( dataDir + "capt0242.tif" )
z = sitk.GetArrayFromImage( image )
image2 = sitk.Image( (z.shape[2], z.shape[1]),
image.GetPixelIDValue(), z.shape[0] );
sitk._SimpleITK._SetImageFromArray( z.tostring(), image2 ) # work for
image color
# Output, set ITK for valid output formats
sitk.WriteImage ( image2, "./Example.mhd" )
print time.clock()-tic
os.system("paraview --data=./Example.mhd")

if one wants to operate on data using python, If you try to
imshow(z[0,::,::]) in order to see one component you will see a

the picture as to be reshaped (it would be very simple to correct in
SimpleITK directly) using :
z=(a.reshape(N[0]*N[1]*N[2],1)).reshape(N[1],N[2],N[0])


the third dimension is then the number of component as it is in matplotlib.

Note that the jpeg import is not working on my PC.




-- 
Jean-François WITZ


More information about the Insight-users mailing list