def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) # we'll be playing around with some vtk objects, this could # be anything self._thresh = vtk.vtkThresholdPoints() # this is wacked syntax! self._thresh.ThresholdByUpper(1) self._reconstructionFilter = vtk.vtkSurfaceReconstructionFilter() self._reconstructionFilter.SetInput(self._thresh.GetOutput()) self._mc = vtk.vtkMarchingCubes() self._mc.SetInput(self._reconstructionFilter.GetOutput()) self._mc.SetValue(0, 0.0) module_utils.setup_vtk_object_progress(self, self._thresh, 'Extracting points...') module_utils.setup_vtk_object_progress(self, self._reconstructionFilter, 'Reconstructing...') module_utils.setup_vtk_object_progress(self, self._mc, 'Extracting surface...') self._iObj = self._thresh self._oObj = self._mc self._viewFrame = self._createViewFrame({'threshold' : self._thresh, 'reconstructionFilter' : self._reconstructionFilter, 'marchingCubes' : self._mc})
def TestMarching(atlas): reader = vtk.vtkNIFTIImageReader() reader.SetFileName(atlas) reader.Update() image = reader.GetOutput() # threshold threshold = vtk.vtkImageThreshold() threshold.SetInputData(image) threshold.ThresholdBetween(60,60) threshold.ReplaceOutOn() threshold.SetOutValue(0) threshold.Update() image1 = threshold.GetOutput() marching = vtk.vtkMarchingCubes() marching.SetInputData(image1) marching.SetValue(0,60) marching.Update() area = marching.GetOutput() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("test") colors.InsertNextTupleValue([0,1,1]) area.GetCellData().SetScalars(colors) # visualization print "visualizing..." mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(area) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() window.SetInteractor(interactor) window.Render() interactor.Start()
def create_frog_actor(file_name, tissue, use_flying_edges): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) iso_value = 63.5 if use_flying_edges: try: iso_surface = vtk.vtkFlyingEdges3D() except AttributeError: iso_surface = vtk.vtkMarchingCubes() else: iso_surface = vtk.vtkMarchingCubes() iso_surface.SetInputConnection(select_tissue.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOn() iso_surface.SetValue(0, iso_value) stripper = vtk.vtkStripper() stripper.SetInputConnection(iso_surface.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def run(self, inputObstacle1, inputObstacle2): # Creating Mesh of Obstacle 1 and Obstacle 2 Mesh1 = vtk.vtkMarchingCubes(); Mesh2 = vtk.vtkMarchingCubes() Mesh1.SetInputData(inputObstacle1.GetImageData()); Mesh2.SetInputData(inputObstacle2.GetImageData()) Mesh1.SetValue(0, 1); Mesh1.Update(); Mesh2.SetValue(0, 1); Mesh2.Update() # Create OBB Tree of Obstacle 1 and Obstacle 2 OBB_obstacle1_tree = vtk.vtkOBBTree(); OBB_obstacle2_tree = vtk.vtkOBBTree() OBB_obstacle1_tree.SetDataSet(mesh.GetOutput()); OBB_obstacle2_tree.SetDataSet(mesh.GetOutput()) OBB_obstacle1_tree.BuildLocator(); OBB_obstacle2_tree.BuildLocator() return OBB_obstacle1_tree, OBB_obstacle2_tree
def __init__(self, renderer, interactor): self.connect = ConnectFilter() self.deci = DecimateFilter() self.marchingCubes = vtk.vtkMarchingCubes() self.prog = ProgressBarDialog( title='Rendering surface %s' % self.label, parent=None, msg='Marching cubes ....', size=(300,40), ) def start(o, event): self.prog.show() while gtk.events_pending(): gtk.main_iteration() def progress(o, event): val = o.GetProgress() self.prog.bar.set_fraction(val) while gtk.events_pending(): gtk.main_iteration() def end(o, event): self.prog.hide() while gtk.events_pending(): gtk.main_iteration() self.marchingCubes.AddObserver('StartEvent', start) self.marchingCubes.AddObserver('ProgressEvent', progress) self.marchingCubes.AddObserver('EndEvent', end) self.renderer = renderer self.interactor = interactor self.isoActor = None self.update_pipeline()
def process_data(input_file, color): reader = vtk.vtkNIFTIImageReader() reader.SetFileName(input_file) extractor = vtk.vtkMarchingCubes() extractor.SetInputConnection(reader.GetOutputPort()) extractor.SetValue(0, 1) smooth_filter = vtk.vtkSmoothPolyDataFilter() smooth_filter.SetInputConnection(extractor.GetOutputPort()) smooth_filter.SetNumberOfIterations(5) smooth_filter.SetRelaxationFactor(0.5) smooth_filter.FeatureEdgeSmoothingOff() smooth_filter.BoundarySmoothingOn() smooth_filter.Update() cleaned = vtk.vtkCleanPolyData() cleaned.SetInputData(smooth_filter.GetOutput()) normal_generator = vtk.vtkPolyDataNormals() normal_generator.ComputePointNormalsOn() normal_generator.ComputeCellNormalsOn() normal_generator.SetInputConnection(cleaned.GetOutputPort()) normal_generator.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(normal_generator.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(color) return normal_generator, actor
def __init__(self, brain_data, isoval=34): # Setup Surface Rendering # Gaussian smoothing of surface rendering for aesthetics # Adds significant delay to rendering self.cortexSmoother = vtk.vtkImageGaussianSmooth() self.cortexSmoother.SetDimensionality(3) self.cortexSmoother.SetRadiusFactors(0.5, 0.5, 0.5) self.cortexSmoother.SetInput(brain_data.GetOutput()) # Apply a marching cubes algorithm to extract surface contour with # isovalue of 30 (can change to adjust proper rendering of tissue self.cortexExtractor = vtk.vtkMarchingCubes() self.cortexExtractor.SetInput(self.cortexSmoother.GetOutput()) self.cortexExtractor.SetValue(0, isoval) self.cortexExtractor.ComputeNormalsOn() # Map/Paint the polydata associated with the surface rendering self.cortexMapper = vtk.vtkPolyDataMapper() self.cortexMapper.SetInput(self.cortexExtractor.GetOutput()) self.cortexMapper.ScalarVisibilityOff() # Color the cortex (RGB) self.cortexProperty = vtk.vtkProperty() self.cortexProperty.SetColor(1, 1, 1) self.cortexProperty.SetOpacity(1); # Set the actor to adhere to mapped surface and inherit properties self.SetMapper(self.cortexMapper) self.SetProperty(self.cortexProperty) self.cortexExtractor.Update()
def marching_cubes(grid_fname_vtk, mesh_filename_ply, value=0.5): """ read in a grid in vtk format, run marching cubes, save the result as ply mesh Parameters ---------- grid_fname_vtk : str The file name of the grid in vtk format mesh_filename_ply : str The file name to save the ply mesh results value : float, optional The value """ reader = vtk.vtkStructuredPointsReader() reader.SetFileName(grid_fname_vtk) reader.Update() points = reader.GetOutput() mcubes = vtk.vtkMarchingCubes() mcubes.SetInput(points) mcubes.SetValue(0, value) mcubes.Update() mesh = mcubes.GetOutput() writer = vtk.vtkPLYWriter() writer.SetInput(mesh) writer.SetFileName(mesh_filename_ply) writer.Update() writer.Write()
def run(self, inputImage): mc = vtk.vtkMarchingCubes() mc.SetInputData(inputImage.GetImageData()) mc.ComputeGradientsOn() mc.SetValue(0, 1) mc.Update() return mc.GetOutput()
def applyMarchingCubes(self, imgData): mc = vtk.vtkMarchingCubes() mc.SetInputData(imgData.GetOutput()) mc.Update() return mc # vtkobject
def initialize(self): #self._vtk_widget.Initialize() super(SurfaceViewer, self).initialize() self._surface_algorithm = vtk.vtkMarchingCubes() if vtk_tools.VTK_VERSION >= 6: self._surface_algorithm.SetInputData(self._image_data) else: self._surface_algorithm.SetInput(self._image_data) self._surface_algorithm.ComputeNormalsOn() self._surface_algorithm.SetValue(0, self._surface_level) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self._surface_algorithm.GetOutputPort()) mapper.ScalarVisibilityOff() self._actor = vtk.vtkActor() self._actor.GetProperty().SetColor(0., 1., 0.) self._actor.SetMapper(mapper) self._renderer.AddViewProp(self._actor) self._renderer.Render() self._vtk_widget.Render() self._level_slider = QtGui.QSlider(QtCore.Qt.Horizontal) self._level_slider.setMaximum(self._SLIDER_MAXIMUM) self._level_slider.valueChanged.connect(self._slider_changed) self._level_slider.setValue(self._INITIAL_SLIDER_POSITION) self._layout.addWidget(self._level_slider) self._vtk_widget.Render()
def open_actor(actor, actor_index=0, scale=SCALE, radius=RADIUS): poly = actor.GetMapper().GetInput() pre_image = voxelizer(poly, scale) opened_image = open_image(pre_image, radius) gauss = vtk.vtkImageGaussianSmooth() gauss.SetDimensionality(3) gauss.SetStandardDeviation(radius, radius, radius) gauss.SetInputData(opened_image) gauss.Update() image_to_contour = gauss.GetOutput() contour = vtk.vtkMarchingCubes() contour.SetInputData(image_to_contour) contour.SetValue(0, 127.5) contour.ComputeScalarsOff() contour.Update() repared_poly = contour.GetOutput() if repared_poly.GetNumberOfCells() == 0: print("ERROR: number_of_cells = 0", end=' ') # write_image(image_to_contour, "/tmp/%d.mhd"%actor_index) raise ValueError("ERROR: number_of_cells = 0") # (minX, maxX, minY, maxY, minZ, maxZ) = [int(x) for x in repared_poly.GetBounds()] #convert tuple of floats to ints # print " Repared bounds are %s"%str((minX, maxX, minY, maxY, minZ, maxZ)) #dimensions of the resulting image # print " Dimensions: %s"%str((maxX - minX, maxY - minY, maxZ - minZ)) actor.GetMapper().SetInputData(repared_poly)
def surface_renderer(img): # get iso surface as polydata marcher = vtk.vtkMarchingCubes() marcher.SetInputData(img) marcher.SetValue(0, 255) marcher.ComputeNormalsOn() marcher.Update() # mapper-actor-render-renderwindow sequence mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(marcher.GetOutput()) mapper.ScalarVisibilityOff() actor = vtk.vtkLODActor() actor.SetMapper(mapper) actor.SetNumberOfCloudPoints(1000000) actor.GetProperty().SetColor(1.6, 0.0, 2) actor.GetProperty().SetOpacity(0.5) render = vtk.vtkRenderer() render.AddActor(actor) render.SetBackground(0.0, 0.0, 0.0) window = vtk.vtkRenderWindow() window.AddRenderer(render) window.PolygonSmoothingOn() window.SetSize(500, 500) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(window) iren.Initialize() window.Render() iren.Start()
def __init__(self, layer_dist=1.115, number_of_cells_per_side_=1, surface_density=0.1, unit_cell_size_=300): molar.pdb.Pdb.__init__(self) self.layer_dist = layer_dist self.step_num = int(32) self.marching_cubes = vtk.vtkMarchingCubes() self.poly_data = vtk.vtkPolyData() self.data = vtk.vtkDataObject() self.unit_cell_size = unit_cell_size_ self.form = "G" self.number_of_cells_per_side = number_of_cells_per_side_ self.cerebroside = False self.Update() self.units = [] self.units_transed = [] self.points = vtk.vtkPoints() #for visualization self.surf_dens = surface_density self.total_area = 0 self.total_pair = 0 for f in FILES: self.units.append(molar.pdb.Pdb()) self.units[-1].ReadFile(PATH + f) for f in FILES: self.units_transed.append(molar.pdb.Pdb()) self.units_transed[-1].ReadFile(PATH + f) self.units_transed[-1].RotateX(180) self.units[-1].BringToNegativeY()
def vtkCreateIsoContour(self , config = 'MARCHINGCUBES'): """ Fonction pour la creation de l'isocontour pour une valeur de seuillage""" #----------------------------------------- # Creation de l isocontour #----------------------------------------- if config == 'CONTOUR' : self.aneurysmExtractor = vtk.vtkContourFilter() if config == 'MARCHINGCUBES' : self.aneurysmExtractor = vtk.vtkMarchingCubes() self.aneurysmExtractor.SetInputConnection(self.vtkVolumBlur.GetOutputPort()) self.aneurysmExtractor.SetValue(0, self.valSeuil) self.aneurysmExtractor.ComputeNormalsOn() self.aneurysmTriangleFilter = vtk.vtkTriangleFilter() self.aneurysmTriangleFilter.SetInputConnection(self.aneurysmExtractor.GetOutputPort()) self.aneurysmCleanFilter = vtk.vtkCleanPolyData() self.aneurysmCleanFilter.SetInputConnection(self.aneurysmTriangleFilter.GetOutputPort()) self.aneurysmConnectFilter = vtk.vtkPolyDataConnectivityFilter() self.aneurysmConnectFilter.SetExtractionModeToLargestRegion() self.aneurysmConnectFilter.ScalarConnectivityOff() self.aneurysmConnectFilter.SetInputConnection(self.aneurysmCleanFilter.GetOutputPort()) self.aneurysmNormals = vtk.vtkPolyDataNormals() self.aneurysmNormals.SetInputConnection(self.aneurysmConnectFilter.GetOutputPort()) self.aneurysmNormals.SetFeatureAngle(60.0) self.aneurysmNormals.ComputeCellNormalsOn() self.aneurysmNormals.ComputePointNormalsOn() self.aneurysmNormals.ConsistencyOn() self.aneurysmNormals.AutoOrientNormalsOn() self.aneurysmNormals.Update()
def initialize(self): super(SurfaceViewer, self).initialize() self._surface_algorithm = vtk.vtkMarchingCubes() if vtk_tools.VTK_VERSION >= 6: self._surface_algorithm.SetInputData(self._image_data) else: self._surface_algorithm.SetInput(self._image_data) self._surface_algorithm.ComputeNormalsOn() self._surface_algorithm.SetValue(0, self._surface_level) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self._surface_algorithm.GetOutputPort()) mapper.ScalarVisibilityOff() self._actor = vtk.vtkActor() self._actor.GetProperty().SetColor(0., 1., 0.) self._actor.SetMapper(mapper) self._renderer.AddViewProp(self._actor) self._renderer.Render() self._vtk_widget.Render() self._level_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self._level_slider.setMaximum(self._SLIDER_MAXIMUM) self._level_slider.valueChanged.connect(self._slider_changed) self._level_slider.setValue(self._INITIAL_SLIDER_POSITION) self._layout.addWidget(self._level_slider) self._vtk_widget.Render()
def vtk_marching_cube(modeller, compute_normals=False, compute_scalars=False, compute_gradients=False): """Wrapper for vtkMarchingCube Args: modeller (vtkPolyballModeller): Modeller of a surface model compute_normals (bool): Set/Get the computation of normals. compute_scalars (bool): Set/Get the computation of scalars. compute_gradients (bool): Set/Get the computation of gradients. Returns: vtkMarchingCube: Isosurface generated from surface """ marching_cube = vtk.vtkMarchingCubes() if compute_normals: marching_cube.ComputeNormalsOn() if compute_scalars: marching_cube.ComputeScalarsOn() if compute_gradients: marching_cube.ComputeGradientsOn() marching_cube.SetInputData(modeller.GetOutput()) marching_cube.SetValue(0, 0.0) marching_cube.Update() return marching_cube
def load_nii_save_stl(self, in_name='data/skull.nii', out_name='data/skull.stl', threshold=100.0): print "Function: load_nii_save_stl" print "Para1: input file name (.nii file)\nPara2: output file name (.stl file)" reader = vtk.vtkNIFTIImageReader() reader.SetFileName(in_name) reader.Update() image = reader.GetOutput() surface = vtk.vtkMarchingCubes() surface.SetInputData(image) surface.SetValue(0, threshold) surface.Update() # extract largest connectivity area confilter = vtk.vtkPolyDataConnectivityFilter() confilter.SetInputData(surface.GetOutput()) confilter.SetExtractionModeToLargestRegion() confilter.Update() skull = confilter.GetOutput() writer = vtk.vtkSTLWriter() writer.SetFileName(out_name) writer.SetInputData(skull) writer.Update() print out_name, ' saved!'
def __init__(self, module_manager, contourFilterText): # call parent constructor ModuleBase.__init__(self, module_manager) self._contourFilterText = contourFilterText if contourFilterText == 'marchingCubes': self._contourFilter = vtk.vtkMarchingCubes() else: # contourFilter == 'contourFilter' self._contourFilter = vtk.vtkContourFilter() module_utils.setup_vtk_object_progress(self, self._contourFilter, 'Extracting iso-surface') # now setup some defaults before our sync self._config.isoValue = 128; self._viewFrame = None self._createViewFrame() # transfer these defaults to the logic self.config_to_logic() # then make sure they come all the way back up via self._config self.logic_to_config() self.config_to_view()
def surfextract(filt): vmc = vtk.vtkMarchingCubes() vmc.SetInputConnection(filt.GetOutputPort()) vmc.GenerateValues(1, 1, 1) vmc.Update() return vmc
def getIsoActor(fname, colour, opacity, value): isoreader = vtk.vtkStructuredPointsReader() isoreader.SetFileName(fname) isoreader.Update() extractiso = vtk.vtkExtractVOI() if (options.xmax > -1 or options.ymax > -1 or options.zmax > -1): extractiso.SetVOI(options.zmin,options.zmax, options.ymin,options.ymax, options.xmin,options.xmax) extractiso.SetInput(isoreader.GetOutput()) iso = vtk.vtkMarchingCubes() iso.SetInput(extractiso.GetOutput()) iso.SetValue(0,value) polymap = vtk.vtkPolyDataMapper() polymap.SetInput(iso.GetOutput()) polymap.ScalarVisibilityOff() isoactor = vtk.vtkActor() isoactor.SetMapper(polymap) isoactor.GetProperty().SetColor(colour) isoactor.GetProperty().SetOpacity(opacity) return (isoreader, isoactor)
def Execute(self): if self.Image == None: self.PrintError('Error: No Image.') extent = self.Image.GetExtent() translateExtent = vtk.vtkImageTranslateExtent() translateExtent.SetInputData(self.Image) translateExtent.SetTranslation(-extent[0],-extent[2],-extent[4]) translateExtent.Update() if (self.ArrayName != ''): translateExtent.GetOutput().GetPointData().SetActiveScalars(self.ArrayName) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInputConnection(translateExtent.GetOutputPort()) marchingCubes.SetValue(0,self.Level) marchingCubes.Update() self.Surface = marchingCubes.GetOutput() if self.Connectivity == 1: connectivityFilter = vtk.vtkPolyDataConnectivityFilter() connectivityFilter.SetInputData(self.Surface) connectivityFilter.SetExtractionModeToLargestRegion() connectivityFilter.Update() self.Surface = connectivityFilter.GetOutput()
def CreateFrogActor(fileName, tissue): reader = vtk.vtkMetaImageReader() reader.SetFileName(fileName) reader.Update() selectTissue = vtk.vtkImageThreshold() selectTissue.ThresholdBetween(tissue, tissue) selectTissue.SetInValue(255) selectTissue.SetOutValue(0) selectTissue.SetInputConnection(reader.GetOutputPort()) isoValue = 63.5 mcubes = vtk.vtkMarchingCubes() mcubes.SetInputConnection(selectTissue.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOn() mcubes.SetValue(0, isoValue) stripper = vtk.vtkStripper() stripper.SetInputConnection(mcubes.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def tomo_poly_iso_cube(tomo, dec=None): # Creating the cube cube = np.zeros(shape=tomo.shape, dtype=np.float32) cube[1:tomo.shape[0] - 1, 1:tomo.shape[1] - 1, 1:tomo.shape[2] - 1] = 1. # Marching cubes configuration march = vtk.vtkMarchingCubes() cube_vtk = ps.disperse_io.numpy_to_vti(cube) march.SetInputData(cube_vtk) march.SetValue(0, .5) # Running Marching Cubes march.Update() hold_poly = march.GetOutput() # Decimation filter if dec is not None: tr_dec = vtk.vtkDecimatePro() tr_dec.SetInputData(hold_poly) tr_dec.SetTargetReduction(dec) tr_dec.Update() hold_poly = tr_dec.GetOutput() return hold_poly
def __init__(self, module_manager, contourFilterText): # call parent constructor ModuleBase.__init__(self, module_manager) self._contourFilterText = contourFilterText if contourFilterText == 'marchingCubes': self._contourFilter = vtk.vtkMarchingCubes() else: # contourFilter == 'contourFilter' self._contourFilter = vtk.vtkContourFilter() module_utils.setup_vtk_object_progress(self, self._contourFilter, 'Extracting iso-surface') # now setup some defaults before our sync self._config.isoValue = 128 self._viewFrame = None self._createViewFrame() # transfer these defaults to the logic self.config_to_logic() # then make sure they come all the way back up via self._config self.logic_to_config() self.config_to_view()
def Convert(image: Image_Data, threshold1, threshold2, smooth_iterations=0): ''' Input: 需转换的图像,两个阈值,平滑迭代次数 Output: 转换得到的曲面数据 Description: 使用Marching cube方法将标签图转换为曲面,并平滑。两个阈值间的灰度范围为前景,其余部分为背景 ''' label = Threshold_Seg.Threshold(image, threshold1, threshold2) Extractor = vtk.vtkMarchingCubes() Extractor.SetInputData(label.Get_vtkImageData()) Extractor.SetValue(0, 1) Smoother = vtk.vtkSmoothPolyDataFilter() Smoother.SetInputConnection(Extractor.GetOutputPort()) Smoother.SetNumberOfIterations(smooth_iterations) Smoother.SetRelaxationFactor(0.1) Smoother.FeatureEdgeSmoothingOff() Smoother.BoundarySmoothingOn() Smoother.Update() Normals = vtk.vtkPolyDataNormals() Normals.SetInputConnection(Smoother.GetOutputPort()) Normals.SetFeatureAngle(60.0) Stripper = vtk.vtkStripper() Stripper.SetInputConnection(Normals.GetOutputPort()) Stripper.Update() polydata = Poly_Data() polydata.Init_From_Vtk(Stripper.GetOutput()) return polydata
def tomo_poly_iso(tomo, th, flp, dec=None): # Marching cubes configuration march = vtk.vtkMarchingCubes() # tomo_vtk = numpy_support.numpy_to_vtk(num_array=tomo.ravel(), deep=True, array_type=vtk.VTK_FLOAT) tomo_vtk = ps.disperse_io.numpy_to_vti(tomo) # Flipping if flp: fliper = vtk.vtkImageFlip() fliper.SetFilteredAxis(2) fliper.SetInputData(tomo_vtk) fliper.Update() tomo_vtk = fliper.GetOutput() march.SetInputData(tomo_vtk) march.SetValue(0, th) # Running Marching Cubes march.Update() hold_poly = march.GetOutput() # Decimation filter if dec is not None: tr_dec = vtk.vtkDecimatePro() tr_dec.SetInputData(hold_poly) tr_dec.SetTargetReduction(dec) tr_dec.Update() hold_poly = tr_dec.GetOutput() return hold_poly
def isosurface(data, levels, cmap=None, vmin=None, vmax=None, color='g', opacity=1.0, renderer=None): vdata = RegData_to_vtkImageData(data) dmc = vtk.vtkMarchingCubes() vtkConnectDataInput(vdata, dmc) for i,l in enumerate(levels): dmc.SetValue(i, l) # dmc.Update() mapper = vtk.vtkPolyDataMapper() vtkConnectOutputInput(dmc, mapper) actor = vtk.vtkActor() if cmap is None: mapper.ScalarVisibilityOff() color = colors.to_rgb(color) actor.GetProperty().SetColor(*color) rval = actor else: vmin,vmax = data_range(data, vmin=vmin, vmax=vmax) ctf = get_vtkColorTransferFunction(cmap, vmin=vmin, vmax=vmax) mapper.ScalarVisibilityOn() mapper.SetLookupTable(ctf) rval = (actor, ctf) # actor.GetProperty().SetOpacity(opacity) actor.SetMapper(mapper) if renderer is not None: renderer.AddActor(actor) # return rval
def simple(reader, r): d = vtk.vtkMarchingCubes() d.SetInputConnection(reader.GetOutputPort()) d.SetValue(r[0], r[1]) #0,50 d.ComputeNormalsOn() d.Update() return d
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkMarchingCubes(), 'Processing.', ('vtkImageData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, volume, level=None, spacing=(1., 1., 1.)): self._surface_algorithm = None self._renderer = None self._actor = None self._mapper = None self._volume_array = None self._float_array = _vtk.vtkFloatArray() self._image_data = _vtk.vtkImageData() self._image_data.GetPointData().SetScalars(self._float_array) self._setup_data(_numpy.float32(volume)) self._image_data.SetSpacing(spacing[2], spacing[1], spacing[0]) self._surface_algorithm = _vtk.vtkMarchingCubes() if VTK_VERSION >= 6: self._surface_algorithm.SetInputData(self._image_data) else: self._surface_algorithm.SetInput(self._image_data) self._surface_algorithm.ComputeNormalsOn() if level is not None: try: self.set_multiple_levels(iter(level)) except TypeError: self.set_level(0, level) self._mapper = _vtk.vtkPolyDataMapper() self._mapper.SetInputConnection( self._surface_algorithm.GetOutputPort()) self._mapper.ScalarVisibilityOn() self._actor = _vtk.vtkActor() self._actor.SetMapper(self._mapper)
def __init__(self, brain_data, isoval=34): # Setup Surface Rendering # Gaussian smoothing of surface rendering for aesthetics # Adds significant delay to rendering self.cortexSmoother = vtk.vtkImageGaussianSmooth() self.cortexSmoother.SetDimensionality(3) self.cortexSmoother.SetRadiusFactors(0.5, 0.5, 0.5) self.cortexSmoother.SetInput(brain_data.GetOutput()) # Apply a marching cubes algorithm to extract surface contour with # isovalue of 30 (can change to adjust proper rendering of tissue self.cortexExtractor = vtk.vtkMarchingCubes() self.cortexExtractor.SetInput(self.cortexSmoother.GetOutput()) self.cortexExtractor.SetValue(0, isoval) self.cortexExtractor.ComputeNormalsOn() # Map/Paint the polydata associated with the surface rendering self.cortexMapper = vtk.vtkPolyDataMapper() self.cortexMapper.SetInput(self.cortexExtractor.GetOutput()) self.cortexMapper.ScalarVisibilityOff() # Color the cortex (RGB) self.cortexProperty = vtk.vtkProperty() self.cortexProperty.SetColor(1, 1, 1) self.cortexProperty.SetOpacity(1) # Set the actor to adhere to mapped surface and inherit properties self.SetMapper(self.cortexMapper) self.SetProperty(self.cortexProperty) self.cortexExtractor.Update()
def SurfMarchingCubes(self): """ To make two surfaces on the headgoups. """ step = self.number_of_cells_per_side * 2 * np.pi / float(self.step_num) self.s_marching_cubes = vtk.vtkMarchingCubes() self.s_marching_cubes.ComputeScalarsOff() vol = vtk.vtkImageData() vol.SetDimensions(self.step_num, self.step_num, self.step_num) vol.AllocateScalars(vtk.VTK_DOUBLE, int(1)) for i in range(self.step_num): for j in range(self.step_num): for k in range(self.step_num): f = self.Func(i * step, j * step, k * step) vol.SetScalarComponentFromDouble(i, j, k, 0, f) self.s_marching_cubes.SetInputData(vol) self.s_marching_cubes.SetValue(0, WATER_MARGIN_SURF_VALUE) self.s_marching_cubes.SetValue(1, -1 * WATER_MARGIN_SURF_VALUE) self.s_marching_cubes.Update() self.s_marching_cubes.UpdateInformation() self.surf_actor = vtk.vtkActor() scaleTrans = vtk.vtkTransform() scaleTrans.Scale(self.sampling_size, self.sampling_size, self.sampling_size) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.s_marching_cubes.GetOutputPort()) self.surf_actor.SetMapper(mapper) self.surf_actor.GetProperty().SetColor(0.0, 0.95, 0.0) self.surf_actor.SetUserTransform(scaleTrans) pass
def createMeshfromVTKMask(self, imMask): """ Takes a binary mask image and makes it a vtkPolyData VOI_mesh """ # Create a binary Image with 0-255 image_VOIlesion = vtk.vtkImageThreshold() image_VOIlesion.ThresholdByUpper(0.1) image_VOIlesion.SetInValue(255) image_VOIlesion.SetOutValue(0) image_VOIlesion.SetInput(imMask) image_VOIlesion.Update() # Convert VOIlesion into polygonal struct VOIlesion_poly = vtk.vtkMarchingCubes() VOIlesion_poly.SetValue(0, 125) VOIlesion_poly.SetInput(image_VOIlesion.GetOutput()) VOIlesion_poly.ComputeNormalsOff() VOIlesion_poly.Update() # Recalculate num_voxels and vol_lesion on VOI nvoxels = VOIlesion_poly.GetOutput().GetNumberOfCells() npoints = VOIlesion_poly.GetOutput().GetNumberOfPoints() print "Number of points: %d" % npoints print "Number of cells: %d" % nvoxels # prepare output meshlesion3D = VOIlesion_poly.GetOutput() return meshlesion3D
def __init__(self, number_of_cells_per_side_=1, unit_cell_size_=200): molar.pdb.Pdb.__init__(self) self.surface_density = SURFACE_DENSITY self.step_num = int(32) self.marching_cubes = vtk.vtkMarchingCubes() self.poly_data = vtk.vtkPolyData() self.data = vtk.vtkDataObject() self.unit_cell_size = unit_cell_size_ self.form = "G" self.number_of_cells_per_side = number_of_cells_per_side_ self.cerebroside = False self.Update() self.units = [] self.units_transed = [] self.points = vtk.vtkPoints() #for visualization self.attempt = 0 self.collisioncounter = 0 self.total_area = 0 self.total_pair = 0 for f in FILES: self.units.append(molar.pdb.Pdb()) self.units[-1].ReadFile(PATH + f) for f in FILES: self.units_transed.append(molar.pdb.Pdb()) self.units_transed[-1].ReadFile(PATH + f) self.units_transed[-1].RotateX(180) self.pointlocator = vtk.vtkPointLocator() self.pointlocator.Initialize() self.pointlocator.SetDataSet(vtk.vtkPolyData()) self.pointlocator.InitPointInsertion( vtk.vtkPoints(), [0, unit_cell_size_, 0, unit_cell_size_, 0, unit_cell_size_])
def main(argv): if len(argv) < 2: print "usage:",argv[0]," data.vtk" exit(1) data_fn = argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() skin = vtk.vtkMarchingCubes() skin.ComputeNormalsOn() skin.ComputeGradientsOn() skin.SetValue(0, rgb[0][0]) skin.SetInput(data) skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin_actor = vtk.vtkActor() skin_property = vtk.vtkProperty() skin_property.SetColor(rgb[0][1], rgb[0][2], rgb[0][3]) skin_property.SetOpacity(opacity[0][1]) skin_actor.SetProperty(skin_property) skin_actor.SetMapper(skin_mapper) bone = vtk.vtkMarchingCubes() bone.ComputeNormalsOn() bone.ComputeGradientsOn() bone.SetValue(0, rgb[1][0]) bone.SetInput(data) bone_mapper = vtk.vtkPolyDataMapper() bone_mapper.SetInputConnection(bone.GetOutputPort()) bone_mapper.ScalarVisibilityOff() bone_actor = vtk.vtkActor() bone_actor.GetProperty().SetColor(rgb[1][1], rgb[1][2], rgb[1][3]) bone_actor.GetProperty().SetOpacity(opacity[1][1]) bone_actor.SetMapper(bone_mapper) renderer = vtk.vtkRenderer() renderWin = vtk.vtkRenderWindow() renderWin.AddRenderer(renderer) renderInteractor = vtk.vtkRenderWindowInteractor() renderInteractor.SetRenderWindow(renderWin) renderer.AddActor(skin_actor) #renderer.AddActor(bone_actor) renderer.SetBackground(0,0,0) renderWin.SetSize(400, 400) renderInteractor.Initialize() renderWin.Render() renderInteractor.Start()
def createIsoSurface(self,configuration): marchingCube = vtk.vtkMarchingCubes() marchingCube.SetInputConnection(self.reader.GetOutputPort()) marchingCube.SetValue(0,configuration.getIsoValue()) marchingCube.ComputeNormalsOn() self.outputPortForMapper = marchingCube.GetOutputPort() self.createMapper() self.createActor() self.modifyActorIso(configuration) self.finalizePipeline()
def adjust_contour(self, volume, contourValue, mapper): """Adjust or create an isocontour using the Marching Cubes surface at the given value using the given mapper """ self._view_frame.SetStatusText("Calculating new volumerender...") contour = vtk.vtkMarchingCubes() contour.SetValue(0,contourValue) contour.SetInput(volume) mapper.SetInput(contour.GetOutput()) mapper.Update() self.render() self._view_frame.SetStatusText("Calculated new volumerender")
def __init__(self, inputs = (1,1)): """ Initialization """ self.defaultLower = 0 self.defaultUpper = 255 lib.ProcessingFilter.ProcessingFilter.__init__(self,(1,1)) self.contour = vtk.vtkMarchingCubes() self.decimate = vtk.vtkDecimatePro() self.descs = {"Simplify": "Simplify surface", "IsoValue":"Iso-surface value", "PreserveTopology":"PreserveTopology"} self.filterDesc = "Creates iso-surface as polygons\nInput: Binary image (Grayscale image)\nOutput: Surface mesh";
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() sphereSource = vtk.vtkSphereSource() sphereSource.SetPhiResolution(20) sphereSource.SetThetaResolution(20) sphereSource.Update() bounds = [1, 1, 1, 1, 1, 1] sphereSource.GetOutput().GetBounds(bounds) for i in range(0, 6, 2): range_ = bounds[i+1] - bounds[i] bounds[i] = bounds[i] - 0.1 * range_ bounds[i+1] = bounds[i+1] + 0.1 * range_ voxelModeller = vtk.vtkVoxelModeller() voxelModeller.SetSampleDimensions(50, 50, 50) voxelModeller.SetModelBounds(bounds) voxelModeller.SetScalarTypeToFloat() voxelModeller.SetMaximumDistance(0.1) voxelModeller.SetInputConnection(sphereSource.GetOutputPort()) voxelModeller.Update() volume = vtk.vtkImageData() volume.DeepCopy(voxelModeller.GetOutput()) surface = vtk.vtkMarchingCubes() surface.SetInput(volume) surface.SetValue(0, 0.5) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def vtk_iso(vol, iso_thresh=1): im_data = vol.tostring() img = vtk.vtkImageImport() img.CopyImportVoidPointer(im_data, len(im_data)) img.SetDataScalarType(vtk.VTK_UNSIGNED_SHORT) img.SetNumberOfScalarComponents(1) img.SetDataExtent(0, vol.shape[2]-1, 0, vol.shape[1]-1, 0, vol.shape[0]-1) img.SetWholeExtent(0, vol.shape[2]-1, 0, vol.shape[1]-1, 0, vol.shape[0]-1) iso = vtk.vtkMarchingCubes() iso.SetInput(img.GetOutput()) iso.SetValue(0, iso_thresh) return iso,img
def DisplayLevelSetSurface(self,levelSets,value=0.0): marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInputData(levelSets) marchingCubes.SetValue(0,value) marchingCubes.Update() self.OutputText('Displaying.\n') self.SurfaceViewer.Surface = marchingCubes.GetOutput() self.SurfaceViewer.Display = 0 self.SurfaceViewer.Opacity = 0.5 self.SurfaceViewer.BuildView()
def marchingCubes(self, image, ijkToRasMatrix, threshold): transformIJKtoRAS = vtk.vtkTransform() transformIJKtoRAS.SetMatrix(ijkToRasMatrix) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInputData(image) marchingCubes.SetValue(0, threshold) marchingCubes.ComputeScalarsOn() marchingCubes.ComputeGradientsOn() marchingCubes.ComputeNormalsOn() marchingCubes.ReleaseDataFlagOn() marchingCubes.Update() if transformIJKtoRAS.GetMatrix().Determinant() < 0: reverser = vtk.vtkReverseSense() reverser.SetInputData(marchingCubes.GetOutput()) reverser.ReverseNormalsOn() reverser.ReleaseDataFlagOn() reverser.Update() correctedOutput = reverser.GetOutput() else: correctedOutput = marchingCubes.GetOutput() transformer = vtk.vtkTransformPolyDataFilter() transformer.SetInputData(correctedOutput) transformer.SetTransform(transformIJKtoRAS) transformer.ReleaseDataFlagOn() transformer.Update() normals = vtk.vtkPolyDataNormals() normals.ComputePointNormalsOn() normals.SetInputData(transformer.GetOutput()) normals.SetFeatureAngle(60) normals.SetSplitting(1) normals.ReleaseDataFlagOn() normals.Update() stripper = vtk.vtkStripper() stripper.SetInputData(normals.GetOutput()) stripper.ReleaseDataFlagOff() stripper.Update() stripper.GetOutput() result = vtk.vtkPolyData() result.DeepCopy(stripper.GetOutput()) return result
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 DisplayLevelSetSurface(self,levelSets,value=0.0): marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInput(levelSets) marchingCubes.SetValue(0,value) marchingCubes.Update() self.OutputText('Displaying.\n') self.SurfaceViewer.Surface = marchingCubes.GetOutput() if self.SurfaceViewer.Surface.GetSource(): self.SurfaceViewer.Surface.GetSource().UnRegisterAllOutputs() self.SurfaceViewer.Display = 1 self.SurfaceViewer.Opacity = 0.5 self.SurfaceViewer.BuildView()
def _setup_surface(self): """Create the isosurface object, mapper and actor""" self._surface_level = INIT_SURFACE_LEVEL self._surface_algorithm = vtk.vtkMarchingCubes() self._surface_algorithm.SetInputData(self._volume) self._surface_algorithm.ComputeNormalsOn() self._surface_algorithm.SetValue(0, self._surface_level) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self._surface_algorithm.GetOutputPort()) mapper.ScalarVisibilityOff() self._surface_actor = vtk.vtkActor() self._surface_actor.GetProperty().SetColor(self._color[0], self._color[1], self._color[2]) self._surface_actor.SetMapper(mapper) self._renderer.AddViewProp(self._surface_actor)
def calculateFrontAndRear(self, reader, maxPush, minPush): """ Method to calculate front and rear of objects in the track Image parameter must be vtkImageData """ spacing = [] for i in range(len(self.voxelSize)): spacing.append(self.voxelSize[i] / self.voxelSize[0]) for tp in range(self.mintp, self.maxtp + 1): label = self.values[tp] com1 = self.points[tp] if tp == self.maxtp: # Use latest direction for i in range(len(direction)): direction[i] *= -1.0 else: com2 = self.points[tp+1] direction = [] for i in range(len(com1)): direction.append(com2[i] - com1[i]) # Polygon data image = reader.getDataSet(tp) objThreshold = vtk.vtkImageThreshold() objThreshold.SetInput(image) objThreshold.SetOutputScalarTypeToUnsignedChar() objThreshold.SetInValue(255) objThreshold.SetOutValue(0) objThreshold.ThresholdBetween(label,label) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInput(objThreshold.GetOutput()) marchingCubes.SetValue(0, 255) marchingCubes.Update() polydata = marchingCubes.GetOutput() polydata.Update() front = self.locateOutmostPoint(polydata, com1, direction, maxPush, minPush) for i in range(len(direction)): direction[i] *= -1.0 rear = self.locateOutmostPoint(polydata, com1, direction, maxPush, minPush) for i in range(len(front)): front[i] /= spacing[i] rear[i] /= spacing[i] self.fronts[tp] = tuple(front) self.rears[tp] = tuple(rear)
def create_lungcontour(self): """Create a lungcontour using the Marching Cubes algorithm and smooth the surface """ self._view_frame.SetStatusText("Calculating lungcontour...") contourLung = vtk.vtkMarchingCubes() contourLung.SetValue(0,1) contourLung.SetInput(self.mask_data) smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInput(contourLung.GetOutput()) smoother.BoundarySmoothingOn() smoother.SetNumberOfIterations(40) smoother.Update() self.lung_mapper.SetInput(smoother.GetOutput()) self.lung_mapper.Update() self._view_frame.SetStatusText("Calculated lungcontour")
def ensureInSegment(self, image, lesionMesh, pathSegment, nameSegment, image_pos_pat, image_ori_pat): # Proceed to build reference frame for display objects based on DICOM coords [transformed_image, transform_cube] = self.loadDisplay.dicomTransform(image, image_pos_pat, image_ori_pat) dataToStencil = vtk.vtkPolyDataToImageStencil() dataToStencil.SetInput(lesionMesh) dataToStencil.SetOutputOrigin(transformed_image.GetOrigin()) print transformed_image.GetOrigin() dataToStencil.SetOutputSpacing(transformed_image.GetSpacing()) print transformed_image.GetSpacing() dataToStencil.SetOutputWholeExtent(transformed_image.GetExtent()) dataToStencil.Update() stencil = vtk.vtkImageStencil() stencil.SetInput(transformed_image) stencil.SetStencil(dataToStencil.GetOutput()) stencil.ReverseStencilOff() stencil.SetBackgroundValue(0.0) stencil.Update() newSegment = vtk.vtkMetaImageWriter() newSegment.SetFileName(pathSegment+'/'+nameSegment+'.mhd') newSegment.SetInput(stencil.GetOutput()) newSegment.Write() thresh = vtk.vtkImageThreshold() thresh.SetInput(stencil.GetOutput()) thresh.ThresholdByUpper(1) thresh.SetInValue(255) thresh.SetOutValue(0) thresh.Update() contouriso = vtk.vtkMarchingCubes() contouriso.SetInput(thresh.GetOutput()) contouriso.SetValue(0,125) contouriso.ComputeScalarsOn() contouriso.Update() # Recalculate num_voxels and vol_lesion on VOI nvoxels = contouriso.GetOutput().GetNumberOfCells() npoints = contouriso.GetOutput().GetNumberOfPoints() print "Number of points: %d" % npoints print "Number of cells: %d" % nvoxels return contouriso.GetOutput()
def marchingCubes(img,spacing=[1.0,1.0,1.0],contours=[]): importer = numpy2VTK(img,spacing) if len(contours) == 0: contours = [[img.max(),1.0,1.0,1.0,1.0]] actors = [] for c in contours: mc = vtk.vtkMarchingCubes() mc.ComputeScalarsOff() mc.ComputeGradientsOff() mc.ComputeNormalsOff() mc.SetValue( 0, c[0] ) mc.SetInput( importer.GetOutput()) # connectivityFilter = vtk.vtkPolyDataConnectivityFilter() # connectivityFilter.SetInput(mc.GetOutput()) # connectivityFilter.ColorRegionsOff() # connectivityFilter.SetExtractionModeToLargestRegion() # tris = vtk.vtkTriangleFilter() # tris.SetInput(mc.GetOutput()) # tris.GetOutput().ReleaseDataFlagOn() # tris.Update() # strip = vtk.vtkStripper() # strip.SetInput(tris.GetOutput()) # strip.GetOutput().ReleaseDataFlagOn() # strip.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInput(mc.GetOutput() ) mapper.ImmediateModeRenderingOn() # mapper.SetInput( connectivityFilter.GetOutput() ) actor = vtk.vtkActor() actor.SetMapper( mapper) actor.GetProperty().SetColor(c[1],c[2],c[3]) actor.GetProperty().SetOpacity(c[4]) actor.GetProperty().SetRepresentationToSurface() actors.append(actor) return actors
def isoSurface(reader,ren,renWin,isoValue,color,opacity): print color marchingCube = vtk.vtkMarchingCubes() marchingCube.SetInputConnection(reader.GetOutputPort()) marchingCube.SetValue(0,isoValue) marchingCube.ComputeNormalsOn() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(marchingCube.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color[0],color[1],color[2]) actor.GetProperty().SetOpacity(opacity) ren.RemoveAllViewProps() ren.AddActor(actor) ren.SetBackground(0.329412, 0.34902, 0.427451) #paraview blue from tutorial renWin.Render()
def __init__(self, parent, visualizer, **kws): """ Initialization """ self.init = False VisualizationModule.__init__(self, parent, visualizer, numberOfInputs=(2, 2), **kws) # self.name = "Surface Rendering" self.normals = vtk.vtkPolyDataNormals() self.smooth = None self.volumeModule = None self.scalarRange = (0, 255) for i in range(1, 3): self.setInputChannel(i, i) self.eventDesc = "Rendering iso-surface" self.decimate = vtk.vtkDecimatePro() self.mapper = vtk.vtkPolyDataMapper() self.mapper2 = vtk.vtkPolyDataMapper() self.contour = vtk.vtkMarchingCubes() self.contour2 = vtk.vtkDiscreteMarchingCubes() self.descs = { "Normals": "Smooth surface with normals", "FeatureAngle": "Feature angle of normals\n", "Simplify": "Simplify surface", "PreserveTopology": "Preserve topology", "Transparency": "Surface transparency", "Distance": "Distance to consider inside", "MarkColor": "Mark in/outside objects with colors", } self.actor = self.lodActor = vtk.vtkLODActor() self.lodActor.SetMapper(self.mapper) self.lodActor.SetNumberOfCloudPoints(10000) self.actor2 = vtk.vtkLODActor() self.actor2.SetMapper(self.mapper2) self.actor2.SetNumberOfCloudPoints(10000) self.renderer = self.parent.getRenderer() self.renderer.AddActor(self.lodActor) self.renderer.AddActor(self.actor2) lib.messenger.connect(None, "highlight_object", self.onHighlightObject)
def __init__(self, imageData, intensity, color=None): self._uuid = uuid.uuid1() if intensity!=None: self.intensity = intensity if color==None: color=self.color_ self.set_color(color) self.connect = ConnectFilter() self.deci = DecimateFilter() self.marchingCubes = vtk.vtkMarchingCubes() self.marchingCubes.SetInput(imageData) self.output = vtk.vtkPassThrough() self.prog = ProgressBarDialog( title='Rendering surface %s' % self.label, parent=None, msg='Marching cubes ....', size=(300,40), ) self.prog.set_modal(True) def start(o, event): self.prog.show() while gtk.events_pending(): gtk.main_iteration() def progress(o, event): val = o.GetProgress() self.prog.bar.set_fraction(val) while gtk.events_pending(): gtk.main_iteration() def end(o, event): self.prog.hide() while gtk.events_pending(): gtk.main_iteration() self.marchingCubes.AddObserver('StartEvent', start) self.marchingCubes.AddObserver('ProgressEvent', progress) self.marchingCubes.AddObserver('EndEvent', end) self.update_pipeline() self.notify_add_surface(self.output)
def opImplement(self): sample_implicit = vtk.vtkSampleFunction(); #sample_implicit.CappingOn(); sample_implicit.ComputeNormalsOn(); #sample_implicit.SetCapValue(.05); from math import ceil; from random import randint; x_len = self.bbox.x_max - self.bbox.x_min ; y_len = self.bbox.y_max -self.bbox.y_min ; z_len = self.bbox.z_max -self.bbox.z_min ; x_res = int(ceil(x_len/self.resoulation[0])); y_res = int(ceil(y_len/self.resoulation[1])); z_res = int(ceil(z_len/self.resoulation[2])); import time; threshold = 1.5; #Main slower.... #sample_implicit.SetSampleDimensions(x_res,y_res,z_res); sample_implicit.SetSampleDimensions(int(VOLUME_SETP),int(VOLUME_SETP),int(VOLUME_SETP)); #sample_implicit.SetSampleDimensions(100,100,100); sample_implicit.SetImplicitFunction(self.data); sample_implicit.SetOutputScalarTypeToUnsignedChar(); sample_implicit.SetModelBounds(self.bbox.x_min * threshold,self.bbox.x_max * threshold,self.bbox.y_min * threshold,self.bbox.y_max * threshold,self.bbox.z_min * threshold,self.bbox.z_max * threshold); sample_implicit.Update(); sampled_result = sample_implicit.GetOutput(); #Difference between Marching cubes and contour filter????? structed_point2Poly = vtk.vtkMarchingCubes(); #structed_point2Poly = vtk.vtkContourFilter(); structed_point2Poly.SetInputData(sampled_result); structed_point2Poly.ComputeScalarsOff(); structed_point2Poly.ComputeNormalsOff(); structed_point2Poly.ComputeGradientsOff(); structed_point2Poly.GenerateValues(1,1,1); #structed_point2Poly.SetValue(0,int(IMAGEIN+1)); #threshold structed_point2Poly.SetValue(0,int((IMAGEIN+IMAGEOUT)/2.0)); #threshold structed_point2Poly.Update(); result = structed_point2Poly.GetOutput(); return result;
def GeneratePolyData(self): if self._imagemask: contour_filter = vtk.vtkMarchingCubes() contour_filter.ReleaseDataFlagOn() contour_filter.SetNumberOfContours(1) contour_filter.SetComputeScalars(0) contour_filter.SetComputeNormals(0) if vtk.vtkVersion().GetVTKMajorVersion() > 5: contour_filter.SetInputData(self._imagemask) else: contour_filter.SetInput(self._imagemask) contour_filter.SetValue(0, 128.0) try: contour_filter.Update() except: print sys.exc_type, sys.exc_value return False decimate = vtk.vtkDecimatePro() decimate.ReleaseDataFlagOn() decimate.SetInputConnection(contour_filter.GetOutputPort()) decimate.PreserveTopologyOn() decimate.SetTargetReduction(0) try: decimate.Update() except: print sys.exc_type, sys.exc_value return False if self._polydata is None: self._polydata = GeometryObject( self._name, self._name, decimate.GetOutputPort()) else: self._polydata.SetInputConnection(decimate.GetOutputPort()) if self._wireframe: self._polydata.SetWireFrameOn() else: self._polydata.SetWireFrameOff() self._polydata.SetVisibilityOff()
def filter_marching_cubes(vtkObject, isovalue=1e-5): """ Create vtkMarchingCubes filter on vtkObject. :param vtkObject: input :param isovalue: contour value :type vtkObject: :py:class:`vtk.vtkObject` :type isovalue: float >>> image_data = create_image_data_from_array(surf) >>> cubes = filter_marching_cubes(image_data) >>> show(cubes) """ cubes = vtk.vtkMarchingCubes() pipe(vtkObject, cubes) cubes.SetValue(0, isovalue) cubes.ComputeScalarsOn() cubes.ComputeNormalsOn() return cubes
def __init__(self, volume, level=None): self._surface_algorithm = None self._renderer = None self._actor = None self._mapper = None self._volume_array = None self._float_array = _vtk.vtkFloatArray() self._image_data = _vtk.vtkImageData() self._image_data.GetPointData().SetScalars(self._float_array) self._setup_data(_numpy.float32(volume)) self._surface_algorithm = _vtk.vtkMarchingCubes() self._surface_algorithm.SetInputData(self._image_data) self._surface_algorithm.ComputeNormalsOn() if level is not None: try: self.set_multiple_levels(iter(level)) except TypeError: self.set_level(0, level) self._mapper = _vtk.vtkPolyDataMapper() self._mapper.SetInputConnection(self._surface_algorithm.GetOutputPort()) self._mapper.ScalarVisibilityOn() # new self._actor = _vtk.vtkActor() self._actor.SetMapper(self._mapper)