Convert NVL Matrix to NumPy array

Just found out that I should not post to the mailing list anymore. So here is my question.

I am using the python wrapper of itk to manipulate. I checked the quick
start guide (
http://itkpythonpackage.readthedocs.io/en/latest/Quick_start_guide.html#usage)
to go from numpy to vnl matrices and vice-versa. However, I got into
trouble when trying to use those utils with itk images. As a short example:

import numpy as np

img = np.random.random((100, 100, 100))
img_itk = itk.GetImageFromArray(img)

vnl_matrix = img_itk.GetDirection().GetVnlMatrix()
type(vnl_matrix)
vnl_matrix_fixedPython.vnl_matrix_fixedD_3_3
itk.GetArrayFromVnlMatrix(vnl_matrix)

TypeError: in method 'itkPyVnlD__GetArrayViewFromVnlMatrix', argument 1 of
type 'vnl_matrixD *'

So what would the proper way of converting this matrix into a numpy array
or view.

Hi Guillaume,

Welcome to Discourse! :slight_smile: :sunny:

img_itk.GetDirection().GetVnlMatrix() returns a vnl_matrix_fixed instead of vnl_matrix, the type expected by GetArrayFromVnlMatrix, so try

vnl_matrix = img_itk.GetDirection().GetVnlMatrix().as_matrix()

HTH,
Matt

3 Likes