ITKNumpyBridge problems converting from numpy array.

I am using ITKBridgeNumPy to pass an image to a numpy algorithm, and then returning it to another image.

    #image is a RealImageType
    X = itk.GetArrayViewFromImage(image)
    print("X", X.shape)
    lam = 0.1
    F = ptv.tv1_2d(X, lam)
    print("F", F.shape)
    # Line77 (error in next line)
    modifiedImage = itk.PyBuffer[RealImageType].GetImageViewFromArray(F) 

But I am getting an error that I don’t get, I thought modifiedImage doesn’t need any initialization (following ITKBridgeNumpy example).

X (1280, 1280)
F (1280, 1280)
RuntimeError: Size mismatch of image and Buffer.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "wavelet-TV.py", line 77, in <module>
    modifiedImage = itk.PyBuffer[RealImageType].GetImageViewFromArray(F)
  File "/home/phc/repository_local/total_variation/venv_proxTV/lib/python3.6/site-packages/itk/Configuration/../itkPyBufferPython.py", line 1486, in GetImageViewFromArray
    imgview = itkPyBufferIF2._GetImageViewFromArray( ndarr, ndarr.shape[::-1], 1)
  File "/home/phc/repository_local/total_variation/venv_proxTV/lib/python3.6/site-packages/itk/Configuration/../itkPyBufferPython.py", line 1400, in _GetImageViewFromArray
    return _itkPyBufferPython.itkPyBufferIF2__GetImageViewFromArray(arr, shape, numOfComponent)
SystemError: <built-in function itkPyBufferIF2__GetImageViewFromArray> returned a result with an error set

Any hint?

Solved, types where different!

print(X.dtype) #float32
print(F.dtype) #float64

To solve:

F = F.astype(X.dtype, copy=False)
1 Like

Cool!

Another approach is to use:

modifiedImage = itk.GetImageViewFromArray(F) 

instead of

modifiedImage = itk.PyBuffer[RealImageType].GetImageViewFromArray(F) 

because it automatically uses the correct type.

More information was provided by @fbudin here:

https://blog.kitware.com/convert-itk-data-structures-to-numpy-arrays/

1 Like