4

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()?

Stiefel
  • 2,677
  • 3
  • 31
  • 42
  • I looked into the C++ code of PyBuffer and found, that the call to PyArray_ContiguousFromObject() fails. What conditions must an object have to be contiguous? I would expect a numpy array to be contiguous. – Stiefel Nov 04 '11 at 14:37

1 Answers1

6

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)
Stiefel
  • 2,677
  • 3
  • 31
  • 42