def test_information(): filename = 'test_file.vti' path = os.path.join(helpers.get_dir(), filename) info1 = VTKInformation(path) info2 = VTKInformation(path=path) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(path) reader.Update() info3 = VTKInformation(reader=reader) assert info1 == info2 assert info1 == info3 with pytest.raises(IOError): VTKInformation('bad_path') with pytest.raises(ValueError): reader = vtk.vtkXMLImageDataReader() VTKInformation(reader=reader) # No path with pytest.raises(ValueError): reader = vtk.vtkXMLImageDataReader() reader.SetFileName('bad_path') VTKInformation(reader=reader) assert info1.dtype == np.int32 assert info1.datatype == vtk.VTK_INT
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])
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()
def read_rect_vtu(name): """ Opens a vtp and returns the vtkUnstructuredGrid class """ reader = vtk.vtkXMLImageDataReader() reader.SetFileName(name) reader.Update() ug = reader.GetOutput() return ug
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))
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()
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})
def import_space(filename): if (not os.path.isfile(filename)): print("Can't find file: " + filename) else: reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() reader.GetNumberOfCells() data = reader.GetOutput() dim = np.asarray(data.GetDimensions()) x = np.zeros(data.GetNumberOfPoints()) y = x.copy() z = x.copy() for i in range(data.GetNumberOfPoints()): x[i], y[i], z[i] = data.GetPoint(i) x = x.reshape(dim, order='F') x = 0.5 * (x[1:, 0, 0] + x[:-1, 0, 0]) y = y.reshape(dim, order='F') y = 0.5 * (y[0, 1:, 0] + y[0, :-1, 0]) z = z.reshape(dim, order='F') z = 0.5 * (z[0, 0, 1:] + z[0, 0, :-1]) return x, y, z
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
def main(): path = "yC31/" # the variable name of data array which we used to analyze daryName = "tev" files = os.listdir(path) # declare empty list first, and for every timestep statistics inside. #for i in range(0, 10): #for i in range(0, len(files)): for i in range(74, 75): filename = path + files[i] print(filename) # data reader reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0) # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetScalars(daryName)) dMax = np.amax(dary) dMin = np.amin(dary) dstd = np.std(dary) dsize = np.size(dary) dRange = dMax - dMin dMean = np.mean(dary) dMedian = np.median(dary) print("Data array median: ", dMedian) print("Data array mean: ", dMean) print("Data array std: ", dstd) print("Data array size: ", dsize) print("Data array max: ", dMax) print("Data array min: ", dMin) print("Data array range: ", dRange)
def __init__(self, vtifname, parallel=False, dtype=np.float64): if not os.path.isfile(vtifname): raise FileNotFoundError(vtifname) if parallel: self.reader = vtk.vtkXMLPImageDataReader() else: self.reader = vtk.vtkXMLImageDataReader() self.reader.SetFileName(vtifname) self.reader.Update() self.data = self.reader.GetOutput() self.dim = self.data.GetDimensions() self.trim_0 = [0, 0, 0] self.trim_1 = [x - 1 for x in self.dim] self.s_vec = [self.dim[2] - 1, self.dim[1] - 1, self.dim[0] - 1] if self.dim[2] > 2: self.subspace = np.meshgrid( *[range(self.trim_0[i], self.trim_1[i]) for i in range(3)]) self.s_scal = [self.dim[2] - 1, self.dim[1] - 1, self.dim[0] - 1] else: self.s_scal = [self.dim[1] - 1, self.dim[0] - 1] self.subspace = np.meshgrid( *[range(self.trim_0[i], self.trim_1[i]) for i in range(2)]) self.dtype = dtype
def read(path, name=None): """ Read a vti image. :param path: Path to file :param name: Name or index of array. If 'name' is None then array at index 0 is returned :return: VTKImage instance """ if not os.path.exists(path): raise IOError("No such file or directory: '{}'".format(path)) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(path) reader.Update() output = reader.GetOutput() obj = VTKImage.from_image_data(output, name) obj.info.path = path del output del reader return obj
def generate(self, input_path, output_directory, part_name): input_path = work_dir + "/vtk_image/itk_tile_0_2_6.vti" reader = vtk.vtkXMLImageDataReader() reader.SetFileName(input_path) reader.Update() pad_filter = vtk.vtkImageConstantPad() pad_filter.SetInputConnection(reader.GetOutputPort()) pad_filter.SetConstant(0) pad_filter.SetOutputWholeExtent(reader.GetOutput().GetExtent()[0]-5, reader.GetOutput().GetExtent()[1]+5, reader.GetOutput().GetExtent()[2]-5, reader.GetOutput().GetExtent()[3]+5, reader.GetOutput().GetExtent()[4]-5, reader.GetOutput().GetExtent()[5]+5) pad_filter.Update() writer = vtk.vtkXMLImageDataWriter() writer.SetFileName(work_dir + "/surface/itk_tile_0_2_6_pad.vti") writer.SetInputConnection(pad_filter.GetOutputPort()) writer.Update() myArguments = 'vmtklevelsetsegmentation -ifile ' + work_dir + "/surface/itk_tile_0_2_6_pad.vti" + ' -ofile ' + output_path+"/itk_tile_0_2_6_ls.vti" myPype = pypes.PypeRun(myArguments) myArguments = 'vmtkmarchingcubes -ifile ' + output_path+"/itk_tile_0_2_6_ls.vti" + ' -ofile ' + output_path+"/itk_tile_0_2_6_model.vtp" myPype = pypes.PypeRun(myArguments)
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 = store.Document(desc, imageslice) doc.attributes = None return doc
def load(file): datareader = v.vtkXMLImageDataReader() datareader.SetFileName(file) datareader.Update() data = datareader.GetOutput() return data
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkXMLImageDataReader(), 'Reading vtkXMLImageData.', (), ('vtkXMLImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def convert_vtk_file(vtk_file, plt_file, strand=None, solution_time=None): reader = None if vtk_file.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif vtk_file.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif vtk_file.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif vtk_file.endswith(".vti"): reader = vtk.vtkXMLImageDataReader() reader.SetFileName(vtk_file) reader.Update() vtk_dataset = reader.GetOutput() tp.new_layout() tecplot_dataset = tp.active_frame().dataset add_vtk_dataset(vtk_dataset, tecplot_dataset) if tecplot_dataset.num_zones == 0: print("No zones created.") return for z in tecplot_dataset.zones(): z.name = os.path.basename(vtk_file) if strand and solution_time: z.strand = strand z.solution_time = solution_time tp.data.save_tecplot_plt(plt_file, dataset=tecplot_dataset)
def VTK_import_space(filename): if(os.path.isfile(filename)): print('Space',filename) else: print('Space',filename + ' not found') return reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() reader.GetNumberOfCells() data = reader.GetOutput() ''' Import space ''' dim = np.asarray(data.GetDimensions()) c = np.asarray(data.GetOrigin()) d = np.asarray(data.GetSpacing()) x = np.arange(dim[0])*d[0]+c[0] y = np.arange(dim[1])*d[1]+c[1] z = np.arange(dim[2])*d[2]+c[2] x = 0.5*(x[1:]+x[:-1]) y = 0.5*(y[1:]+y[:-1]) z = 0.5*(z[1:]+z[:-1]) return x,y,z
def VTK_import_array(filename,varname): if(os.path.isfile(filename)): print('File',filename,varname) else: print('File',filename + ' not found') return #varname = filename[:4] + varname reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() reader.GetNumberOfCells() data = reader.GetOutput() dim = data.GetDimensions() cdata = data.GetCellData() N_comps = cdata.GetNumberOfComponents() v = vtk_to_numpy(data.GetCellData().GetArray(varname)) vec = [int(i-1) for i in dim] if(N_comps>1): vec.append(N_comps) v = v.reshape(vec,order='F') return v
def __init__(self, data_file_name, scalar_field_name='Scalars_', max_zoom=2.5, begin_alpha=0.1, end_alpha=0.9): volume_reader = vtk.vtkXMLImageDataReader() volume_reader.SetFileName(data_file_name) volume_reader.Update() volume_data = volume_reader.GetOutput() volume_data.GetPointData().SetActiveAttribute(scalar_field_name, 0) self.data_range = volume_data.GetPointData().GetScalars().GetRange() # default options self.name = "" self.min_scalar_value = self.data_range[0] self.max_scalar_value = self.data_range[1] self.num_cps = 5 self.num_colors = 5 self.scalar_step = (self.max_scalar_value - self.min_scalar_value) / (self.num_cps - 1) self.min_elevation = 5 self.max_elevation = 165 self.max_modes = 5 self.max_zoom = max_zoom self.tf_res = 256 self.begin_alpha = begin_alpha self.end_alpha = end_alpha
def processVTI(obj_name): filename = './' + obj_name + '.vti' r = vtk.vtkXMLImageDataReader() r.SetFileName(filename) r.Update() data = r.GetOutput() dim = numpy.asarray(data.GetDimensions()) dim = [dim[0] / 1000.0, dim[1] / 1000.0, dim[2] / 1000.0] spacing = data.GetSpacing() spacing = [spacing[0] / 1000.0, spacing[1] / 1000.0, spacing[2] / 1000.0] #x = numpy.zeros(data.GetNumberOfPoints()) #y = x.copy() #z = x.copy() #Can do data.SetOrigin(data.GetOrigin() blah blah blah) bounds = data.GetBounds() bounds = numpy.array(bounds) / 1000 extent = data.GetExtent() pd = data.GetPointData() a = pd.GetArray(0) xshape = numpy.array((extent[1], extent[3], extent[5])) - numpy.array( (extent[0], extent[2], extent[4])) + 1 xshape_rev = xshape[-1::-1] x = numpy.zeros(xshape_rev, numpy.float32) for zi in range(xshape[2]): for yi in range(xshape[1]): for xi in range(xshape[0]): idx = zi * xshape[0] * xshape[1] + yi * xshape[0] + xi x[zi, yi, xi] = a.GetValue(idx) / 1000.0 return x, bounds, extent, spacing
def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file. Use ``load`` instead. E.g. `img = load('myfile.tif').imagedata()` """ if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in filename.lower(): reader = vtk.vtkSLCReader() if not reader.CanReadFile(filename): colors.printc("~prohibited Sorry bad slc file " + filename, c=1) return None elif ".vti" in filename.lower(): reader = vtk.vtkXMLImageDataReader() elif ".mhd" in filename.lower(): reader = vtk.vtkMetaImageReader() elif ".dem" in filename.lower(): reader = vtk.vtkDEMReader() elif ".nii" in filename.lower(): reader = vtk.vtkNIFTIImageReader() elif ".nrrd" in filename.lower(): reader = vtk.vtkNrrdReader() if not reader.CanReadFile(filename): colors.printc("~prohibited Sorry bad nrrd file " + filename, c=1) return None reader.SetFileName(filename) reader.Update() image = reader.GetOutput() if len(spacing) == 3: image.SetSpacing(spacing[0], spacing[1], spacing[2]) return image
def getReader(self): reader = None; if self.srcFormat == "vti": reader = vtk.vtkXMLImageDataReader(); reader.SetFileName(self.src); reader.Update(); return reader;
def readDataset(filePath): # load dataset # reader = vtk.vtkDatasetReader() # reader.SetFileName(filePath) # reader.Update() ## print reader.GetOutput() # if reader.GetOutput() == None: reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filePath) reader.Update() reader.GetOutput().GetPointData().RemoveArray("ProcessId") reader.GetOutput().GetPointData().RemoveArray("vtkValidPointMask") reader.GetOutput().GetPointData().RemoveArray("vtkGhostType") # print reader.GetOutput().GetPointData() # print reader.GetOutput().GetBounds() bounds = numpy.zeros(6) reader.GetOutput().GetBounds(bounds) # print( 'bounds={0}'.format( bounds )) dimension = 3 if abs(bounds[5] - bounds[4]) < 1e-5: dimension = 2 if reader.GetOutput().GetSpacing()[2] == 0: reader.GetOutput().SetSpacing(reader.GetOutput().GetSpacing()[0], reader.GetOutput().GetSpacing()[1], 1) return (reader.GetOutput(), bounds, dimension)
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)})
def main(): path = "yC31/" # the variable name of data array which we used to analyze daryName = "v03" files = os.listdir(path) #for i in range(0, 10): for i in range(0, len(files)): filename = path + files[i] print(filename) # data reader reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0) # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetScalars(daryName)) plt.hist(dary, color="blue", bins=20) titlename = "Histogram of v03 timestep " + files[i][22:27] plt.title(titlename) savefilename = "plots/hists/v03_t_" + files[i][22:27] + ".png" plt.savefig(savefilename) '''
def test_XDMF_shape(self, tmp_path, single_phase): os.chdir(tmp_path) single_phase.export_XDMF() fname = os.path.splitext(os.path.basename( single_phase.fname))[0] + '.xdmf' reader_xdmf = vtk.vtkXdmfReader() reader_xdmf.SetFileName(fname) reader_xdmf.Update() dim_xdmf = reader_xdmf.GetOutput().GetDimensions() bounds_xdmf = reader_xdmf.GetOutput().GetBounds() single_phase.view('increments', 0).export_VTK() fname = os.path.splitext(os.path.basename( single_phase.fname))[0] + '_inc00.vti' for i in range(10): # waiting for parallel IO reader_vti = vtk.vtkXMLImageDataReader() reader_vti.SetFileName(fname) reader_vti.Update() dim_vti = reader_vti.GetOutput().GetDimensions() bounds_vti = reader_vti.GetOutput().GetBounds() if dim_vti == dim_xdmf and bounds_vti == bounds_xdmf: return time.sleep(.5) assert False
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()
def main(): colors = vtk.vtkNamedColors() file_name = get_program_parameters() # Read the source file. reader = vtk.vtkXMLImageDataReader() reader.SetFileName(file_name) # Create the mapper that creates graphics elements mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(reader.GetOutputPort()) # Create the Actor actor = vtk.vtkActor() actor.SetMapper(mapper) # show the edges of the image grid actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetColor(colors.GetColor3d("DarkSalmon")) # Create the Renderer renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.ResetCamera() renderer.SetBackground(colors.GetColor3d("Silver")) # Create the RendererWindow renderer_window = vtk.vtkRenderWindow() renderer_window.AddRenderer(renderer) # Create the RendererWindowInteractor and display the vti file interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderer_window) interactor.Initialize() interactor.Start()
def main(args): IMAGE_FILENAME = args.image_data THRESHOLD = args.t DATA_FILENAME = args.data if not os.path.exists('./TEST_DATA'): os.mkdir('TEST_DATA') #Read vti file ref = vtk.vtkXMLImageDataReader() ref.SetFileName(IMAGE_FILENAME) ref.Update() #Read your data into another polydata variable for reading image = vtk.vtkPolyData() image = ref.GetOutput() global vprint if args.v: def vprint(*args): # Print each argument separately so caller doesn't need to # stuff everything to be printed into a single string for arg in args: print(arg), else: vprint = lambda *a: None heart = read_polydata(args.heart) #determinePerfusionVolumesMask(image,heart,args.t) #centerlines = ['LAD_CAR_004_centerlines.vtp','LCX_CAR_004_centerlines.vtp','RCA_CAR_004_centerlines.vtp'] #centerline_dict = {'LAD_CAR_004_centerlines':0,'LCX_CAR_004_centerlines':1,'RCA_CAR_004_centerlines':2} #centerlines = ['RCA_CAR_004_centerlines.vtp'] centerline_dir = 'TEST_DATA' centerlines = [ 'LCA_adult_mouse_centerlines.vtp', 'RSA_adult_mouse_centerlines.vtp', 'RCA_adult_mouse_centerlines.vtp' ] centerline_dict = { 'LCA_adult_mouse_centerlines': 0, 'RCA_adult_mouse_centerlines': 1, 'RSA_adult_mouse_centerlines': 2 } vtk_centerline_data = dict() for i in centerlines: if not os.path.isfile('./' + 'heart_' + i.split('.')[0] + '.vtu'): cap_center_coordinates = calculateCapCenters(caps) centerline = intializeVTP(os.path.join(centerline_dir, i), vprint) coords = getCoords(centerline) weights = getWeights(centerline, option=0) volumes = determineCenterlinePerfusionVolumes( coords, weights, heart, 'heart_' + i.split('.')[0] + '.vtu') centerline_heart = intializeVTU('heart_' + i.split('.')[0] + '.vtu', vprint) vtk_centerline_data[i.split( '.')[0]] = centerline_heart.GetPointData().GetArray('distance_map') if len(vtk_centerline_data) == len(centerlines): markTerritories(heart, vtk_centerline_data, centerline_dict) write_polydata(heart, args.vtu_data)
def test(): reader = vtk.vtkXMLImageDataReader() reader.SetFileName("C:/Users/Asus/Dropbox/2017-18/ScientificCompAndVisualization/Semana2/SS_2017-master/SS_2017-master/data/wind_image.vti") volume = vtk.vtkVolume() #mapper = vtk.vtkFixedPointVolumeRayCastMapper() mapper = vtk.vtkGPUVolumeRayCastMapper() mapper.SetBlendModeToMinimumIntensity(); mapper.SetSampleDistance(0.1) mapper.SetAutoAdjustSampleDistances(0) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iRen = vtk.vtkRenderWindowInteractor() # Set connections mapper.SetInputConnection(reader.GetOutputPort()); volume.SetMapper(mapper) ren.AddViewProp(volume) renWin.AddRenderer(ren) iRen.SetRenderWindow(renWin) # Define opacity transfer function and color functions opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(0.1, 1.0) opacityTransferFunction.AddPoint(14, 0.5) # Create transfer mapping scalar value to color colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(1.5, 1.0, 1.0, 0.0) colorTransferFunction.AddRGBPoint(0.5, 1.0, 0.0, 0.0) colorTransferFunction.AddRGBPoint(3.0, 0.0, 1.0, 0.0) colorTransferFunction.AddRGBPoint(6.0, 0.0, 1.0, 1.0) colorTransferFunction.AddRGBPoint(14.0, 0.0, 0.0, 1.0) # Now set the opacity and the color volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.ShadeOff() volumeProperty.SetInterpolationTypeToLinear() volume.SetProperty(volumeProperty) renderer = vtk.vtkRenderer() renderer.SetBackground(0.5, 0.5, 0.5) renderer.AddVolume(volume) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(500, 500) renderWindow.Render() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renderWindow) iren.Start()
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
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) })
def test_image_data(field_data, compression_fixture, format_fixture, ordering_fixture): coords, r, e_r, field, order = field_data dim = r.ndim f = io.StringIO() compress = compression_fixture.param format = format_fixture.param with ImageData(f, [(min(x), max(x)) for x in coords], [x.size for x in coords], compression=compress, byte_order=order) as fh: fh.addPointData(DataArray(r, range(dim), 'point', ordering_fixture.param), vtk_format=format).addCellData( DataArray(e_r, range(dim), 'cell', ordering_fixture.param), vtk_format=format).addFieldData(DataArray( field, [0], 'field', ordering_fixture.param), vtk_format=format) reader = vtkXMLImageDataReader() vtk_r, vtk_e_r, vtk_f = get_vtk_data(reader, f) vtk_r = vtk_r.reshape(r.shape, order='F') vtk_e_r = vtk_e_r.reshape(e_r.shape, order='F') \ .transpose(ordering_fixture.transp(dim)) assert all(vtk_r == r) assert all(vtk_e_r == e_r) assert all(vtk_f == field)
def load_image_to_nifty(fn): """ This function imports image file as vtk image. Args: fn: filename of the image data Return: label: label map as a vtk image """ import SimpleITK as sitk ext = fn.split(os.extsep)[-1] if ext == 'vti': reader = vtk.vtkXMLImageDataReader() reader.SetFileName(fn) reader.Update() label_vtk = reader.GetOutput() size = label_vtk.GetDimensions() py_arr = np.reshape(vtk_to_numpy( label_vtk.GetPointData().GetScalars()), tuple(size), order='F') label = sitk.GetImageFromArray(py_arr.transpose(2, 1, 0)) label.SetOrigin(label_vtk.GetOrigin()) label.SetSpacing(label_vtk.GetSpacing()) label.SetDirection(np.eye(3).ravel()) elif ext == 'nii' or ext == 'nii.gz': label = sitk.ReadImage(fn) else: raise IOError("File extension is not recognized: ", ext) return label
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 })
def from_vti(cls, fname, idx=0): """ Get data and metadata from a VTK file. Assumes gprMax 'material' array has index 0. """ reader = vtk.vtkXMLImageDataReader() reader.SetFileName(fname) reader.Update() output = reader.GetOutput() dx_dy_dz = reader.GetOutput().GetSpacing() arr = cls._get_vti_array(output, 0) pml = (cls._get_vti_array(output, 1) == 1).astype(int) npml = np.where(pml[:, pml.shape[1]//2] == 0)[0][0] # Squeeze out the last dim if it's really a 2D model. if arr.shape[-1] == 1: arr = arr.squeeze() dx, dz, dy = dx_dy_dz # Careful! gprMax y is vertical (depth). params = {'dx_dy_dz': (dx, dy, dz), 'dx': dx, 'dz': dz, 'npml': npml, 'domain': 'depth', } return cls(arr, params)
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()
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]
def Import(filename): reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) # TODO: Check if the code bellow is necessary reader.WholeSlicesOn() reader.Update() return reader.GetOutput()
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
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()
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
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"
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
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()
def _load_data_from_file(self, file_path): """Loads scanvolume data from file. Also sets the volume as input for the sliceviewers """ #self.frame.SetStatusText("Opening file: %s..." % (file_path)) filename = os.path.split(file_path)[1] fileBaseName = os.path.splitext(filename)[0] self.frame._set_filename(filename) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(file_path) reader.Update() self.set_input(0, reader.GetOutput())
def __init__(self,offset,get=1,file='data',mirrorPlane=None,silent=0): self.offset=offset self.filenameout = file self.isLoaded = False self.mirrorPlane=mirrorPlane self.silent = silent self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vti']) self.datareader = v.vtkXMLImageDataReader() if (self.silent == 0): print '========================================' if (self.silent == 0): print 'loading file %s' % (self.filename) if get != None: self.getAll()
def test_vtk_exceptions(self): """Test if VTK has been patched with our VTK error to Python exception patch. """ import vtk a = vtk.vtkXMLImageDataReader() a.SetFileName('blata22 hello') b = vtk.vtkMarchingCubes() b.SetInput(a.GetOutput()) try: b.Update() except RuntimeError, e: self.failUnless(str(e).startswith('ERROR'))
def reader_vti(filename): logging.debug("In data.reader_vti()") append = vtk.vtkImageAppend() append.ReleaseDataFlagOn() append.SetAppendAxis(2) reader = vtk.vtkXMLImageDataReader() reader.ReleaseDataFlagOn() if os.path.exists(filename): reader.SetFileName(filename) # reader.GetOutput().Register(reader) reader.Update() return vtk.vtkImageData.SafeDownCast(reader.GetOutput()) else: i = 0 paths = [] while True: partName = filename.replace(".vti", "{0}.vti".format(i)) # print partName if os.path.exists(partName): paths.append(partName) else: break i = i + 1 # paths.reverse() for i, partName in enumerate(paths): reader = vtk.vtkXMLImageDataReader() reader.ReleaseDataFlagOn() reader.SetFileName(partName) # reader.GetOutput().Register(reader) reader.Update() append.SetInput(i, reader.GetOutput()) append.Update() output = append.GetOutput() for i in range(append.GetNumberOfInputs()): append.GetInput(i).ReleaseData() return output
def __init__(self, vtifname, parallel=False, dtype=np.float64): if parallel: self.reader = vtk.vtkXMLPImageDataReader() else: 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[2]-1, self.dim[1]-1, self.dim[0]-1] self.s_vec = [self.dim[2]-1, self.dim[1]-1, self.dim[0]-1,3] self.trim_0 = [0,0,0] self.trim_1 = [x-1 for x in self.dim] self.dtype = dtype
def loadVti(self, filename): """ Loads the specified DataSet from disk and returns it as vtkImageData @param filename The file where Dataset is loaded from """ if not self.reader or self.filename != filename: self.filename = filename self.reader = vtk.vtkXMLImageDataReader() self.reader.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.reader, 'ProgressEvent', self.updateProgress) filepath = os.path.join(self.path, filename) if not self.reader.CanReadFile(filepath): Logging.error("Cannot read file", "Cannot read XML Image Data File %s"%filename) self.reader.SetFileName(filepath) self.updateProgress(None, None) data = self.reader.GetOutput() return data
def to_h5(fname, outname): 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>0] = 1 print m.dtype, m.shape mh5 = h5py.File(outname, 'w') mh5.create_dataset('spacing', data=o.GetSpacing()); mh5.create_dataset('data', shape=m.shape, dtype=m.dtype) d = mh5['data'] d[:] = m mh5.flush() mh5.close()
def vti2arr(fileIn): """Convert voxel-array from VTI to Numpy 3D image array. Parameters ---------- fileIn : str Path for input VTI file. fileOut : str Path for output MAT file. Returns ------- V : np.ndarray Lx x Ly x Lz 3D array, representing the voxel-array. metadata : dict Dict containing metadata about voxel array: - 'spacing': array of voxel dimensions (pixel/mm) """ import numpy as np import vtk from vtk.util import numpy_support as nps 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]) #V = flatV.reshape(dim) metadata = {} spacing = np.array(vtkImageData.GetSpacing())[::-1] #spacing = np.array(vtkImageData.GetSpacing()) metadata['spacing'] = spacing return V, metadata
def readImage( filename, verbose=1): myVTK.myPrint(verbose, "*** readImage: " + filename + " ***") if ('vtk' in filename): image_reader = vtk.vtkImageDataReader() elif ('vti' in filename): image_reader = vtk.vtkXMLImageDataReader() else: assert 0, "File must be .vtk or .vti. Aborting." image_reader.SetFileName(filename) image_reader.Update() image = image_reader.GetOutput() if (verbose): print "n_points = " + str(image.GetNumberOfPoints()) return image
def readImage( filename, verbose=0): myVTK.myPrint(verbose, "*** readImage: "+filename+" ***") assert (os.path.isfile(filename)), "Wrong filename (\""+filename+"\"). Aborting." if ('vtk' in filename): image_reader = vtk.vtkImageDataReader() elif ('vti' in filename): image_reader = vtk.vtkXMLImageDataReader() else: assert 0, "File must be .vtk or .vti. Aborting." image_reader.SetFileName(filename) image_reader.Update() image = image_reader.GetOutput() myVTK.myPrint(verbose-1, "n_points = "+str(image.GetNumberOfPoints())) return image