Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a vtkimage into a numpy array

I tried to deal with MHD image files with python and python-vtk. The file is placed in google drive : mhd .

I want to convert it into numpy array and then split them according to a given value' 500 for instance '. then calculate the summary information. I followed the instruction of this
[post] How to convert a 3D vtkDataSet into a numpy array?
but it 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()

an error comes here:

AttributeError: GetPixelSpacing

How could I achieve the conversion?
When I finish the data splitting, how could I save them back to mhd (or a raw data would be better ?)

like image 378
user3817800 Avatar asked Aug 10 '14 16:08

user3817800


1 Answers

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

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

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

like image 195
Saullo G. P. Castro Avatar answered Sep 29 '22 11:09

Saullo G. P. Castro