本文整理汇总了Python中vtk.vtkXMLImageDataReader函数的典型用法代码示例。如果您正苦于以下问题:Python vtkXMLImageDataReader函数的具体用法?Python vtkXMLImageDataReader怎么用?Python vtkXMLImageDataReader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了vtkXMLImageDataReader函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ConvertVTItoMatlab
def ConvertVTItoMatlab(work_dir):
import vtk
import vtk.util.numpy_support as vtkNumPy
import numpy
import scipy.io as scipyio
import os
# echo vtk version info
print "using vtk version", vtk.vtkVersion.GetVTKVersion()
directoryList = os.listdir(work_dir)
files = filter(lambda x:os.path.isfile("%s/%s" % (work_dir,x) ),directoryList)
vtiFiles = filter(lambda x: x.split(".").pop() == "vti" ,files)
filenames = filter(lambda x: x.split(".").pop(0) == "updatefemROI5" ,vtiFiles)
for idlist, fileID in enumerate( filenames):
print "reading %s/%s" % (work_dir,fileID)
vtkReader = vtk.vtkXMLImageDataReader()
vtkReader.SetFileName( "%s/%s" % (work_dir,fileID) )
vtkReader.Update()
imageDataVTK = vtkReader.GetOutput()
dimensions = imageDataVTK.GetDimensions()
spacing = imageDataVTK.GetSpacing()
origin = imageDataVTK.GetOrigin()
print spacing, origin, dimensions
#fem.SetImagingDimensions( dimensions ,origin,spacing)
image_point_data = imageDataVTK.GetPointData()
image_data = vtkNumPy.vtk_to_numpy( image_point_data.GetArray(0) )
# write numpy to disk in matlab
scipyio.savemat("%s/%s.mat" % (work_dir,fileID), {'spacing':spacing, 'origin':origin,'image':image_data})
print "wrote %d of %d" % (idlist, len( filenames))
示例2: load
def load(file):
datareader = v.vtkXMLImageDataReader()
datareader.SetFileName(file)
datareader.Update()
data = datareader.GetOutput()
return data
示例3: _load_slice
def _load_slice(self, q, index, desc):
if not self._volume:
import vtk
dirname = os.path.dirname(self.__dbfilename)
vol_file = os.path.join(dirname, "cinema.vti")
vr = vtk.vtkXMLImageDataReader()
vr.SetFileName(vol_file)
vr.Update()
volume = vr.GetOutput()
self._volume = volume
self._vol_file = vol_file
else:
volume = self._volume
ext = volume.GetExtent()
width = ext[1]-ext[0]
height = ext[3]-ext[2]
from vtk.numpy_interface import dataset_adapter as dsa
image = dsa.WrapDataObject(volume)
oid = volume.ComputePointId([0, 0, index])
nparray = image.PointData[0]
imageslice = np.reshape(nparray[oid:oid+width*height], (width,height,3))
doc = Document(desc, imageslice)
doc.attributes = None
return doc
示例4: __init__
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkXMLImageDataReader(), 'Reading vtkXMLImageData.',
(), ('vtkXMLImageData',),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
示例5: main
def main(argv):
#Just get something working for testing...
try:
opts, args = getopt.getopt(argv,"hi:", ["ifile="])
except getopt.GetoptError as err:
print 'tviewer.py -i <inputfile.vtk>'
print (str(err))
for opt, arg in opts:
if opt == '-h':
print 'tviewer.py -i <inputfile.vtk>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
print("Going to load and generate png from ", inputfile)
#Read data
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(inputfile)
reader.Update()
image = reader.GetOutput()
#image.SetSpacing(1,1,1)
#image.GetPointData().SetScalars(image.GetPointData().GetVectors())
#Compute Q Criterion for texture mapping
#Now put this in a png file
castFilter = vtk.vtkImageCast()
castFilter.SetInputData(image)
castFilter.Update()
w = vtk.vtkPNGWriter()
w.SetInputData(castFilter.GetOutput())
w.SetFileName("xyslice.png")
w.Write()
示例6: __init__
def __init__(self,offset,get=1,file='data',type='vtu',mirrorPlane=None,silent=0):
self.offset=offset
self.filenameout = file
self.type = type
self.isLoaded = False
self.mirrorPlane=mirrorPlane
self.silent = silent
if type == 'vtu':
self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vtu'])
self.datareader = v.vtkXMLUnstructuredGridReader()
elif type == 'pvtu':
self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.pvtu'])
self.datareader = v.vtkXMLPUnstructuredGridReader()
elif type == 'vti':
self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vti'])
self.datareader = v.vtkXMLImageDataReader()
else:
print 'Unknown filetype'
if (self.silent == 0): print '========================================'
if (self.silent == 0): print 'loading file %s' % (self.filename)
if get != None:
self.getAll()
示例7: vti2mat
def vti2mat(fileIn, fileOut):
"""Convert voxel-array from VTI to MAT (MATLAB(R)) format.
Parameters
----------
fileIn : str
Path for input VTI file.
fileOut : str
Path for output MAT file.
"""
import numpy as np
import vtk
import scipy.io as sio
from vtk.util import numpy_support as nps
from math_utils import lcmm
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(fileIn)
reader.Update()
vtkImageData = reader.GetOutput()
dim = vtkImageData.GetDimensions()
flatV = nps.vtk_to_numpy(vtkImageData.GetPointData().GetScalars())
V = flatV.reshape(dim[::-1])
spacing = np.array(vtkImageData.GetSpacing())[::-1]
estimatedFactors = lcmm(*spacing) / spacing
estimatedVoxelSize = 1. / estimatedFactors
sio.savemat(fileOut, {'volume':V, 'spacing': spacing, 'estimated_voxel_size': estimatedVoxelSize})
示例8: getReader
def getReader(self):
reader = None;
if self.srcFormat == "vti":
reader = vtk.vtkXMLImageDataReader();
reader.SetFileName(self.src);
reader.Update();
return reader;
示例9: loadVisualisations
def loadVisualisations(self):
for tuple in self.d_tuples:
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(tuple[0])
reader.Update()
self.d_window.open_vtk_data(reader.GetOutput())
self.d_window.load_mm(tuple[1])
示例10: ConvertVTKMatlab
def ConvertVTKMatlab(input_filename,output_filename):
import vtk.util.numpy_support as vtkNumPy
import numpy
import scipy.io as scipyio
extension = input_filename.split('.').pop()
vtkReader = None
if extension == 'vtk':
vtkReader = vtk.vtkDataSetReader()
elif extension == 'vti':
vtkReader = vtk.vtkXMLImageDataReader()
else:
raise RuntimeError('unknown file type %s ' % input_filename)
vtkReader.SetFileName( "%s" % (input_filename) )
vtkReader.Update()
imageDataVTK = vtkReader.GetOutput()
dimensions = imageDataVTK.GetDimensions()
spacing = imageDataVTK.GetSpacing()
origin = imageDataVTK.GetOrigin()
print spacing, origin, dimensions
#fem.SetImagingDimensions( dimensions ,origin,spacing)
image_point_data = imageDataVTK.GetPointData()
image_data = vtkNumPy.vtk_to_numpy( image_point_data.GetArray(0) )
# write numpy to disk in matlab
# indexing is painful.... reshape to dimensions and transpose 2d dimensions only
scipyio.savemat( output_filename, {'spacing':spacing, 'origin':origin,'image':image_data.reshape(dimensions,order='F').transpose(1,0,2)})
示例11: vti_to_numpy
def vti_to_numpy(filename, fieldName='density'):
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(filename)
reader.Update()
# get vtkImageData
imageData = reader.GetOutput()
sr = imageData.GetScalarRange()
print("scalar range {}".format(sr))
# get dimensions tuple
dims = imageData.GetDimensions()
print("dims {}".format(dims))
# get vtk data
vtk_data = imageData.GetPointData().GetArray(fieldName)
# convert to numpy array
numpy_data = numpy_support.vtk_to_numpy(vtk_data)
#numpy_data = numpy_data.reshape(dims[0], dims[1], dims[2])
numpy_data = numpy_data.reshape(dims[1], dims[0])
print("shape in reader {}".format(numpy_data.shape))
#numpy_data = numpy_data.transpose(2,1,0)
return numpy_data
示例12: ReadVTKXMLImageFile
def ReadVTKXMLImageFile(self):
if (self.InputFileName == ''):
self.PrintError('Error: no InputFileName.')
self.PrintLog('Reading VTK XML image file.')
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(self.InputFileName)
reader.Update()
self.Image = reader.GetOutput()
示例13: Import
def Import(filename):
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(filename)
# TODO: Check if the code bellow is necessary
reader.WholeSlicesOn()
reader.Update()
return reader.GetOutput()
示例14: __init__
def __init__(self, vtifname, parallel=False):
self.reader = vtk.vtkXMLImageDataReader()
self.reader.SetFileName(vtifname)
self.reader.Update()
self.data = self.reader.GetOutput()
self.dim = self.data.GetDimensions()
self.s_scal = [self.dim[1]-1, self.dim[0]-1]
self.s_vec = [self.dim[1]-1, self.dim[0]-1,3]
示例15: GetImageDataForBaseAndExtension
def GetImageDataForBaseAndExtension(self, fileName, extension):
"""
:type fileName: basestring
:type extension: basestring
:rtype: vtkImageData
"""
if extension == DataReader.TypeMHA or extension == DataReader.TypeMHD:
# Use a vktMetaImageReader
imageReader = vtkMetaImageReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeDICOM:
# Use a dicom reader
dirName = os.path.dirname(fileName)
return self.GetImageDataFromDirectory(dirName)
elif extension == DataReader.TypeDAT:
raise Exception("Support for .dat files is not implemented.")
# Read in the .dat file byte by byte
imageData = None
import numpy as np
with open(fileName, "rb") as f:
dimensions = np.fromfile(f, np.int16, count=3)
imageData = vtkImageData()
imageData.SetDimensions(int(dimensions[0]), int(dimensions[1]), int(dimensions[2]))
imageData.SetScalarTypeToFloat()
imageData.SetNumberOfScalarComponents(1)
imageData.AllocateScalars()
imageData.Update()
imageData.PrepareForNewData()
fileData = np.fromfile(f, np.int16)
dataIndex = 0
for z in range(int(dimensions[2])):
for y in range(int(dimensions[1])):
for x in range(int(dimensions[0])):
imageData.SetScalarComponentFromFloat(x, y, z, 0, float(fileData[dataIndex]))
dataIndex += 1
return imageData
elif extension == DataReader.TypeVTI:
# Use a XMLImageReader
imageReader = vtkXMLImageDataReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
elif extension == DataReader.TypeNRRD:
# Use a NrrdReader
imageReader = vtkNrrdReader()
imageReader.SetFileName(fileName)
imageReader.Update()
return imageReader.GetOutput()
else:
assert False