TAGS :Viewed: 8 - Published at: a few seconds ago

[ Why does the Python ITK PyBuffer not accept my numpy array? ]

I am using python 2.6 with ITK wrappers (from PythonXY 2.6.6.2). I am trying to send a 3D image from numpy/scipy to itk for processing.

import itk
imageType = itk.Image.F3
buf =  scipy.zeros( (100,100,100), dtype = float) 
itkImage = itk.PyBuffer[imageType].GetImageFromArray(buf)

GetImageFromArray() fails with the following error:

RuntimeError: Contiguous array couldn't be created from input python object

However, if I do not create the buffer myself, but let ITK create the image, GetImageFromArray() suddenly work:

import itk
imageType = itk.Image.F3
itkImage1 = imageType.New(Regions=[256, 256, 256])
buf = itk.PyBuffer[imageType].GetArrayFromImage(itkImage1)
itkImage2 = itk.PyBuffer[imageType].GetImageFromArray(buf)

How do I create a numpy array myself, that will be accepted by GetImageFromArray()?

Answer 1


The answer was easy:

  • In python a "float" might be 64-Bit (double in c).
  • In itk F3 is a 32-bit float.

Specifying the right type for the ndarray makes it work:

import itk
imageType = itk.Image.F3
buf =  scipy.zeros( (100,100,100), dtype = numpy.float32)
itkImage = itk.PyBuffer[imageType].GetImageFromArray(buf)