当前位置: 首页>>代码示例>>Python>>正文


Python numpy_support.vtk_to_numpy函数代码示例

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


在下文中一共展示了vtk_to_numpy函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: NumpyCombinePixelValues

  def NumpyCombinePixelValues(self,inputVolumeNode1, inputVolumeNode2):
    """This method gets Numpy array information from the input volumes and combines 
    the pixel information to give an output numpy array. All input volumes must 
    be the same size"""

    # Print to Slicer CLI
    print('Combining input pixels...'),
    start_time = time.time()

    # Get Image Data for Input Volumes
    imdata1 = inputVolumeNode1.GetImageData()
    imdata2 = inputVolumeNode2.GetImageData()

    # Get Dimensions of First Input (all inputs should match)
    x,y,z   = imdata1.GetDimensions()

    # Get scalar data for all inputs
    scalars1 = imdata1.GetPointData().GetScalars()
    scalars2 = imdata2.GetPointData().GetScalars()

    ## Make Numpy Arrays from Scalar Data
    array1 = numpy_support.vtk_to_numpy(scalars1)
    array2 = numpy_support.vtk_to_numpy(scalars2)

    # Combine Arrays (must divide before summing or will add to more than 256 and wrap around values)
    #outputNumpyarray = array1/2+array2/2
    outputNumpyarray = np.around(27*np.true_divide(array1,array2)) # For Normalization

    # Print to Slicer CLI
    end_time = time.time()
    print('done (%0.2f s)') % float(end_time-start_time)

    return outputNumpyarray
开发者ID:tjg17,项目名称:AssortedLabModules,代码行数:33,代码来源:SetVolumeScalars.py

示例2: read_data_and_build_snapshot_matrix

def read_data_and_build_snapshot_matrix(x_min,x_max,y_min,y_max,z_min,z_max,snapshot_dir,file_list,\
						num_snapshots,num_points,num_components,var_name, A):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	extract_region = "false"
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract_region = "true"
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.MergingOn()
	u_temp_read = np.array(np.zeros((num_points,3), dtype=np.float64))
	print '\n   Reading data ...'
	for j in range(0,num_snapshots+1):
		print '      Reading file ', file_list[j].strip(), 'file number ', j, ' of ', num_snapshots
		reader.SetFileName(snapshot_dir + file_list[j].strip())
		reader.Update()
		if (extract_region=="true"):
			extract.SetInput(reader.GetOutput())
			extract.Update()
			u_temp_read = VN.vtk_to_numpy(extract.GetOutput().GetPointData().GetVectors(var_name))
		else:
			u_temp_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors(var_name))
		for k in range(0,num_components):
			A[k*num_points:(k+1)*num_points,j] = u_temp_read[:,k]
开发者ID:vassilikitsios,项目名称:snapshot_pod_rom_py,代码行数:25,代码来源:io_vtk_m.py

示例3: get_normals

def get_normals(polydata):
    #normals = polydata.GetPointData().GetArray("Normals")
    normals = polydata.GetPointData().GetArray("Normals")
    print numpy_support.vtk_to_numpy(normals)
    

    return numpy_support.vtk_to_numpy(normals)
开发者ID:jcdinis,项目名称:POMES,代码行数:7,代码来源:app.py

示例4: loadVtk

def loadVtk(filename):
    if 'vtp' in filename:
        vreader = vtk.vtkXMLPolyDataReader()
    else:
        vreader = vtk.vtkPolyDataReader()

    vreader.SetFileName(filename)
    vreader.Update()
    polydata = vreader.GetOutput()
    polydata.ReleaseDataFlagOn()

    streamlines = []
    verts = vtk_to_numpy(polydata.GetPoints().GetData())
    scalars = {}

    pointdata = polydata.GetPointData()
    for si in range(pointdata.GetNumberOfArrays()):
        sname =  pointdata.GetArrayName(si)
        scalars[sname] = vtk_to_numpy(pointdata.GetArray(si))

    for i in range(polydata.GetNumberOfCells()):
        pids =  polydata.GetCell(i).GetPointIds()
        ids = [ pids.GetId(p) for p in range(pids.GetNumberOfIds())]
        streamlines.append(ids)

    res = {'points':verts, 'values':scalars, 'streamlines':streamlines}
    return res
开发者ID:sinkpoint,项目名称:fascicle,代码行数:27,代码来源:trkmanage.py

示例5: _extractRectGridByBounds

def _extractRectGridByBounds(vtrObj,boundObj):
    '''
    Function that extracts cell from a rectilinear grid (vtr) using bounds.

    Should be signifacantly faster the extractBounds method.

    '''
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    bO = boundObj.GetBounds()
    xC = npsup.vtk_to_numpy(vtrObj.GetXCoordinates())
    yC = npsup.vtk_to_numpy(vtrObj.GetYCoordinates())
    zC = npsup.vtk_to_numpy(vtrObj.GetZCoordinates())
    iLT = np.where(xC <= bO[0])[0]
    iL = 0 if iLT.shape[0] == 0 else iLT[-1]
    iUT = np.where(xC >= bO[1])[0]
    iU = len(xC) if iUT.shape[0] == 0 else iUT[0]
    jLT = np.where(yC <= bO[2])[0]
    jL = 0 if jLT.shape[0] == 0 else jLT[-1]
    jUT = np.where(yC >= bO[3])[0]
    jU = len(yC) if jUT.shape[0] == 0 else jUT[0]
    kLT = np.where(zC <= bO[4])[0]
    kL = 0 if kLT.shape[0] == 0 else kLT[-1]
    kUT = np.where(zC >= bO[5])[0]
    kU = len(zC) if kUT.shape[0] == 0 else kUT[0]
    extRect = vtk.vtkExtractRectilinearGrid()
    extRect.SetInputData(vtrObj)
    extRect.SetVOI((iL,iU,jL,jU,kL,kU))
    extRect.Update()
    return extRect
开发者ID:grosenkj,项目名称:telluricpy,代码行数:31,代码来源:surjection.py

示例6: vtk_ensure_trilist

def vtk_ensure_trilist(polydata):
    try:
        import vtk
        from vtk.util.numpy_support import vtk_to_numpy

        trilist = vtk_to_numpy(polydata.GetPolys().GetData())

        # 5 is the triangle type - if we have another type we need to
        # use a vtkTriangleFilter
        c = vtk.vtkCellTypes()
        polydata.GetCellTypes(c)

        if c.GetNumberOfTypes() != 1 or polydata.GetCellType(0) != 5:
            warnings.warn('Non-triangular mesh connectivity was detected - '
                          'this is currently unsupported and thus the '
                          'connectivity is being coerced into a triangular '
                          'mesh. This may have unintended consequences.')
            t_filter = vtk.vtkTriangleFilter()
            t_filter.SetInputData(polydata)
            t_filter.Update()
            trilist = vtk_to_numpy(t_filter.GetOutput().GetPolys().GetData())

        return trilist.reshape([-1, 4])[:, 1:]
    except Exception as e:
        warnings.warn(str(e))
        return None
开发者ID:HaoyangWang,项目名称:menpo3d,代码行数:26,代码来源:base.py

示例7: execute

  def execute(self):
    vessel=self._vessel
    array_v =dict();
            
    for ff in ["ChestRegion"]:
      tmp=vessel.GetPointData().GetArray(ff)
      if isinstance(tmp,vtk.vtkDataArray) == False:
        tmp=vessel.GetFieldData().GetArray(ff)
      array_v[ff]=vtk_to_numpy(tmp)

    xyz_arr=vtk_to_numpy(vessel.GetPoints().GetData())
    
    fig=plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.set_aspect('equal')
    X=xyz_arr[:,0]
    Y=xyz_arr[:,1]
    Z=xyz_arr[:,2]
    ax.scatter(X,Y,Z,s=1,c=array_v['ChestRegion'],marker='.',cmap=plt.cm.jet,linewidth=0)
    ax.grid(True)
    plt.xlabel('x')
    plt.ylabel('y')
    # Create cubic bounding box to simulate equal aspect ratio
    max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max()
    Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(X.max()+X.min())
    Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(Y.max()+Y.min())
    Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(Z.max()+Z.min())
    # Comment or uncomment following both lines to test the fake bounding box:
    for xb, yb, zb in zip(Xb, Yb, Zb):
      ax.plot([xb], [yb], [zb], 'w')
    ax.view_init(elev=20.,azim=80)
    fig.savefig(self.output_prefix+'_vasculatureQualityControl.png',dpi=180)
开发者ID:151706061,项目名称:ChestImagingPlatform,代码行数:32,代码来源:vasculature_qc.py

示例8: GetRawDICOMData

def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileName("rawdata.%04d.vtk" % fileID )
  vtkDcmWriter.SetInput(vtkAppend.GetOutput())
  vtkDcmWriter.Update()

  return (real_array,imag_array)
开发者ID:ImageGuidedTherapyLab,项目名称:DakotaApplications,代码行数:33,代码来源:tmap.py

示例9: read_vtk

    def read_vtk(self, data_dir='./data', file_name='separatrices.vtk'):
        """
        Read the separatrices from a vtk file.

        call signature:

            read_vtk(data_dir='./data', file_name='separatrices.vtk')

        Arguments:

        *data_dir*:
            Origin data directory.

        *file_name*:
            Origin file name.
        """

        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(os.path.join(data_dir, file_name))
        reader.Update()
        output = reader.GetOutput()

        # Read the separatrices.
        points = output.GetPoints()
        cells = output.GetCells()
        self.separatrices = []
        self.connectivity = []
        for separatrix in range(points.GetNumberOfPoints()):
            self.separatrices.append(points.GetPoint(separatrix))
        self.separatrices = np.array(self.separatrices)
        self.connectivity = np.array([VN.vtk_to_numpy(cells.GetData())[1::3],
                                      VN.vtk_to_numpy(cells.GetData())[2::3]])
        self.connectivity = self.connectivity.swapaxes(0, 1)
开发者ID:debanjan0811,项目名称:pencil-code,代码行数:33,代码来源:field_skeleton.py

示例10: PlotData

    def PlotData(self):

        # remove any measurement line that might exist
        self.removeMeasurementLine(False)

        if self._usebar is False:
            # handle 'pixel' vs 'mm' options:
            self._transform.Identity()
            self._transform.Scale(self._unit_scalings[self._unit], self._unit_scalings[
                                  self._unit], self._unit_scalings[self._unit])
            self._plotData.Update()
            points = numpy_support.vtk_to_numpy(
                self._plotData.GetPoints().GetData())
            points = (points - points[0]).transpose()
            self.xdata = sum(points * points) ** 0.5
            self.ydata = numpy_support.vtk_to_numpy(
                self._plotData.GetPointData().GetScalars()).astype('float32')
        else:
            inc = abs(self.xdata[1] - self.xdata[0])
            self.lower_panel.m_spinCtrlLower.SetIncrement(inc)
            self.lower_panel.m_spinCtrlUpper.SetIncrement(inc)
            self.lower_panel.m_spinCtrlLower.SetMin(self.xdata[0])
            self.lower_panel.m_spinCtrlLower.SetMax(self.xdata[-1])
            self.lower_panel.m_spinCtrlUpper.SetMin(self.xdata[0])
            self.lower_panel.m_spinCtrlUpper.SetMax(self.xdata[-1])

        self.draw_plot()
        self.canvas.draw()
开发者ID:andyTsing,项目名称:MicroView,代码行数:28,代码来源:VTKPlotWindow.py

示例11: test_pointdata

 def test_pointdata(self):
     self.nrrdArray = ns.vtk_to_numpy(
         self.rnrrd.GetOutput().GetPointData().GetScalars()
     )
     self.itkArray = ns.vtk_to_numpy(
         self.ritk.GetOutput().GetPointData().GetScalars()
     )
     self.assertTrue(numpy.allclose(self.nrrdArray, self.itkArray))
开发者ID:BRAINSia,项目名称:BRAINSTools,代码行数:8,代码来源:vtkITKArchetypeScalarReaderFile.py

示例12: rdmmag

def rdmmag(X1, X2):
    """Rdm and Mag calculation."""
    X1 = vtk_to_numpy(X1)
    X2 = vtk_to_numpy(X2)
    rdm = la.norm(X1 / la.norm(X1) - X2 / la.norm(X2))
    rmag = abs(1. - la.norm(X2) / la.norm(X1))
    print("  RDM = ", rdm, "\t  rMAG = ", rmag)
    return rdm, rmag
开发者ID:eolivi,项目名称:openmeeg_sample_data,代码行数:8,代码来源:om_compare.py

示例13: getDataArray

def getDataArray(vtkObj,name,arrType='Cell'):
    """Function that returns the cell/point data array. """
    return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    if arrType == 'Cell':
        return npsup.vtk_to_numpy(vtkObj.GetCellData().GetArray(name))
    elif arrType == 'Point':
        return npsup.vtk_to_numpy(vtkObj.GetPointData().GetArray(name))
    else:
        raise Exception('Not a support arrType')
开发者ID:grosenkj,项目名称:telluricpy,代码行数:9,代码来源:dataset.py

示例14: __init__

 def __init__(self, dataDir = 'data', streamFile = 'stream.vtk'):
     """
     Read the initial streamlines.
     
     call signature:
     
       readStream(dataDir = 'data', streamFile = 'stream.vtk')
       
     Keyword arguments:
      *dataDir*:
         Data directory.
         
      *streamFile*:
         Read the initial streamline from this file.
     """
 
     # load the data
     reader = vtk.vtkPolyDataReader()
     reader.SetFileName(dataDir + '/' + streamFile)
     reader.Update()
     output = reader.GetOutput()
     
     # get the fields
     field = output.GetFieldData()
     nArrays = field.GetNumberOfArrays()
     class params: pass
     p = params()
     for i in range(nArrays):            
         arrayName = field.GetArrayName(i)
         if any(arrayName == np.array(['l', 'sl'])):
             setattr(self, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName)))
         elif any(arrayName == np.array(['hMin', 'hMax', 'lMax', 'tol', 'iterMax', 'nt'])):
             setattr(self, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName))[0])
         else:
             # change this if parameters can have more than one entry
             setattr(p, arrayName, VN.vtk_to_numpy(field.GetArray(arrayName))[0])
     setattr(self, 'p', p)
     
     # get the points
     points = output.GetPoints()
     pointsData = points.GetData()
     data = VN.vtk_to_numpy(pointsData)
     #data = np.swapaxes(data, 0, 1)
     print self.nt
     print self.sl
     print data.shape
     tracers = np.zeros([self.nt, np.max(self.sl), 3], dtype = data.dtype)
     sl = 0
     for i in range(self.nt):
         #if (i > 0):
             #sl = self.sl[i-1]
         #else:
             #sl = 0
         print sl, self.sl[i]
         tracers[i,:self.sl[i],:] = data[sl:sl+self.sl[i],:]
         sl += self.sl[i]
     setattr(self, 'tracers', tracers)
开发者ID:TAdeJong,项目名称:plasma-analysis,代码行数:57,代码来源:streamData.py

示例15: read_paths

def read_paths(fold):
    print fold
    fname = fold+'/pathsq.vtk'
    print fname
    npArray = fold+'/pathsq'    # fname = '/home/florian/MEGAsync/calcul/LCS_tractor/data/paths.vtk'
    if os.path.isfile(npArray + '.npy'):
        print 'loading ', npArray
        t0 = time.time()
        xx = np.load(npArray + '.npy')
        print 'already existing array loaded in', time.time() - t0, 's'
    else:
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(fname)
        reader.Update()
        data = reader.GetOutput()
        ll = data.GetLines()
        n_pts = ll.GetSize()  # nb of points
        n_lines = ll.GetNumberOfCells()  # nb of lines
        idList = vtk.vtkIdList()
        idList.SetNumberOfIds(n_lines)
        print idList
        idList.SetId(0, 0)
        abscissaArray = vtk.vtkFloatArray()
        traj = []  # list of pos
        vel = []  # list of vel
        vort = []  # list of vort
        k = 0
        for i in xrange(n_lines):
            cell = data.GetCell(i)
            abscissa = 0.0
            previousPoint = None
            if i % np.int(n_lines / 100) == 0:
                print k, '% read'
                k += 1


            llength = cell.GetNumberOfPoints()
            pos = []  # np.empty([llength, 3])  # pos, u, vort
            u = []  # np.empty([llength, 3])  # pos, u, vort
            vorti = []  # np.empty([llength])  # pos, u, vort
            for j in range(llength):
                pointId = cell.GetPointId(j)
                pos.append(data.GetPoint(pointId))
                u.append(vtk_to_numpy(data.GetPointData().GetArray("U"))[pointId])
                vorti.append(vtk_to_numpy(data.GetPointData().GetArray("Vorticity"))[pointId])

            traj.append(pos)
            vel.append(u)
            vort.append(vorti)

        # print traj
        # x = [traj, vel, vort]
        xx = np.array([traj,vel,vort])
        np.save(npArray, xx)
        print 'shit\'s read'
        print 'end of path lines reading'
    return xx
开发者ID:totocaca,项目名称:LCS_tractor,代码行数:57,代码来源:readpython.py


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