How to convert a vtkimage into a numpy array How to convert a vtkimage into a numpy array numpy numpy

How to convert a vtkimage into a numpy array


Adapting from this thread... you can do the following:

import numpy as npimport vtkfrom vtk.util.numpy_support import vtk_to_numpyimr = vtk.vtkMetaImageReader()imr.SetFileName('t10-Subvolume-resample_scale-1.mhd')imr.Update()im = imr.GetOutput()rows, cols, _ = im.GetDimensions()sc = im.GetPointData().GetScalars()a = vtk_to_numpy(sc)a = a.reshape(rows, cols, -1)assert a.shape==im.GetDimensions()

where a will be a NumPy array containing the image data.


To get the channels right for later use as OpenCV image:

import vtkimport numpy as npfrom vtk.util import numpy_supportdef vtkImgToNumpyArray(vtkImageData):    rows, cols, _ = vtkImageData.GetDimensions()    scalars = vtkImageData.GetPointData().GetScalars()    resultingNumpyArray = numpy_support.vtk_to_numpy(scalars)    resultingNumpyArray = resultingNumpyArray.reshape(cols, rows, -1)    red, green, blue, alpha = np.dsplit(resultingNumpyArray, resultingNumpyArray.shape[-1])    resultingNumpyArray = np.stack([blue, green, red, alpha], 2).squeeze()    resultingNumpyArray = np.flip(resultingNumpyArray, 0)    return resultingNumpyArray