How to convert vtkimage to numpy array

I tried to process MHD image files using python and python-vtk. File uploaded to Google Drive: mhd .

I want to convert it to a numpy array and then split them according to the given value of "500, for example." then calculate the summary information. I followed the instructions of this
[post] How to convert a 3D vtkDataSet file to a numpy array?
but this does not work for my case.

import vtk
imageReader = vtk.vtkMetaImageReader()
imageReader.SetFileName(testfile1)
imageReader.Update() 
# from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy does not work for the data type issue

image = imageReader.GetOutput()
# List the dimensions of the image, for example
print image.GetDimensions()
pixelspace = imageReader.GetPixelSpacing()

here comes the error:

AttributeError: GetPixelSpacing

How can I achieve conversion?
When I finish splitting the data, how can I save it back to mhd (or will the original data be better?)

+4
1

... :

import numpy as np
import vtk
from vtk.util.numpy_support import vtk_to_numpy

imr = 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()

a NumPy, .

+3

All Articles