def load_vtk(file_number,vtk_dir="vtk_files",organs=list_organs): """Loads .vtk file into tensor given file number""" file_number = str(file_number).zfill(3) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(vtk_dir+"/500%s_fat_content.vtk" %(file_number)) reader.Update() data_fat = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) x_range, y_range, z_range = reader.GetOutput().GetDimensions() data = np.zeros(6*x_range*y_range*z_range).reshape(6,x_range,y_range,z_range) data[0] = data_fat.reshape(x_range,y_range,z_range) #reader.SetFileName(vtk_dir+"/500%s_wat_content.vtk" %(file_number)) #reader.Update() #data_wat = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) #data[1] = data_wat.reshape(x_range,y_range,z_range) for i,organ in enumerate(organs): reader.SetFileName(vtk_dir+"/binary_"+organ+"500%s.vtk" %(file_number)) reader.Update() data_organ = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) data[i+1] = data_organ.reshape(x_range,y_range,z_range) grid = torch.from_numpy(data[:,54:214,:,54:214]) return grid.to(dtype=torch.float32)
def load_surface(filename): # Set a VTKReader reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filename) reader.Update() return reader
def read_3D_file(filename): """ Read a mesh from an STL, OBJ, PLY or VTK file. """ def _read(filename, reader, getVtkReader): reader.SetFileName(filename) reader.Update() if getVtkReader: return reader return reader.GetOutput() if not os.path.exists(filename): raise IOError('Input file "{0}" was not found'.format(filename)) filenameLower = filename.lower() getVtkReader = False extension = get_filename_extension(filenameLower) if extension == 'stl': reader = vtk.vtkSTLReader() sm = _read(filename, reader, getVtkReader) elif extension == 'obj': reader = vtk.vtkOBJReader() sm = _read(filename, reader, getVtkReader) elif extension == 'ply': reader = vtk.vtkPLYReader() sm = _read(filename, reader, getVtkReader) elif extension == 'vtk': reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filename) reader.Update() if reader.IsFilePolyData(): sm = reader.GetPolyDataOutput() else: raise Exception else: raise Exception('Unknown file format : {0}'.format(extension)) return sm
def load_vtk(file_number): """Loads .vtk file into tensor given file number""" file_number = str(file_number).zfill(3) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName("../../Project course/500%s_fat_content.vtk" % (file_number)) reader.Update() data_fat = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) x_range, y_range, z_range = reader.GetOutput().GetDimensions() data_fat = data_fat.reshape(x_range, y_range, z_range) reader.SetFileName("../../Project course/500%s_wat_content.vtk" % (file_number)) reader.Update() data_wat = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) data_wat = data_wat.reshape(x_range, y_range, z_range) reader.SetFileName("../../Project course/binary_liver500%s.vtk" % (file_number)) reader.Update() data_liv = vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars()) data_liv = data_liv.reshape(x_range, y_range, z_range) data = np.zeros(3 * x_range * y_range * z_range).reshape( 3, x_range, y_range, z_range) data[0] = data_fat data[1] = data_wat data[2] = data_liv grid = torch.from_numpy(data) return grid.to(dtype=torch.float32)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGenericDataObjectReader(), 'Reading vtkGenericDataObject.', (), ('vtkGenericDataObject',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def load(fname, dataset_type=None): """ Load from VTK file. Parameters ---------- fname : str or pathlib.Path Filename for reading. Valid extensions are .vti, .vtr, .vtu, .vtp, and .vtk. dataset_type : {'vtkImageData', ''vtkRectilinearGrid', 'vtkUnstructuredGrid', 'vtkPolyData'}, optional Name of the vtk.vtkDataSet subclass when opening a .vtk file. Returns ------- loaded : damask.VTK VTK-based geometry from file. """ if not os.path.isfile(fname): # vtk has a strange error handling raise FileNotFoundError(f'No such file: {fname}') ext = Path(fname).suffix if ext == '.vtk' or dataset_type is not None: reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(str(fname)) if dataset_type is None: raise TypeError('Dataset type for *.vtk file not given.') elif dataset_type.lower().endswith(('imagedata', 'image_data')): reader.Update() vtk_data = reader.GetStructuredPointsOutput() elif dataset_type.lower().endswith( ('rectilineargrid', 'rectilinear_grid')): reader.Update() vtk_data = reader.GetRectilinearGridOutput() elif dataset_type.lower().endswith( ('unstructuredgrid', 'unstructured_grid')): reader.Update() vtk_data = reader.GetUnstructuredGridOutput() elif dataset_type.lower().endswith(('polydata', 'poly_data')): reader.Update() vtk_data = reader.GetPolyDataOutput() else: raise TypeError( f'Unknown dataset type {dataset_type} for vtk file') else: if ext == '.vti': reader = vtk.vtkXMLImageDataReader() elif ext == '.vtr': reader = vtk.vtkXMLRectilinearGridReader() elif ext == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif ext == '.vtp': reader = vtk.vtkXMLPolyDataReader() else: raise TypeError(f'Unknown file extension {ext}') reader.SetFileName(str(fname)) reader.Update() vtk_data = reader.GetOutput() return VTK(vtk_data)
def LabelToSurface(label_path, surface_path, lcc=False, smoothIterations=15,relaxationFactor=0.1): tqdm.write("Converting segmentation label to surface file: {}".format(label_path)) # binary path if platform == "linux" or platform == "linux2": bin_path = "/home/jacky/Projects/CFD_intraranial/cxx/label_to_mesh/build_linux/LabelToMesh" elif platform == "darwin": return elif platform == "win32": bin_path = "D:/projects/CFD_intracranial/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1,-1,1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(smoothIterations); smoothFilter.SetRelaxationFactor(relaxationFactor); smoothFilter.FeatureEdgeSmoothingOff(); smoothFilter.BoundarySmoothingOn(); smoothFilter.Update(); surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() if pathlib.Path(surface_path).suffix == ".vtk": writer = vtk.vtkGenericDataObjectWriter() elif pathlib.Path(surface_path).suffix == ".vtp": writer = vtk.vtkXMLPolyDataWriter() elif pathlib.Path(surface_path).suffix == ".stl": writer = vtk.vtkSTLWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update() tqdm.write("Convert segmentation label to surface file complete: {}".format(label_path))
def load_vtk(file): """Get raw data from .vtk file.""" reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(file) reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.Update() return reader.GetOutput()
def makeFromVTK3(fileName,units, time=0,forceVersion2=False): ''' Create fields from a VTK unstructured grid file (``.vtu``, format version 3, or ``.vtp`` with *forceVersion2*); the mesh is shared between fields. ``vtk.vtkXMLGenericDataObjectReader`` is used to open the file (unless *forceVersion2* is set), but it is checked that contained dataset is a ``vtk.vtkUnstructuredGrid`` and an error is raised if not. .. note:: Units are not supported when loading from VTK, all fields will have ``None`` unit assigned. :param str fileName: VTK (``*.vtu``) file :param PhysicalUnit units: units of read values :param float time: time value for created fields (time is not saved in VTK3, thus cannot be recovered) :param bool forceVersion2: if ``True``, ``vtk.vtkGenericDataObjectReader`` (for VTK version 2) will be used to open the file, isntead of ``vtk.vtkXMLGenericDataObjectReader``; this also supposes *fileName* ends with ``.vtk`` (not checked, but may cause an error). :return: list of new :obj:`Field` instances :rtype: [Field,Field,...] ''' import vtk from . import fieldID #rr=vtk.vtkXMLUnstructuredGridReader() if forceVersion2 or fileName.endswith('.vtk'): rr=vtk.vtkGenericDataObjectReader() else: rr=vtk.vtkXMLGenericDataObjectReader() rr.SetFileName(fileName) rr.Update() ugrid=rr.GetOutput() if not isinstance(ugrid,vtk.vtkUnstructuredGrid): raise RuntimeError("vtkDataObject read from '%s' must be a vtkUnstructuredGrid (not a %s)"%(fileName,ugrid.__class__.__name__)) #import sys #sys.stderr.write(str((ugrid,ugrid.__class__,vtk.vtkUnstructuredGrid))) # make mesh -- implemented separately mesh=Mesh.UnstructuredMesh.makeFromVtkUnstructuredGrid(ugrid) # fields which will be returned ret=[] # get cell and point data cd,pd=ugrid.GetCellData(),ugrid.GetPointData() for data,fieldType in (pd,FieldType.FT_vertexBased),(cd,FieldType.FT_cellBased): for idata in range(data.GetNumberOfArrays()): aname,arr=pd.GetArrayName(idata),pd.GetArray(idata) nt=arr.GetNumberOfTuples() if nt==0: raise RuntimeError("Zero values in field '%s', unable to determine value type."%aname) t0=arr.GetTuple(0) valueType=ValueType.fromNumberOfComponents(len(arr.GetTuple(0))) # this will raise KeyError if fieldID with that name not defined fid=fieldID.FieldID[aname] # get actual values as tuples values=[arr.GetTuple(t) for t in range(nt)] ret.append(Field( mesh=mesh, fieldID=fid, units=units, # not stored at all time=time, # not stored either, set by caller valueType=valueType, values=values, fieldType=fieldType )) return ret
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGenericDataObjectReader(), "Reading vtkGenericDataObject.", (), ("vtkGenericDataObject",), replaceDoc=True, inputFunctions=None, outputFunctions=None, )
def makeFromVTK3(fileName,time=0,forceVersion2=False): ''' Create fields from a VTK unstructured grid file (``.vtu``, format version 3, or ``.vtp`` with *forceVersion2*); the mesh is shared between fields. ``vtk.vtkXMLGenericDataObjectReader`` is used to open the file (unless *forceVersion2* is set), but it is checked that contained dataset is a ``vtk.vtkUnstructuredGrid`` and an error is raised if not. .. note:: Units are not supported when loading from VTK, all fields will have ``None`` unit assigned. :param str fileName: VTK (``*.vtu``) file :param float time: time value for created fields (time is not saved in VTK3, thus cannot be recovered) :param bool forceVersion2: if ``True``, ``vtk.vtkGenericDataObjectReader`` (for VTK version 2) will be used to open the file, isntead of ``vtk.vtkXMLGenericDataObjectReader``; this also supposes *fileName* ends with ``.vtk`` (not checked, but may cause an error). :return: list of new :obj:`Field` instances :rtype: [Field,Field,...] ''' import vtk from . import fieldID #rr=vtk.vtkXMLUnstructuredGridReader() if forceVersion2 or fileName.endswith('.vtk'): rr=vtk.vtkGenericDataObjectReader() else: rr=vtk.vtkXMLGenericDataObjectReader() rr.SetFileName(fileName) rr.Update() ugrid=rr.GetOutput() if not isinstance(ugrid,vtk.vtkUnstructuredGrid): raise RuntimeError("vtkDataObject read from '%s' must be a vtkUnstructuredGrid (not a %s)"%(fileName,ugrid.__class__.__name__)) #import sys #sys.stderr.write(str((ugrid,ugrid.__class__,vtk.vtkUnstructuredGrid))) # make mesh -- implemented separately mesh=mupif.Mesh.UnstructuredMesh.makeFromVtkUnstructuredGrid(ugrid) # fields which will be returned ret=[] # get cell and point data cd,pd=ugrid.GetCellData(),ugrid.GetPointData() for data,fieldType in (pd,FieldType.FT_vertexBased),(cd,FieldType.FT_cellBased): for idata in range(data.GetNumberOfArrays()): aname,arr=pd.GetArrayName(idata),pd.GetArray(idata) nt=arr.GetNumberOfTuples() if nt==0: raise RuntimeError("Zero values in field '%s', unable to determine value type."%aname) t0=arr.GetTuple(0) valueType=ValueType.fromNumberOfComponents(len(arr.GetTuple(0))) # this will raise KeyError if fieldID with that name not defined fid=fieldID.FieldID[aname] # get actual values as tuples values=[arr.GetTuple(t) for t in range(nt)] ret.append(Field( mesh=mesh, fieldID=fid, units=None, # not stored at all time=time, # not stored either, set by caller valueType=valueType, values=values, fieldType=fieldType )) return ret
def main(): filename = get_program_parameters() # Get all data from the file reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filename) reader.Update() # All of the standard data types can be checked and obtained like this: if reader.IsFilePolyData(): print("output is a polydata") output = reader.GetPolyDataOutput() print("output has", output.GetNumberOfPoints(), "points.")
def readVTK(inputFileName): """ IO :: read a file.txt """ reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(inputFileName) reader.Update() # Needed because of GetScalarRange append = vtk.vtkAppendPolyData() append.AddInputData(reader.GetOutput()) append.Update() pdata = append.GetOutput() return pdata
def convertFile(filepath, outdir): if not os.path.isdir(outdir): os.makedirs(outdir) if os.path.isfile(filepath): basename = os.path.basename(filepath) print("Copying file:", basename) basename = os.path.splitext(basename)[0] outfile = os.path.join(outdir, basename + ".ply") reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filepath) reader.Update() writer = vtk.vtkPLYWriter() writer.SetInputConnection(reader.GetOutputPort()) writer.SetFileName(outfile) return writer.Write() == 1 return False
def initVessels(self): qDebug('initVessels()') if os.name == 'nt': filename = os.path.join(filedir, '../../data/Abdomen/Connected.vtp') if IOUSFAN: #filename = 'e:/analogic/TrialVTK/data/VesselMeshData.vtk' filename = 'e:/analogic/TrialVTK/data/LiverVesselMeshData.vtk' else: filename = '/home/jmh/bkmedical/data/CT/Connected.vtp' # read data if IOUSFAN: reader = vtk.vtkGenericDataObjectReader() else: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename) reader.Update() connectFilter = vtk.vtkPolyDataConnectivityFilter() connectFilter.SetInputConnection(reader.GetOutputPort()) connectFilter.SetExtractionModeToLargestRegion() connectFilter.Update() self.vesselPolyData = self.scale(connectFilter.GetOutput()) # compute normals self.vesselNormals = vtk.vtkPolyDataNormals() self.vesselNormals.SetInputData(self.vesselPolyData) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.vesselNormals.GetOutputPort()) # actor for vessels self.vessels = vtk.vtkActor() self.vessels.SetMapper(mapper) prop = self.vessels.GetProperty() if self.brighter25: prop.SetColor(vtk.vtkColor3d(hexCol("#517487"))) # 25% lighter else: prop.SetColor(vtk.vtkColor3d(hexCol("#415d6c"))) # assign actor to the renderer self.renderer.AddActor(self.vessels)
def load(fname,dataset_type=None): """ Create VTK from file. Parameters ---------- fname : str or pathlib.Path Filename for reading. Valid extensions are .vtr, .vtu, .vtp, and .vtk. dataset_type : str, optional Name of the vtk.vtkDataSet subclass when opening a .vtk file. Valid types are vtkRectilinearGrid, vtkUnstructuredGrid, and vtkPolyData. """ ext = Path(fname).suffix if ext == '.vtk' or dataset_type is not None: reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(str(fname)) if dataset_type is None: raise TypeError('Dataset type for *.vtk file not given.') elif dataset_type.lower().endswith('rectilineargrid'): reader.Update() vtk_data = reader.GetRectilinearGridOutput() elif dataset_type.lower().endswith('unstructuredgrid'): reader.Update() vtk_data = reader.GetUnstructuredGridOutput() elif dataset_type.lower().endswith('polydata'): reader.Update() vtk_data = reader.GetPolyDataOutput() else: raise TypeError(f'Unknown dataset type {dataset_type} for vtk file') else: if ext == '.vtr': reader = vtk.vtkXMLRectilinearGridReader() elif ext == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif ext == '.vtp': reader = vtk.vtkXMLPolyDataReader() else: raise TypeError(f'Unknown file extension {ext}') reader.SetFileName(str(fname)) reader.Update() vtk_data = reader.GetOutput() return VTK(vtk_data)
def LabelToSurface(label_path, surface_path, lcc=False): print("Converting segmentation label to surface file:", label_path) # binary path bin_path = "D:/Dr_Simon_Yu/CFD_intracranial/code/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1, -1, 1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(15) smoothFilter.SetRelaxationFactor(0.1) smoothFilter.FeatureEdgeSmoothingOff() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update()
def from_file(fname, dataset_type=None): """ Create VTK from file. Parameters ---------- fname : str Filename for reading. Valid extensions are .vtr, .vtu, .vtp, and .vtk. dataset_type : str, optional Name of the vtk.vtkDataSet subclass when opening an .vtk file. Valid types are vtkRectilinearGrid, vtkUnstructuredGrid, and vtkPolyData. """ ext = os.path.splitext(fname)[1] if ext == '.vtk': reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(fname) reader.Update() if dataset_type is None: raise TypeError('Dataset type for *.vtk file not given.') elif dataset_type.lower().endswith('rectilineargrid'): geom = reader.GetRectilinearGridOutput() elif dataset_type.lower().endswith('unstructuredgrid'): geom = reader.GetUnstructuredGridOutput() elif dataset_type.lower().endswith('polydata'): geom = reader.GetPolyDataOutput() else: raise TypeError('Unknown dataset type for vtk file {}'.format( dataset_type)) else: if ext == '.vtr': reader = vtk.vtkXMLRectilinearGridReader() elif ext == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif ext == '.vtp': reader = vtk.vtkXMLPolyDataReader() else: raise TypeError('Unknown file extension {}'.format(ext)) reader.SetFileName(fname) reader.Update() geom = reader.GetOutput() return VTK(geom)
def get_coordinates(fid): """ I couldn't, for the life of me, figure out how to get the mesh dimensions out of the mayavi objects, so instead just get it from using the VTK lib :type fid: str :param fid: file id of the .vtk file :rtype: numpy array :return: Nx3 numpy array with columns corresponding to x, y, z """ import vtk from vtk.util.numpy_support import vtk_to_numpy reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(fid) reader.Update() coords = vtk_to_numpy(reader.GetOutput().GetPoints().GetData()) return coords
def vtp2csv(fileIn, fileOut): reader = vtk.vtkGenericDataObjectReader() reader = vtk.vtkXMLPPolyDataReader() reader.SetFileName(fileIn) reader.Update() point_obj = reader.GetOutput() points = point_obj.GetPoints() table = vtk.vtkDataObjectToTable() table.SetInputData(point_obj) table.Update() table.GetOutput().AddColumn(points.GetData()) table.Update() writer = vtk.vtkDelimitedTextWriter() writer.SetInputConnection(table.GetOutputPort()) writer.SetFileName(fileOut) writer.Update() writer.Write()
def read_vtk_format(filename, type='point'): ''' file: .vtk file or .stl type: 'point', 'poly' return: vtkPoints or vtkPolyData ''' print 'Reading ', filename sufx = filename.split('.')[-1] if sufx == 'vtk': reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filename) reader.Update() geo = vtk.vtkGeometryFilter( ) # convert unstructed grid to a poly data, cannot write to stl now geo.SetInputData(reader.GetOutput()) geo.Update() poly = geo.GetOutput() # important: convert point to triangle triangle = vtk.vtkTriangleFilter() triangle.SetInputData(poly) triangle.Update() poly = triangle.GetOutput() return poly elif sufx == 'stl': reader = vtk.vtkSTLReader() reader.SetFileName(filename) reader.Update() points = reader.GetOutput().GetPoints() poly = reader.GetOutput() else: raise ValueError('Support stl file only...') if type == 'point': return points elif type == 'poly': return poly else: raise ValueError('Invalid output type')
def setup_vtk(filename): """ Set vtk reader and get vector dimansions. """ from vtk import vtkStructuredGridReader from vtk import vtkGenericDataObjectReader from vtk import vtkRectilinearGridReader from vtk import vtkStructuredPointsReader reader = vtkGenericDataObjectReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() dim = data.GetDimensions() sca = list(dim) sca = [i - 1 for i in dim] vec = list(dim) vec = [i - 1 for i in dim] vec.append(3) return data, vec, sca, dim
def centerlineCalculation(working_dir, relaxation=0, post=False): if post: # compute centerline command = binary_path + " " + \ os.path.join(working_dir,"surface_capped.stl") + " " + \ os.path.join(working_dir,"surface_capped.stl") + " " + \ os.path.join(working_dir,"centerline_clipped.vtp") else: if not os.path.exists(os.path.join(working_dir, "surface.vtk")): return # convert vtk to stl reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(os.path.join(working_dir, "surface.vtk")) reader.Update() surface = reader.GetOutput() if relaxation > 0: smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(100) smoothFilter.SetRelaxationFactor(relaxation) smoothFilter.FeatureEdgeSmoothingOff() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() surface.DeepCopy(smoothFilter.GetOutput()) writer = vtk.vtkSTLWriter() writer.SetFileName(os.path.join(working_dir, "surface.stl")) writer.SetInputData(surface) writer.Update() # compute centerline command = binary_path + " " + \ os.path.join(working_dir,"surface.stl") + " " + \ os.path.join(working_dir,"surface_capped.stl") + " " + \ os.path.join(working_dir,"centerline.vtp") os.system(command)
def initLiver(self): qDebug('initLiver()') if os.name == 'nt': filename = os.path.join( filedir, '../../data/Abdomen/Liver_3D-interpolation.vtp') if IOUSFAN: filename = 'e:/analogic/TrialVTK/data/segmented_liver_ITK_snap.vtk' else: filename = '/home/jmh/bkmedical/data/CT/Liver_3D-interpolation.vtp' if IOUSFAN: reader = vtk.vtkGenericDataObjectReader() else: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename) reader.Update() connectFilter = vtk.vtkPolyDataConnectivityFilter() connectFilter.SetInputConnection(reader.GetOutputPort()) connectFilter.SetExtractionModeToLargestRegion() connectFilter.Update() surfNormals = vtk.vtkPolyDataNormals() surfNormals.SetInputData(self.scale(connectFilter.GetOutput())) #Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surfNormals.GetOutputPort()) # was reader self.liver = vtk.vtkActor() self.liver.SetMapper(mapper) prop = self.liver.GetProperty() if self.brighter25: prop.SetColor(vtk.vtkColor3d(hexCol("#873927"))) else: prop.SetColor(vtk.vtkColor3d(hexCol("#6c2e1f"))) prop.SetOpacity(self.opacity) self.renderer.AddActor(self.liver)
def gmsh1D(listPoints, h): # use gmsh in 1D # print (listPoints) if isinstance(listPoints, (np.ndarray, list, tuple)): # test if listPoints is a np.array, list or tuple listPoints = np.asarray(listPoints) # convert in np.array else: raise ValueError( 'List of points must be a numpy array, list or tuple.') exit() nPoints = listPoints.shape[0] # store number of points if not isinstance( h, (float, int, np.ndarray, list, tuple)): # test if h is an other struc raise ValueError('h must be a scalar, numpy array, list or tuple.') exit() if isinstance( h, (np.ndarray, list, tuple)): # test if h is a np.array, list or tuple h = np.asarray(h) # convert h in np.array if h.shape[0] != nPoints: # /!\ size are different raise ValueError('h must have the same size of number of points.') else: h = np.full( (nPoints), h) # h is a number, convert in np.array : value h, size nPoints # print (h) if nPoints < 2: # create a line is not possible without 2 points raise ValueError('You have to precise 2 points minimum.') exit() listPoints_ = np.ndarray((nPoints, 3)) # store 'point' structure of GMSH for i in np.arange(nPoints): # loop over points if isinstance( listPoints[i], (np.ndarray, list, tuple)): # convert point [i] in np.array listPoints[i] = np.asarray(listPoints[i]) else: raise ValueError( '{}ieme point must be a numpy array, list or tuple.'.format(i)) exit() if listPoints[i].shape[0] == 1: # point [i] is [x] listPoints_[i] = np.array([listPoints[i, 0], 0., 0.]) elif listPoints[i].shape[0] == 2: # point [i] is [x, y] listPoints_[i] = np.array([listPoints[i, 0], listPoints[i, 1], 0.]) else: # point [i] is [x, y, z] listPoints_[i] = listPoints[i] listPoints = listPoints_ # erase point with correct number of coordinates geom = pygmsh.built_in.Geometry() # create module of GMSH listPoints_ = [] # array of points GMSH structure for i in np.arange(nPoints): listPoints_.append( geom.add_point( # create a GMSH point listPoints[i], # point [i] = [x, y, z] lcar=h[i] # h [i] is the size at the point [i] )) listPoints = listPoints_ # erase listPoints with GMSH structure for i in np.arange(1, nPoints): # loop over points p = listPoints[i - 1] # p1 : beginning of line p_ = listPoints[i] # p2 : end of the line geom.add_line(p, p_) # create GMSH line between p1 and p2 mesh = pygmsh.generate_mesh(geom) # generate mesh (see pyGMSH) file = tempfile.mkstemp( suffix='.vtk') # create a temporary file to write the temporary vtk meshio.write(file[1], mesh) # write output of pyGMSH in the temporary file reader = vtk.vtkGenericDataObjectReader() # Generic reader of VTK reader.SetFileName(file[1]) # set the fileName with temporary fileName reader.Update() # Update generic reader pdata = vtk.vtkPolyData() # create an empty vtkPolyData geoFilter = vtk.vtkGeometryFilter() # transform any entry in vtkPolyData geoFilter.SetInputData(reader.GetOutput()) # geoFilter.Update() # pdata.DeepCopy(geoFilter.GetOutput()) # deep copy of output of geoFilter return pdata
import vtk import os # Set filename filename = os.path.join(os.getcwd(), 'files', 'lh.vtk') # Set a VTKReader reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(filename) reader.Update() # Set a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) # Set an actor actor = vtk.vtkActor() actor.SetMapper(mapper) # Renderer ren = vtk.vtkRenderer() ren.AddActor(actor) # RenderWindow ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(ren) # WindowInteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win)
inplace = False, render = False, ) (options, filenames) = parser.parse_args() if not options.vtk: parser.error('No VTK file specified.') if not os.path.exists(options.vtk): parser.error('VTK file does not exist.') if os.path.splitext(options.vtk)[1] == '.vtr': reader = vtk.vtkXMLRectilinearGridReader() reader.SetFileName(options.vtk) reader.Update() rGrid = reader.GetOutput() elif os.path.splitext(options.vtk)[1] == '.vtk': reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(options.vtk) reader.Update() rGrid = reader.GetRectilinearGridOutput() else: parser.error('Unsupported VTK file type extension.') Npoints = rGrid.GetNumberOfPoints() Ncells = rGrid.GetNumberOfCells() damask.util.croak('{}: {} points and {} cells...'.format(options.vtk,Npoints,Ncells)) # --- loop over input files ------------------------------------------------------------------------- if filenames == []: filenames = [None]
def gmsh2D (listPoints, h, trSur = "no"): # see D1.py for more details # print (listPoints) if isinstance (listPoints, (np.ndarray, list, tuple)): listPoints = np.asarray (listPoints) else: raise ValueError('List of points must be a numpy array, list or tuple.') exit () nPoints = listPoints.shape [0] if not isinstance (h, (float, int, np.ndarray, list, tuple)): raise ValueError('h must be a scalar, numpy array, list or tuple.') exit () if isinstance (h, (np.ndarray, list, tuple)): h = np.asarray (h) if h.shape [0] != nPoints: raise ValueError('h must have the same size of number of points.') else: h = np.full ((nPoints), h) # print (h) if nPoints < 3: raise ValueError('You have to precise 3 points minimum.') exit () listPoints_ = np.ndarray ((nPoints, 3)) for i in np.arange (nPoints): if isinstance (listPoints [i], (np.ndarray, list, tuple)): listPoints [i] = np.asarray (listPoints [i]) else: raise ValueError('{}ieme point must be a numpy array, list or tuple.'.format (i)) exit () if listPoints [i].shape [0] == 1: listPoints_ [i] = np.array ([listPoints [i, 0], 0., 0.]) elif listPoints [i].shape [0] == 2: print (listPoints [i]) listPoints_ [i] = np.array ([listPoints [i, 0], listPoints [i, 1], 0.]) else: listPoints_ [i] = listPoints [i] listPoints = listPoints_ if nPoints > 3: for i, subset in zip ( np.arange (nPoints), itertools.combinations (listPoints, 4)): if not coplanar (subset [0], subset [1], subset [2], subset [3]): raise ValueError('You must choose coplanar points.') exit () geom = pygmsh.built_in.Geometry () listPoints_ = [] for i in np.arange (nPoints): listPoints_.append (geom.add_point ( listPoints [i], lcar= h [i] )) listPoints = listPoints_ listLines = [] for i in np.arange (nPoints): p = listPoints [i] if i + 1 == nPoints: p_ = listPoints [0] else: p_ = listPoints [i + 1] listLines.append (geom.add_line (p, p_)) ll = geom.add_line_loop(listLines) surface = geom.add_plane_surface(ll) if trSur == "yes": # transfinite surface : surface reguliere geom.set_transfinite_surface(surface) mesh = pygmsh.generate_mesh(geom) file = tempfile.mkstemp (suffix = '.vtk') meshio.write(file [1], mesh) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(file [1]) reader.Update() pdata = vtk.vtkPolyData() geoFilter = vtk.vtkGeometryFilter () # transform any entry in vtkPolyData geoFilter.SetInputData (reader.GetOutput ()) geoFilter.Update() pdata.DeepCopy (geoFilter.GetOutput ()) return pdata
def read_data(): reader = vtk.vtkGenericDataObjectReader() reader.SetFileName("data/SMRX.vtk") reader.Update() return reader
def Extrude(Slope,Extrusion,Plane,Model,Sediment,Start_time,End_time,Time_step,Mesh): ugrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata gridreader1=vtk.vtkUnstructuredGridReader() gridreader1.SetFileName(Slope) #.pvd gridreader1.Update() ugrid1 = gridreader1.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid1) GeomFilt1.Update() y1 = GeomFilt1.GetOutput() Extrude = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata Extrude.SetInput(y1) Extrude.SetExtrusionTypeToVectorExtrusion() Extrude.SetVector(0,0,-1) PreliminaryExtrusion = Extrude.GetOutput() PE = vtk.vtkPolyData() PE = PreliminaryExtrusion PE.Update() ugrid2 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below gridreader2=vtk.vtkXMLUnstructuredGridReader() gridreader2.SetFileName(Plane) # 000000.vtu gridreader2.Update() ugrid2 = gridreader2.GetOutput() ExtrudedPoints = PE.GetPoints() #4. take points from the extruded polydata PlanePoints = ugrid2.GetPoints() #5. get points from surface below nPoints = PE.GetNumberOfPoints() #6. for first half of points determine if above or below last surface Begin = nPoints/2 #7. if below set as the same as bottom surface (slightly above?) #8. set second half counter = 0 uPoints = ugrid2.GetPoints() for p in range(Begin,nPoints): y = uPoints.GetPoint(counter)[2:] x = ExtrudedPoints.GetPoint(p)[:2] + y ExtrudedPoints.SetPoint(p,x) counter += 1 PE.Update() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(Model) writer.SetInput(PE) writer.Update() writer.Write() ################################################################################################################# t = Start_time dt = Time_step ET = End_time et = ET-1 Save = Sediment + str(t) +'000000.vtu' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata SedimentGridreader1=vtk.vtkUnstructuredGridReader() SedimentGridreader1.SetFileName(Import) #.pvd SedimentGridreader1.Update() SedimentGrid1 = SedimentGridreader1.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(SedimentGrid1) GeomFilt2.Update() ExtrudeInput1 = GeomFilt2.GetOutput() ExtrudeSed1 = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata ExtrudeSed1.SetInput(ExtrudeInput1) ExtrudeSed1.SetExtrusionTypeToVectorExtrusion() ExtrudeSed1.SetVector(0,0,-1) PreliminarySedExtrusion1 = ExtrudeSed1.GetOutput() PSE1 = vtk.vtkPolyData() PSE1 = PreliminarySedExtrusion1 PSE1.Update() PreSurface1 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below PSreader1=vtk.vtkGenericDataObjectReader() PSreader1.SetFileName(Slope) # 000000.vtu PSreader1.Update() PreSurface1 = PSreader1.GetOutput() ExtrudedSedPoints1 = PSE1.GetPoints() #4. take points from the extruded polydata PSPoints1 = PreSurface1.GetPoints() #5. get points from surface below SedPoints1 = PSE1.GetNumberOfPoints() #6. for first half of points determine if above or below last surface BeginSed1 = nPoints/2 EndSed1 = BeginSed1 - 1 #7. if below set as the same as bottom surface (slightly above? sedcounter1 = 0 #8. set second half sedcounter2 = BeginSed1 for p in range(BeginSed1,SedPoints1): y = PSPoints1.GetPoint(sedcounter1)[2:] x = ExtrudedSedPoints1.GetPoint(p)[:2] + y ExtrudedSedPoints1.SetPoint(p,x) sedcounter1 += 1 writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(PSE1) writer.Update() writer.Write() ##################################################################################################################### while t <= et: t += dt pre = t -1 Previous = Sediment +str(pre) + '_sed_slope.pvd' PreviousSave = Sediment + str(pre)+ 'extruded_sed_slope.pvd' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid2 = vtk.vtkUnstructuredGrid() SedimentGridreader2=vtk.vtkUnstructuredGridReader() SedimentGridreader2.SetFileName(Import) #.pvd SedimentGridreader2.Update() SedimentGrid2 = SedimentGridreader2.GetOutput() GeomFilt3 = vtk.vtkGeometryFilter() GeomFilt3.SetInput(SedimentGrid2) GeomFilt3.Update() ExtrudeInput = GeomFilt3.GetOutput() ExtrudeInput2 = GeomFilt3.GetOutput() ExtrudeSed2 = vtk.vtkLinearExtrusionFilter() ExtrudeSed2.SetInput(ExtrudeInput2) ExtrudeSed2.SetExtrusionTypeToVectorExtrusion() ExtrudeSed2.SetVector(0,0,-1) PreliminarySedExtrusion2 = ExtrudeSed2.GetOutput() PSE2 = vtk.vtkPolyData() PSE2 = PreliminarySedExtrusion2 PSE2.Update() PreSurface2 = vtk.vtkUnstructuredGrid() PSreader2=vtk.vtkGenericDataObjectReader() PSreader2.SetFileName(PreviousSave) # 000000.vtu PSreader2.Update() PreSurface2 = PSreader2.GetOutput() Append = vtk.vtkAppendPolyData() Append.AddInput(PreSurface2) Append.AddInput(PSE2) DD = Append.GetOutput() DD.Update() ExtrudedSedPoints = PSE2.GetPoints() PSPoints = PreSurface2.GetPoints() SedPoints = PSE2.GetNumberOfPoints() BeginSed = nPoints/2 EndSed = BeginSed - 1 sedcounter3 = 0 sedcounter4 = BeginSed Data = DD.GetPoints() mesh = Mesh m = (mesh+1)**2 c = t while c != 0: c = (c -1) e = int((c*m)*2) ee = int(e + m) for p in range(e,ee): A = Data.GetPoint(p+(2*m))[2:] #New sediment height B = Data.GetPoint(p)[2:] # old sediment height C = Data.GetPoint(p+m)[2:] # old sediment bottom if A < B: #If new sediment height is less than old sediment height y = (Data.GetPoint(p)[:2] + Data.GetPoint(p+(2*m))[2:]) Data.SetPoint(p,y) if A < C: x = Data.GetPoint(p+m)[:2] + Data.GetPoint(p)[2:] Data.SetPoint((p+m),x) f = int((t*m)*2+m) ff = int(f + m) for p in range(f,ff): y = Data.GetPoint((p-3*m))[2:] x = Data.GetPoint(p)[:2] + y Data.SetPoint(p,x) writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(DD) writer.Update() writer.Write()
def execute(working_dir): # convert vtk to stl reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(os.path.join(working_dir, "surface.vtk")) reader.Update() surface = reader.GetOutput() writer = vtk.vtkSTLWriter() writer.SetFileName(os.path.join(working_dir, "surface.stl")) writer.SetInputData(surface) writer.Update() # compute centerline command = binary_path + " " + \ os.path.join(working_dir,"surface.stl") + " " + \ os.path.join(working_dir,"surface_capped.stl") + " " + \ os.path.join(working_dir,"centerline.vtp") # os.system(command) # crop equal distance from the defected zone # load defected zone coordinate defected_point = open(os.path.join(working_dir, "defected_point.fcsv"), "r").readlines()[3] defected_point = defected_point.split(",")[1:4] defected_point = [float(i) for i in defected_point] # load the centerline file reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(os.path.join(working_dir, "centerline.vtp")) reader.Update() centerline = reader.GetOutput() kdTree = vtk.vtkKdTreePointLocator() kdTree.SetDataSet(centerline) iD = kdTree.FindClosestPoint(defected_point) end_id = centerline.GetNumberOfPoints() - 1 defected_point_absc = centerline.GetPointData().GetArray( "Abscissas").GetComponent(iD, 0) # find the start point start_id = 0 start_point_absc = 0 start_point = [0, 0, 0] start_point_tangent = [1, 0, 0] start_point_normal = [0, 1, 0] start_point_binormal = [0, 0, 1] for i in range(centerline.GetNumberOfPoints() - 1): if defected_point_absc - centerline.GetPointData().GetArray( "Abscissas").GetComponent(i, 0) < dist_from_defect: break else: start_id = i start_point_absc = centerline.GetPointData().GetArray( "Abscissas").GetComponent(i, 0) start_point = list(centerline.GetPoints().GetPoint(i)) start_point_tangent = list(centerline.GetPointData().GetArray( "FrenetTangent").GetTuple(i)) start_point_normal = list( centerline.GetPointData().GetArray("FrenetNormal").GetTuple(i)) start_point_binormal = list(centerline.GetPointData().GetArray( "FrenetBinormal").GetTuple(i)) print(start_id, start_point, start_point_tangent, start_point_normal, start_point_binormal) clipBoxes = [] clipPlanes = [] surface, clipBox, clipPlane = clip_polydata_by_box(surface, start_point, start_point_tangent, start_point_normal, start_point_binormal) centerline, _, _ = clip_polydata_by_box(centerline, start_point, start_point_tangent, start_point_normal, start_point_binormal) clipBoxes.append(clipBox) clipPlanes.append(clipPlane) # find end points # split the polydata by centerline id splitter = vtk.vtkThreshold() splitter.SetInputData(centerline) splitted_centerlines = [] for i in range( int(centerline.GetCellData().GetArray("CenterlineIds").GetRange() [1]) + 1): splitter.ThresholdBetween(i, i) splitter.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "CenterlineIds") splitter.Update() splitted_centerline = vtk.vtkPolyData() splitted_centerline.DeepCopy(splitter.GetOutput()) splitted_centerlines.append(splitted_centerline) end_ids = [] end_points = [] end_points_tangent = [] end_points_normal = [] end_points_binormal = [] for splitted_centerline in splitted_centerlines: end_id = splitted_centerline.GetNumberOfPoints() - 1 end_point_absc = splitted_centerline.GetPointData().GetArray( "Abscissas").GetComponent( splitted_centerline.GetNumberOfPoints() - 1, 0) end_point = list(splitted_centerline.GetPoints().GetPoint( splitted_centerline.GetNumberOfPoints() - 1)) end_point_tangent = list(splitted_centerline.GetPointData().GetArray( "FrenetTangent").GetTuple(splitted_centerline.GetNumberOfPoints() - 1)) end_point_normal = list(splitted_centerline.GetPointData().GetArray( "FrenetNormal").GetTuple(splitted_centerline.GetNumberOfPoints() - 1)) end_point_binormal = list( splitted_centerline.GetPointData().GetArray("FrenetBinormal"). GetTuple(splitted_centerline.GetNumberOfPoints() - 1)) for i in range(splitted_centerline.GetNumberOfPoints()): if splitted_centerline.GetPointData().GetArray( "Abscissas").GetComponent( i, 0) - start_point_absc > 2 * dist_from_defect: end_ids.append(end_id) end_points.append(end_point) end_points_tangent.append(end_point_tangent) end_points_normal.append(end_point_normal) end_points_binormal.append(end_point_binormal) break else: end_id = i end_point_absc = splitted_centerline.GetPointData().GetArray( "Abscissas").GetComponent(i, 0) end_point = list(splitted_centerline.GetPoints().GetPoint(i)) end_point_tangent = list( splitted_centerline.GetPointData().GetArray( "FrenetTangent").GetTuple(i)) end_point_normal = list( splitted_centerline.GetPointData().GetArray( "FrenetNormal").GetTuple(i)) end_point_binormal = list( splitted_centerline.GetPointData().GetArray( "FrenetBinormal").GetTuple(i)) if i == splitted_centerline.GetNumberOfPoints() - 1: end_ids.append(end_id) end_points.append(end_point) end_points_tangent.append(end_point_tangent) end_points_normal.append(end_point_normal) end_points_binormal.append(end_point_binormal) for i in range(len(end_ids)): print(end_ids[i], end_points[i], end_points_tangent[i], end_points_normal[i], end_points_binormal[i]) surface, clipBox, clipPlane = clip_polydata_by_box( surface, end_points[i], end_points_tangent[i], end_points_normal[i], end_points_binormal[i]) centerline, _, _ = clip_polydata_by_box(centerline, end_points[i], end_points_tangent[i], end_points_normal[i], end_points_binormal[i]) clipBoxes.append(clipBox) clipPlanes.append(clipPlane) # connected component calculation on surface and centerline connectedFilter = vtk.vtkConnectivityFilter() # connectedFilter.SetExtractionModeToAllRegions() # connectedFilter.ColorRegionsOn() connectedFilter.SetExtractionModeToClosestPointRegion() connectedFilter.SetClosestPoint(defected_point) connectedFilter.SetInputData(surface) connectedFilter.Update() surface.DeepCopy(connectedFilter.GetOutput()) # output vtpWriter = vtk.vtkXMLPolyDataWriter() vtpWriter.SetFileName(os.path.join(working_dir, "surface_clipped.vtp")) vtpWriter.SetInputData(surface) vtpWriter.Update() connectedFilter.SetInputData(centerline) connectedFilter.Update() centerline.DeepCopy(connectedFilter.GetOutput()) vtpWriter.SetFileName(os.path.join(working_dir, "centerline_clipped.vtp")) vtpWriter.SetInputData(centerline) vtpWriter.Update() for i in range(len(clipBoxes)): writer.SetFileName( os.path.join(working_dir, "clip_box_" + str(i) + ".stl")) writer.SetInputData(clipBoxes[i]) writer.Update() writer.SetFileName( os.path.join(working_dir, "clip_plane_" + str(i) + ".stl")) writer.SetInputData(clipPlanes[i]) writer.Update()