[Insight-users] Got NaN from WrapITK registration

Julien Lamy lamy at unistra.fr
Mon Jan 11 06:34:35 EST 2010


Le 10/01/2010 22:39, Benjamin M. Schwartz a écrit :
> I tried to port the simplest python registration example
> (ImageRegistration3.py) to wrapitk.  The ported script is attached,
> including a trivial test case.  When the test case runs, the resampling
> appears to introduce a NaN value.  It also introduces non-zero values,
> despite the fact that the entire input image is zero.  These values vary
> from run to run, suggesting that the resampler is reading uninitialized
> memory.
> 
> Is this a bug, as I suspect?  Do you see the same behavior?  I am using
> itk, WrapITK, and PyBuffer compiled from the 3.16.0 tarball.

I had a similar problem, and it seems to be indeed a memory problem :
PyBuffer.GetArrayFromImage does not transfer the ownership of the
container from the ITK image to the ndarray. Inside the function,
everything works fine, but when it returns, the itk.Image is destroyed,
frees its container, and the numpy array points to unallocated memory.
This causes weird results with small images, and segfaults with larger
images.

I wrote two functions to set the data ownership, one for the ITK image,
the other for the numpy.ndarray. I did not find a way to do that on the
Python level, so they must be wrapped before use, or best, integrated in
PyBuffer. After calling GetArrayFromImage, you will have to call
set_pixel_container_ownership(movedImage, False)
set_array_ownership(a2_mod, True)

Here's the code for the functions:

void
set_array_ownership(PyObject* array, bool value)
{

	PyArrayObject* pyArray = reinterpret_cast<PyArrayObject*>(array);

	if(value)
	{
		pyArray->flags |= NPY_OWNDATA;
	}
	else
	{
		pyArray->flags &= ~NPY_OWNDATA;
	}
}

void
set_pixel_container_ownership(itk::Image<float, 3>::Pointer image, bool
value)
{
    image->GetPixelContainer()->SetContainerManageMemory(value);
}

-- 
Julien


More information about the Insight-users mailing list