• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python vtk.vtkXMLImageDataReader函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中vtk.vtkXMLImageDataReader函数的典型用法代码示例。如果您正苦于以下问题:Python vtkXMLImageDataReader函数的具体用法?Python vtkXMLImageDataReader怎么用?Python vtkXMLImageDataReader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了vtkXMLImageDataReader函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:ImageGuidedTherapyLab,项目名称:FileConversionScripts,代码行数:31,代码来源:convertVTItoMatlab.py


示例2: load

def load(file):
    datareader = v.vtkXMLImageDataReader()
    datareader.SetFileName(file)
    datareader.Update()
    data = datareader.GetOutput()

    return data
开发者ID:yangyha,项目名称:mpi-AMRVAC,代码行数:7,代码来源:convergence.py


示例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
开发者ID:edgar-mtz-e,项目名称:ParaView,代码行数:29,代码来源:cinema_store.py


示例4: __init__

 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkXMLImageDataReader(), 'Reading vtkXMLImageData.',
         (), ('vtkXMLImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
开发者ID:fvpolpeta,项目名称:devide,代码行数:7,代码来源:vtkXMLImageDataReader.py


示例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()
开发者ID:sshamilton,项目名称:vtkscripts,代码行数:33,代码来源:xyslice.py


示例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()
开发者ID:yangyha,项目名称:mpi-AMRVAC,代码行数:25,代码来源:read.py


示例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})
开发者ID:AlfiyaZi,项目名称:Py3DFreeHandUS,代码行数:30,代码来源:converters.py


示例8: getReader

 def getReader(self):
     reader = None;
     if self.srcFormat == "vti":
         reader = vtk.vtkXMLImageDataReader();
     reader.SetFileName(self.src);
     reader.Update();
     return reader;
开发者ID:avontd2868,项目名称:OU_Final_Year,代码行数:7,代码来源:vtkIO.py


示例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])
开发者ID:gaoshuai,项目名称:pcraster,代码行数:7,代码来源:viewblock.py


示例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)})
开发者ID:ImageGuidedTherapyLab,项目名称:FileConversionScripts,代码行数:27,代码来源:convertVTKMatlab.py


示例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
开发者ID:pkestene,项目名称:ramsesGPU,代码行数:29,代码来源:read_vti.py


示例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()
开发者ID:vmtk,项目名称:vmtk,代码行数:8,代码来源:vmtkimagereader.py


示例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()
开发者ID:paulojamorim,项目名称:invesalius3,代码行数:8,代码来源:imagedata_utils.py


示例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]
开发者ID:TravisMitchell,项目名称:TCLB,代码行数:8,代码来源:test_eof.py


示例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
开发者ID:berendkleinhaneveld,项目名称:Registrationshop,代码行数:56,代码来源:DataReader.py


示例16: load_image_data

def load_image_data(handle):
    """
    Load vtkImageData from XML file.

    :param handle: file name
    :type handle: str
    """
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(handle)
    return reader.GetOutput()
开发者ID:JoshuaSBrown,项目名称:langmuir,代码行数:10,代码来源:vtkutils.py


示例17: multi_con_h2

def multi_con_h2(filename):
    # Creating contour for h2 fileld
    
    data = vtk.vtkXMLImageDataReader()
    data.SetFileName(filename)#"/Users/y1275963/Documents/homework/multifield.0060.vti")
    data.Update()
    #Getting highest value
    [low,high] = data.GetOutput().GetPointData().GetArray("H2").GetRange()

    data_h2 = vtk.vtkAssignAttribute()
    data_h2.SetInputConnection(data.GetOutputPort())
    data_h2.Assign('H2','SCALARS','POINT_DATA')
    
    
    
    # Create a filter to extract an isosurface from
    # the dataset.  Connect the input of this
    # filter to the output of the reader.  Set the
    # value for the (one) isosurface that we want
    # to extract, and tell the filter to compute
    # normal vectors for each triangle on the
    # output isosurface.
    
    iso = vtk.vtkContourFilter()
    iso.SetInputConnection(data_h2.GetOutputPort())
    iso.ComputeNormalsOn()
    iso.SetNumberOfContours(10)
    for i in range(10):
        iso.SetValue(i, (1.0-0.1*i)*high) #Chnge here to change the isovalue
    
    
    # Create a mapper to traverse the polydata and
    # generate graphics commands for drawing the
    # polygons onto the output device.
    
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(iso.GetOutputPort())
    mapper.ScalarVisibilityOff()
    
    # Output primitives (i.e. the triangles making
    # up the isosurface) are managed as an actor;
    # we specify that all outputs are coloured
    # red.
    
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(0, 0, 1)
    actor.GetProperty().SetOpacity(0.3)
    
    # Create a renderer which will output the
    # graphics commands onto a drawing surface within
    # a window.  By default the renderer will fill
    # all of the window.  We set the background
    # colour of the window to white.
    return actor
开发者ID:y1275963,项目名称:Yingjie-s-Latex-repo,代码行数:55,代码来源:new_work6.py


示例18: vtkKWHeaderAnnotationEditorEntryPoint

def vtkKWHeaderAnnotationEditorEntryPoint(parent, win):

    app = parent.GetApplication()
    
    # -----------------------------------------------------------------------
    
    # Create a render widget
    # Set the header annotation visibility and set some text
    
    hae_renderwidget = vtkKWRenderWidget()
    hae_renderwidget.SetParent(parent)
    hae_renderwidget.Create()
    
    hae_renderwidget.HeaderAnnotationVisibilityOn()
    hae_renderwidget.SetHeaderAnnotationText("Hello, World!")
    
    app.Script("pack %s -side right -fill both -expand y -padx 0 -pady 0",
        hae_renderwidget.GetWidgetName())
    
    # -----------------------------------------------------------------------
    
    # Create a volume reader
    
    hae_reader = vtkXMLImageDataReader()
    hae_reader.SetFileName(os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "..", "..", "..", "..", "Data", "head100x100x47.vti"))
    
    # Create an image viewer
    # Use the render window and renderer of the renderwidget
    
    hae_viewer = vtkImageViewer2()
    hae_viewer.SetRenderWindow(hae_renderwidget.GetRenderWindow())
    hae_viewer.SetRenderer(hae_renderwidget.GetRenderer())
    hae_viewer.SetInput(hae_reader.GetOutput())
    hae_viewer.SetupInteractor(
        hae_renderwidget.GetRenderWindow().GetInteractor())
    
    hae_renderwidget.ResetCamera()
    
    # -----------------------------------------------------------------------
    
    # Create a header annotation editor
    # Connect it to the render widget
    
    hae_anno_editor = vtkKWHeaderAnnotationEditor()
    hae_anno_editor.SetParent(parent)
    hae_anno_editor.Create()
    hae_anno_editor.SetRenderWidget(hae_renderwidget)
    
    app.Script("pack %s -side left -anchor nw -expand n -padx 2 -pady 2",
        hae_anno_editor.GetWidgetName())
    
    return "TypeVTK"
开发者ID:FNNDSC,项目名称:KWWidgets,代码行数:54,代码来源:vtkKWHeaderAnnotationEditor.py


示例19: GetNumPyData

def GetNumPyData(filename):
  print filename
  vtiReader = vtk.vtkXMLImageDataReader()
  vtiReader.SetFileName(filename)
  vtiReader.Update()
  vtiData = vtk.vtkImageCast()
  vtiData.SetOutputScalarTypeToDouble()
  vtiData.SetInput( vtiReader.GetOutput() )
  vtiData.Update( )
  vti_image = vtiData.GetOutput().GetPointData() 
  vti_array = vtkNumPy.vtk_to_numpy(vti_image.GetArray(0)) 
  return vti_array 
开发者ID:ImageGuidedTherapyLab,项目名称:KalmanLocalization,代码行数:12,代码来源:rms.py


示例20: vti_to_nparray

def vti_to_nparray(fname):
    r = vtk.vtkXMLImageDataReader()
    r.SetFileName(fname)
    r.Update()

    o = r.GetOutput()
    x, y, z = o.GetDimensions()
    
    m = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars())
    m.shape = (z, y, x)
    m[:] = (m > 127) * 1
    
    return m, o.GetSpacing()
开发者ID:tfmoraes,项目名称:smooth_c,代码行数:13,代码来源:smooth_vti.py



注:本文中的vtk.vtkXMLImageDataReader函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python vtk.vtkXMLImageDataWriter函数代码示例发布时间:2022-05-26
下一篇:
Python vtk.vtkWindowToImageFilter函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap