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 SurfaceReconstruction(self): pointSource = vtk.vtkProgrammableSource() def readPoints(): output = pointSource.GetPolyDataOutput() points = vtk.vtkPoints() output.SetPoints(points) for i in IDList: p = self.pointCloud.vtkPoints.GetPoint(i) points.InsertNextPoint(p) pointSource.SetExecuteMethod(readPoints) surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cf.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(1, 0.3882, 0.2784) actor.GetProperty().SetSpecularColor(1, 1, 1) actor.GetProperty().SetSpecular(.4) actor.GetProperty().SetSpecularPower(50) self.renderer.AddActor(actor) self.refresh_renderer()
def surfaceRecon(self): pointSource = vtk.vtkProgrammableSource() def readPoints(): output = pointSource.GetPolyDataOutput() #points = vtk.vtkPoints() output.SetPoints(self.vtkPoints) pointSource.SetExecuteMethod(readPoints) surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) print(surf) contour = vtk.vtkContourFilter() contour.SetInputConnection(surf.GetOutputPort()) contour.SetValue(0, 0.0) print(contour) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contour.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() contourMapper = vtk.vtkPolyDataMapper() contourMapper.SetInputConnection(reverse.GetOutputPort()) contourMapper.ScalarVisibilityOff() print(contourMapper) contourActor = vtk.vtkActor() contourActor.SetMapper(contourMapper) print(contourActor) return contourActor
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkSurfaceReconstructionFilter(), 'Processing.', ('vtkDataSet',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkSurfaceReconstructionFilter(), 'Processing.', ('vtkDataSet', ), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def reconstruct(self): # Read some points. Use a programmable filter to read them. # Construct the surface and create isosurface. surf = vtk.vtkSurfaceReconstructionFilter() surf.SetSampleSpacing(1) surf.SetInputConnection(self.pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper() map.SetInputConnection(reverse.GetOutputPort()) map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(.4) surfaceActor.GetProperty().SetSpecularPower(50) # Create the RenderWindow, Renderer and both Actors ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(1, 0, 0) ren.GetActiveCamera().SetViewUp(0, 0, 1) ren.ResetCamera() ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Elevation(30) ren.GetActiveCamera().Dolly(1.2) ren.ResetCameraClippingRange() return cf
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() # Create source source = vtk.vtkSphereSource() #source = vtk.vtkConeSource() source.Update() polydata = vtk.vtkPolyData() polydata.SetPoints(source.GetOutput().GetPoints()) # Construct the surface the create isosurface surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volumn whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent, vetReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reverse.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
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() # Create source source = vtk.vtkSphereSource() #source = vtk.vtkConeSource() source.Update() polydata = vtk.vtkPolyData() polydata.SetPoints(source.GetOutput().GetPoints()) # Construct the surface the create isosurface surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volumn whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent, vetReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reverse.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def createSurface(self, points): surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(points.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() return reverse
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') surfaceModellerFilter = vtk.vtkSurfaceReconstructionFilter() surfaceModellerFilter.SetInputData(self.Surface) surfaceModellerFilter.SetSampleSpacing(self.SampleSpacing) surfaceModellerFilter.SetNeighborhoodSize(40) surfaceModellerFilter.Update() self.Image = surfaceModellerFilter.GetOutput() if self.NegativeInside: negate = vtk.vtkImageMathematics() negate.SetInputData(self.Image) negate.SetConstantK(-1.0) negate.SetOperationToMultiplyByK() negate.Update() self.Image = negate.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') surfaceModellerFilter = vtk.vtkSurfaceReconstructionFilter() surfaceModellerFilter.SetInputData(self.Surface) surfaceModellerFilter.SetSampleSpacing(self.SampleSpacing) surfaceModellerFilter.SetNeighborhoodSize(40) surfaceModellerFilter.Update() self.Image = surfaceModellerFilter.GetOutput() if self.NegativeInside: negate = vtk.vtkImageMathematics() negate.SetInputData(self.Image) negate.SetConstantK(-1.0) negate.SetOperationToMultiplyByK() negate.Update() self.Image = negate.GetOutput()
def compute(self): import vtk phasors = self.get_input("FFT Input") numbins = self.get_input("Num Bins") phasor_matrix = phasors.matrix.toarray() (timeslices, phases) = phasor_matrix.shape point_set = vtk.vtkPoints() histo = numpy.zeros((timeslices, numbins)) for time in xrange(timeslices): phase_slice = phasor_matrix[time, :] reals = phase_slice.real imaginary = phase_slice.imag phases = scipy.arctan2(imaginary, reals) phases = phases * (180. / scipy.pi) bins = phases % numbins for b in bins: histo[time, b] += 1 self.form_point_set(histo, point_set) pointdata = vtk.vtkUnstructuredGrid() pointdata.SetPoints(point_set) self.surf_filter = vtk.vtkSurfaceReconstructionFilter() self.surf_filter.SetInput(0, pointdata) # self.surf_filter.Update() reg = core.modules.module_registry vtk_set = reg.registry.get_descriptor_by_name( 'edu.utah.sci.vistrails.vtk', 'vtkAlgorithmOutput').module() vtk_set.vtkInstance = self.surf_filter.GetOutputPort() histo_mat = SparseMatrix() histo_mat.matrix = sparse.csc_matrix(histo) self.set_output("Num Slices", timeslices) self.set_output("Phase Histogram", histo_mat) self.set_output("Phase Geometry", vtk_set)
def surfaceRecon(vtkPolyData): surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputData(vtkPolyData) print(surf) contour = vtk.vtkContourFilter() contour.SetInputConnection(surf.GetOutputPort()) contour.SetValue(0, 0.0) print(contour) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contour.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() contourMapper = vtk.vtkPolyDataMapper() contourMapper.SetInputConnection(reverse.GetOutputPort()) contourMapper.ScalarVisibilityOff() print(contourMapper) contourActor = vtk.vtkActor() contourActor.SetMapper(contourMapper) print(contourActor) return contourActor
def compute(self): import vtk phasors = self.getInputFromPort("FFT Input") numbins = self.getInputFromPort("Num Bins") phasor_matrix = phasors.matrix.toarray() (timeslices,phases) = phasor_matrix.shape point_set = vtk.vtkPoints() histo = numpy.zeros((timeslices, numbins)) for time in xrange(timeslices): phase_slice = phasor_matrix[time,:] reals = phase_slice.real imaginary = phase_slice.imag phases = scipy.arctan2(imaginary, reals) phases = phases * (180. / scipy.pi) bins = phases % numbins for b in bins: histo[time,b] += 1 self.form_point_set(histo, point_set) pointdata = vtk.vtkUnstructuredGrid() pointdata.SetPoints(point_set) self.surf_filter = vtk.vtkSurfaceReconstructionFilter() self.surf_filter.SetInput(0,pointdata) # self.surf_filter.Update() reg = core.modules.module_registry vtk_set = reg.registry.get_descriptor_by_name('edu.utah.sci.vistrails.vtk', 'vtkAlgorithmOutput').module() vtk_set.vtkInstance = self.surf_filter.GetOutputPort() histo_mat = SparseMatrix() histo_mat.matrix = sparse.csc_matrix(histo) self.setResult("Num Slices", timeslices) self.setResult("Phase Histogram", histo_mat) self.setResult("Phase Geometry", vtk_set)
def createPlaneModel(self, InputModel, plane, breastFlag): #this function creates a model (visual representation) of the defined plane #The input is linearly extruded to create a closed input model so that when the cutter extracts the # region it is large enough to create a plane to cover the entire breast closedInputModel = vtk.vtkLinearExtrusionFilter() closedInputModel.SetInputData(InputModel) closedInputModel.SetScaleFactor(100) closedInputModel.CappingOn() closedInputModel.Update() clippedInput = vtk.vtkClipPolyData() clippedInput.SetInputData(closedInputModel.GetOutput()) clippedInput.SetClipFunction(plane) clippedInput.SetValue(0) clippedInput.SetInsideOut(breastFlag) clippedInput.Update() cutterPlane = vtk.vtkCutter() cutterPlane.SetCutFunction(plane) cutterPlane.SetInputData(clippedInput.GetOutput()) cutterPlane.Update() cutterModel = vtk.vtkPolyData() cutterModel = cutterPlane.GetOutput() surfPlane = vtk.vtkSurfaceReconstructionFilter() surfPlane.SetInputData(cutterModel) surfPlane.SetSampleSpacing(2.5) cfPlane = vtk.vtkContourFilter() cfPlane.SetInputConnection(surfPlane.GetOutputPort()) cfPlane.SetValue(0, 0.0) reversePlane = vtk.vtkReverseSense() reversePlane.SetInputConnection(cfPlane.GetOutputPort()) reversePlane.ReverseCellsOn() reversePlane.ReverseNormalsOn() return reversePlane
def vertices_to_surface(vertices, num_simplify_iter=3, smooth=True): polydata = mesh_to_polydata(vertices, []) surf = vtk.vtkSurfaceReconstructionFilter() surf.SetNeighborhoodSize(30) surf.SetSampleSpacing(5) surf.SetInputData(polydata) surf.Update() # Visualize signed distance function computed by VTK (VTK bug: error outside actual contour) # q = surf.GetOutput() # arr = numpy_support.vtk_to_numpy(q.GetPointData().GetScalars()) # sc = arr.reshape(q.GetDimensions()[::-1]) # plt.imshow(sc[40,:,:]); # plt.colorbar(); cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.) # print cf.GetNumberOfContours() cf.Update() # polydata = cf.GetOutput() reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() polydata = reverse.GetOutput() polydata = simplify_polydata(polydata, num_simplify_iter=num_simplify_iter, smooth=smooth) return polydata
def gen_surface(tomo, lbl=1, mask=True, other_mask=None, purge_ratio=1, field=False, mode_2d=False, verbose=False): """ Generates a VTK PolyData surface from a segmented tomogram. Args: tomo (numpy.ndarray or str): the input segmentation as numpy ndarray or the file name in MRC, EM or VTI format lbl (int, optional): label for the foreground, default 1 mask (boolean, optional): if True (default), the input segmentation is used as mask for the surface other_mask (numpy.ndarray, optional): if given (default None), this segmentation is used as mask for the surface purge_ratio (int, optional): if greater than 1 (default 1), then 1 every purge_ratio points of the segmentation are randomly deleted field (boolean, optional): if True (default False), additionally returns the polarity distance scalar field mode_2d (boolean, optional): needed for polarity distance calculation (if field is True), if True (default False), ... verbose (boolean, optional): if True (default False), prints out messages for checking the progress Returns: - output surface (vtk.vtkPolyData) - polarity distance scalar field (np.ndarray), if field is True """ # Read in the segmentation (if file is given) and check format if isinstance(tomo, str): tomo = io.load_tomo(tomo) elif not isinstance(tomo, np.ndarray): raise pexceptions.PySegInputError( expr='gen_surface', msg='Input must be either a file name or a ndarray.') # Load file with the cloud of points nx, ny, nz = tomo.shape cloud = vtk.vtkPolyData() points = vtk.vtkPoints() cloud.SetPoints(points) if purge_ratio <= 1: for x in range(nx): for y in range(ny): for z in range(nz): if tomo[x, y, z] == lbl: points.InsertNextPoint(x, y, z) else: count = 0 mx_value = purge_ratio - 1 purge = np.random.randint(0, purge_ratio + 1, nx * ny * nz) for x in range(nx): for y in range(ny): for z in range(nz): if purge[count] == mx_value: if tomo[x, y, z] == lbl: points.InsertNextPoint(x, y, z) count += 1 if verbose: print('Cloud of points loaded...') # Creating the isosurface surf = vtk.vtkSurfaceReconstructionFilter() # surf.SetSampleSpacing(2) surf.SetSampleSpacing(purge_ratio) # surf.SetNeighborhoodSize(10) surf.SetInputData(cloud) contf = vtk.vtkContourFilter() contf.SetInputConnection(surf.GetOutputPort()) contf.SetValue(0, 0) rsurf = reverse_sense_and_normals(contf.GetOutputPort()) if verbose: print('Isosurfaces generated...') # Translate and scale to the proper positions cloud.ComputeBounds() rsurf.ComputeBounds() xmin, xmax, ymin, ymax, zmin, zmax = cloud.GetBounds() rxmin, rxmax, rymin, rymax, rzmin, rzmax = rsurf.GetBounds() scale_x = (xmax - xmin) / (rxmax - rxmin) scale_y = (ymax - ymin) / (rymax - rymin) denom = rzmax - rzmin num = zmax - xmin if (denom == 0) or (num == 0): scale_z = 1 else: scale_z = (zmax - zmin) / (rzmax - rzmin) transp = vtk.vtkTransform() transp.Translate(xmin, ymin, zmin) transp.Scale(scale_x, scale_y, scale_z) transp.Translate(-rxmin, -rymin, -rzmin) tpd = vtk.vtkTransformPolyDataFilter() tpd.SetInputData(rsurf) tpd.SetTransform(transp) tpd.Update() tsurf = tpd.GetOutput() if verbose: print('Rescaled and translated...') # Masking according to distance to the original segmentation if mask: if other_mask is None: tomod = distance_transform_edt(np.invert(tomo == lbl)) elif isinstance(other_mask, np.ndarray): tomod = distance_transform_edt(np.invert(other_mask == lbl)) else: raise pexceptions.PySegInputError( expr='gen_surface', msg='Other mask must be a ndarray.') for i in range(tsurf.GetNumberOfCells()): # Check if all points which made up the polygon are in the mask points_cell = tsurf.GetCell(i).GetPoints() count = 0 for j in range(0, points_cell.GetNumberOfPoints()): x, y, z = points_cell.GetPoint(j) if (tomod[int(round(x)), int(round(y)), int(round(z))] > MAX_DIST_SURF): count += 1 if count > 0: tsurf.DeleteCell(i) # Release free memory tsurf.RemoveDeletedCells() if verbose: print('Mask applied...') # Field distance if field: # Get normal attributes norm_flt = vtk.vtkPolyDataNormals() norm_flt.SetInputData(tsurf) norm_flt.ComputeCellNormalsOn() norm_flt.AutoOrientNormalsOn() norm_flt.ConsistencyOn() norm_flt.Update() tsurf = norm_flt.GetOutput() # for i in range(tsurf.GetPointData().GetNumberOfArrays()): # array = tsurf.GetPointData().GetArray(i) # if array.GetNumberOfComponents() == 3: # break array = tsurf.GetCellData().GetNormals() # Build membrane mask tomoh = np.ones(shape=tomo.shape, dtype=np.bool) tomon = np.ones(shape=(tomo.shape[0], tomo.shape[1], tomo.shape[2], 3), dtype=io.TypesConverter().vtk_to_numpy(array)) # for i in range(tsurf.GetNumberOfCells()): # points_cell = tsurf.GetCell(i).GetPoints() # for j in range(0, points_cell.GetNumberOfPoints()): # x, y, z = points_cell.GetPoint(j) # # print(x, y, z, array.GetTuple(j)) # x, y, z = int(round(x)), int(round(y)), int(round(z)) # tomo[x, y, z] = False # tomon[x, y, z, :] = array.GetTuple(j) for i in range(tsurf.GetNumberOfCells()): points_cell = tsurf.GetCell(i).GetPoints() for j in range(0, points_cell.GetNumberOfPoints()): x, y, z = points_cell.GetPoint(j) # print(x, y, z, array.GetTuple(j)) x, y, z = int(round(x)), int(round(y)), int(round(z)) if tomo[x, y, z] == lbl: tomoh[x, y, z] = False tomon[x, y, z, :] = array.GetTuple(i) # Distance transform tomod, ids = distance_transform_edt(tomoh, return_indices=True) # Compute polarity if mode_2d: for x in range(nx): for y in range(ny): for z in range(nz): i_x, i_y, i_z = (ids[0, x, y, z], ids[1, x, y, z], ids[2, x, y, z]) norm = tomon[i_x, i_y, i_z] norm[2] = 0 pnorm = (i_x, i_y, 0) p = (x, y, 0) dprod = dot_norm(np.asarray(p, dtype=np.float), np.asarray(pnorm, dtype=np.float), np.asarray(norm, dtype=np.float)) tomod[x, y, z] = tomod[x, y, z] * np.sign(dprod) else: for x in range(nx): for y in range(ny): for z in range(nz): i_x, i_y, i_z = (ids[0, x, y, z], ids[1, x, y, z], ids[2, x, y, z]) hold_norm = tomon[i_x, i_y, i_z] norm = hold_norm # norm[0] = (-1) * hold_norm[1] # norm[1] = hold_norm[0] # norm[2] = hold_norm[2] pnorm = (i_x, i_y, i_z) p = (x, y, z) dprod = dot_norm(np.asarray(pnorm, dtype=np.float), np.asarray(p, dtype=np.float), np.asarray(norm, dtype=np.float)) tomod[x, y, z] = tomod[x, y, z] * np.sign(dprod) if verbose: print('Distance field generated...') return tsurf, tomod if verbose: print('Finished!') return tsurf
def myMain(controller,args): fname=args.fname controller=args.controller myid = controller.GetLocalProcessId(); numProcs = controller.GetNumberOfProcesses(); pts=np.loadtxt(fname) sf=100 paint=rgbPainter() r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2]) #im=np.abs(getGeomImperfection(r,z,np.mean(r))) if pts.shape[1] == 4: im=pts[:,3] else: im=getGeomImperfection(r,z,np.mean(r)) rid=r-im xx,yy,zz=cyl2rec(rid+im*sf,t,z) math = vtk.vtkMath() points = vtk.vtkPoints() colors =vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3); colors.SetName("Colors"); for i in range(0,pts.shape[0]): #points.InsertPoint(i,pts[i][0],pts[i][1],pts[i][2] ) points.InsertPoint(i,xx[i],yy[i],zz[i] ) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.GetPointData().SetScalars(colors) polydata.Update() surf =vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) surf.SetNeighborhoodSize(40) #surf.SetSampleSpacing(6.0) if (myid != 0): controller.AddRMI(surf.Update,'',200) controller.ProcessRMIs(); else: contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(surf.GetOutputPort()) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contourFilter.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() outputPolyData=reverse.GetOutput() #for i in range(0,pts.shape[0]): # dcolor=np.zeros(3) # colorLookupTable.GetColor(im[i],dcolor) # cc=dcolor*255.0 # colors.InsertNextTupleValue(cc) #outputPolyData.GetPointData().SetScalars(polydata.GetPointData().GetScalars() ); newSurf = transform_back( points, reverse.GetOutput()); pts2=np.zeros((newSurf.GetNumberOfPoints(),3)) for i in range(0,newSurf.GetNumberOfPoints()): pts2[i,:]=newSurf.GetPoint(i) r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2]) im2=getGeomImperfection(r2,z2,np.mean(r2)) #im2-=np.min(im2) #im2=np.abs(im2) paint.setValue(np.min(im2)) paint.setValue(np.max(im2)) for i in range(0,newSurf.GetNumberOfPoints()): colors.InsertNextTupleValue(paint.getRGB(im2[i])) newSurf.GetPointData().SetScalars(colors ); mapper = vtk.vtkPolyDataMapper(); mapper.InterpolateScalarsBeforeMappingOn() #mapper.SetInputConnection(outputPolyData.GetProducerPort()) mapper.SetInputConnection(newSurf.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); ren = vtk.vtkRenderer(); renWin = vtk.vtkRenderWindow(); renWin.AddRenderer(ren); iren = vtk.vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) ren.AddActor(surfaceActor); ren.SetBackground(1, 1, 1); renWin.SetSize(800, 600); prn=1000. pc=-prn plXY = vtk.vtkPlaneSource() plXY.SetPoint1(prn,-prn,0) plXY.SetPoint2(-prn,prn,0) plXY.SetOrigin(pc,pc,0) plXY.SetCenter(0,0,0) plXYmap = vtk.vtkPolyDataMapper() plXYmap.SetInput(plXY.GetOutput()) plXYact = vtk.vtkActor() plXYact.SetMapper(plXYmap) plXYact.GetProperty().SetOpacity(0.1) plYZ = vtk.vtkPlaneSource() plYZ.SetCenter(0,pc,pc) plYZ.SetPoint1(0,prn,-prn) plYZ.SetPoint2(0,-prn,prn) plYZmap = vtk.vtkPolyDataMapper() plYZmap.SetInput(plYZ.GetOutput()) plYZact = vtk.vtkActor() plYZact.SetMapper(plYZmap) plYZact.GetProperty().SetOpacity(0.1) plZX = vtk.vtkPlaneSource() plZX.SetCenter(pc,0,pc) plZX.SetPoint1(prn,0,-prn) plZX.SetPoint2(-prn,0,prn) plZXmap = vtk.vtkPolyDataMapper() plZXmap.SetInput(plZX.GetOutput()) plZXact = vtk.vtkActor() plZXact.SetMapper(plZXmap) plZXact.GetProperty().SetOpacity(0.1) ren.AddActor(plXYact) ren.AddActor(plYZact) ren.AddActor(plZXact) ax=vtk.vtkAxesActor() ax.GetXAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetYAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetZAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ow=vtk.vtkOrientationMarkerWidget() ow.SetOrientationMarker(ax) ow.SetInteractor(iren) ow.SetViewport( 0.0, 0.0, 0.4, 0.4 ) ow.SetEnabled( 1 ) ow.InteractiveOn() lut=vtk.vtkLookupTable() lut.SetHueRange( 0.66667, 0.0 ) lut.SetSaturationRange (1.0, 1.0) lut.SetNumberOfColors(50)# len(self.plotables)) lut.SetTableRange(paint.getMinValue(),paint.getMaxValue()) lut.Build() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetOrientationToHorizontal() scalar_bar.SetLookupTable(lut) scalar_bar.SetTitle("Imperfection value"); scalar_bar.SetNumberOfLabels(11) scalar_bar_widget = vtk.vtkScalarBarWidget() scalar_bar_widget.SetInteractor(iren) scalar_bar_widget.SetScalarBarActor(scalar_bar) scalar_bar_widget.On() iren.Initialize(); renWin.Render(); iren.Start();
def reconstructSurface(folder): pointSource = vtk.vtkProgrammableSource() def readPoints(): output = pointSource.GetPolyDataOutput() points = vtk.vtkPoints() output.SetPoints(points) group_points = groupsToPoints(folder) for p in group_points: points.insertNextPoint(p[0],p[1],p[2]) pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface. surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper() map.SetInputConnection(reverse.GetOutputPort()) map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(.4) surfaceActor.GetProperty().SetSpecularPower(50) # Create the RenderWindow, Renderer and both Actors ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(1, 0, 0) ren.GetActiveCamera().SetViewUp(0, 0, 1) ren.ResetCamera() ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Elevation(30) ren.GetActiveCamera().Dolly(1.2) ren.ResetCameraClippingRange() iren.Initialize() renWin.Render() iren.Start()
def updateModelFromMarkup(self, inputMarkup, outputModel): """ Update model to enclose all points in the input markup list """ # Delaunay triangulation is robust and creates nice smooth surfaces from a small number of points, # however it can only generate convex surfaces robustly. useDelaunay = True # Create polydata point set from markup points points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = inputMarkup.GetNumberOfFiducials() # Surface generation algorithms behave unpredictably when there are not enough points # return if there are very few points if useDelaunay: if numberOfPoints < 3: return else: if numberOfPoints < 10: return points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): inputMarkup.GetNthFiducialPosition(i, new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) pointPolyData = vtk.vtkPolyData() pointPolyData.SetLines(cellArray) pointPolyData.SetPoints(points) # Create surface from point set if useDelaunay: delaunay = vtk.vtkDelaunay3D() delaunay.SetInputData(pointPolyData) surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) smoother = vtk.vtkButterflySubdivisionFilter() smoother.SetInputConnection(surfaceFilter.GetOutputPort()) smoother.SetNumberOfSubdivisions(3) smoother.Update() outputModel.SetPolyDataConnection(smoother.GetOutputPort()) else: surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputData(pointPolyData) surf.SetNeighborhoodSize(20) surf.SetSampleSpacing( 80 ) # lower value follows the small details more closely but more dense pointset is needed as input cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOff() reverse.ReverseNormalsOff() outputModel.SetPolyDataConnection(reverse.GetOutputPort()) # Create default model display node if does not exist yet if not outputModel.GetDisplayNode(): modelDisplayNode = slicer.mrmlScene.CreateNodeByClass( "vtkMRMLModelDisplayNode") # Get color of edited segment segmentationNode = self.scriptedEffect.parameterSetNode( ).GetSegmentationNode() segmentID = self.scriptedEffect.parameterSetNode( ).GetSelectedSegmentID() r, g, b = segmentationNode.GetSegmentation().GetSegment( segmentID).GetColor() modelDisplayNode.SetColor(r, g, b) # Edited segment color modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetSliceIntersectionThickness(2) modelDisplayNode.SetOpacity(0.3) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) outputModel.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) outputModel.GetDisplayNode().SliceIntersectionVisibilityOn() outputModel.Modified()
# vtkPolyData. math = vtk.vtkMath() pointSource = vtk.vtkProgrammableSource() def readPoints(): output = pointSource.GetPolyDataOutput() points = vtk.vtkPoints() output.SetPoints(points) for i in range(0, 50): x, y = math.Random(0,1), math.Random(0,1) points.InsertNextPoint(x, y, x*y+x) pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface. surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper()
line = file.readline() while line: data = line.split() #if data and data[0] == 'p': # x, y, z = float(data[1]), float(data[2]), float(data[3]) # points.InsertNextPoint(x, y, z) x, y, z = float(data[0]), float(data[1]), float(data[2]) points.InsertNextPoint(x, y, z) line = file.readline() pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface. surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() # save ply
def addCSVFile(self,fname,csvDelimiter=None): self.setCaption(r' File:'+str(fname)) pts=np.loadtxt(fname,csvDelimiter) r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2]) sf=self.scalingFactor if pts.shape[1] == 4: im=pts[:,3] else: im=getGeomImperfection(r,z,np.mean(r)) rid=r-im xx,yy,zz=cyl2rec(rid+im*sf,t,z) points = vtk.vtkPoints() colors =vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3); colors.SetName("Colors"); for i in range(0,pts.shape[0]): points.InsertPoint(i,xx[i],yy[i],zz[i] ) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.GetPointData().SetScalars(colors) polydata.Update() surf =vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) surf.SetNeighborhoodSize(self.nbSize) surf.SetSampleSpacing(self.sampleSpacing) contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(surf.GetOutputPort()) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contourFilter.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() outputPolyData=reverse.GetOutput() newSurf = self.transform_back( points, reverse.GetOutput()); pts2=np.zeros((newSurf.GetNumberOfPoints(),3)) for i in range(0,newSurf.GetNumberOfPoints()): pts2[i,:]=newSurf.GetPoint(i) r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2]) im2=getGeomImperfection(r2,z2,np.mean(r2)) self.paint.setValue(np.min(im2)) self.paint.setValue(np.max(im2)) for i in range(0,newSurf.GetNumberOfPoints()): colors.InsertNextTupleValue(self.paint.getRGB(im2[i])) newSurf.GetPointData().SetScalars(colors ); self.outputs.append(newSurf) mapper = vtk.vtkPolyDataMapper(); mapper.InterpolateScalarsBeforeMappingOn() mapper.SetInputConnection(newSurf.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); self.ren.AddActor(surfaceActor);
def addCSVFile(self,fname,mode='folded',csvDelimiter=None): self.setCaption(r' File:'+str(fname)) pts=np.loadtxt(fname,csvDelimiter) points = vtk.vtkPoints() r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2]) im_g=getGeomImperfection(r,z,np.mean(r)) if pts.shape[1] == 4: useThickImp=True else: useThickImp=False if useThickImp: im_t=pts[:,3] else: im_t=np.zeros(pts.shape[0]) rid=r-im_g if mode == 'unfolded': tt=t*r.mean() rr=im_g*self.scalingFactor for i in range(0,pts.shape[0]): points.InsertPoint(i,tt[i],z[i],rr[i] ) else: xx,yy,zz=cyl2rec(rid+im_g*self.scalingFactor,t,z) for i in range(0,pts.shape[0]): points.InsertPoint(i,xx[i],yy[i],zz[i] ) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.Update() if useThickImp: imps=im_t else: imps=im_g # imps=vtk.vtkFloatArray() # if useThickImp: # for i in range(0,polydata.GetNumberOfPoints()): # imps.InsertNextValue(im_t[i]) # else: # imps.InsertNextValue(im_g[i]) # polydata.GetPointData().SetScalars(imps); # surf =vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) surf.SetNeighborhoodSize(self.nbSize) surf.SetSampleSpacing(self.sampleSpacing) contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(surf.GetOutputPort()) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contourFilter.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() outputPolyData=reverse.GetOutput() newSurf = self.transform_back( points, reverse.GetOutput()); pts2=np.zeros((newSurf.GetNumberOfPoints(),3)) for i in range(0,newSurf.GetNumberOfPoints()): pts2[i,:]=newSurf.GetPoint(i) r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2]) kDTree = vtk.vtkKdTreePointLocator() kDTree.SetDataSet(polydata) kDTree.BuildLocator() colors=vtk.vtkFloatArray() for i in range(0,len(pts2)): kid=kDTree.FindClosestPoint(pts2[i]) colors.InsertNextValue(imps[kid]) # if mode == 'folded': # im2=getGeomImperfection(r2,z2,np.mean(r2))/self.scalingFactor # # if mode == 'unfolded': # im2=pts2[:,2]/self.scalingFactor # # colors=vtk.vtkFloatArray() # for i in range(0,newSurf.GetNumberOfPoints()): # colors.InsertNextValue(im2[i]) newSurf.GetPointData().SetScalars(colors); self.scalarRange=colors.GetRange() self.lut=vtk.vtkLookupTable() self.lut.SetNumberOfTableValues(100) self.lut.SetTableRange(self.scalarRange) self.lut.SetHueRange(0.667, 0.0) self.lut.Build() self.resP=newSurf.GetProducerPort() self.colors=colors self.outputs.append(newSurf) mapper = vtk.vtkPolyDataMapper(); mapper.SetLookupTable(self.lut) mapper.InterpolateScalarsBeforeMappingOn() mapper.SetInputConnection(newSurf.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); mapper.SetScalarRange(colors.GetRange()) surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); self.boundBox=newSurf.GetBounds() self.ren.AddActor(surfaceActor);
def myMain(controller, args): fname = args.fname controller = args.controller myid = controller.GetLocalProcessId() numProcs = controller.GetNumberOfProcesses() pts = np.loadtxt(fname) sf = 100 paint = rgbPainter() r, t, z = rec2cyl(pts[:, 0], pts[:, 1], pts[:, 2]) #im=np.abs(getGeomImperfection(r,z,np.mean(r))) if pts.shape[1] == 4: im = pts[:, 3] else: im = getGeomImperfection(r, z, np.mean(r)) rid = r - im xx, yy, zz = cyl2rec(rid + im * sf, t, z) math = vtk.vtkMath() points = vtk.vtkPoints() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for i in range(0, pts.shape[0]): #points.InsertPoint(i,pts[i][0],pts[i][1],pts[i][2] ) points.InsertPoint(i, xx[i], yy[i], zz[i]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.GetPointData().SetScalars(colors) polydata.Update() surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) surf.SetNeighborhoodSize(40) #surf.SetSampleSpacing(6.0) if (myid != 0): controller.AddRMI(surf.Update, '', 200) controller.ProcessRMIs() else: contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(surf.GetOutputPort()) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contourFilter.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() outputPolyData = reverse.GetOutput() #for i in range(0,pts.shape[0]): # dcolor=np.zeros(3) # colorLookupTable.GetColor(im[i],dcolor) # cc=dcolor*255.0 # colors.InsertNextTupleValue(cc) #outputPolyData.GetPointData().SetScalars(polydata.GetPointData().GetScalars() ); newSurf = transform_back(points, reverse.GetOutput()) pts2 = np.zeros((newSurf.GetNumberOfPoints(), 3)) for i in range(0, newSurf.GetNumberOfPoints()): pts2[i, :] = newSurf.GetPoint(i) r2, t2, z2 = rec2cyl(pts2[:, 0], pts2[:, 1], pts2[:, 2]) im2 = getGeomImperfection(r2, z2, np.mean(r2)) #im2-=np.min(im2) #im2=np.abs(im2) paint.setValue(np.min(im2)) paint.setValue(np.max(im2)) for i in range(0, newSurf.GetNumberOfPoints()): colors.InsertNextTupleValue(paint.getRGB(im2[i])) newSurf.GetPointData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() mapper.InterpolateScalarsBeforeMappingOn() #mapper.SetInputConnection(outputPolyData.GetProducerPort()) mapper.SetInputConnection(newSurf.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(mapper) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(800, 600) prn = 1000. pc = -prn plXY = vtk.vtkPlaneSource() plXY.SetPoint1(prn, -prn, 0) plXY.SetPoint2(-prn, prn, 0) plXY.SetOrigin(pc, pc, 0) plXY.SetCenter(0, 0, 0) plXYmap = vtk.vtkPolyDataMapper() plXYmap.SetInput(plXY.GetOutput()) plXYact = vtk.vtkActor() plXYact.SetMapper(plXYmap) plXYact.GetProperty().SetOpacity(0.1) plYZ = vtk.vtkPlaneSource() plYZ.SetCenter(0, pc, pc) plYZ.SetPoint1(0, prn, -prn) plYZ.SetPoint2(0, -prn, prn) plYZmap = vtk.vtkPolyDataMapper() plYZmap.SetInput(plYZ.GetOutput()) plYZact = vtk.vtkActor() plYZact.SetMapper(plYZmap) plYZact.GetProperty().SetOpacity(0.1) plZX = vtk.vtkPlaneSource() plZX.SetCenter(pc, 0, pc) plZX.SetPoint1(prn, 0, -prn) plZX.SetPoint2(-prn, 0, prn) plZXmap = vtk.vtkPolyDataMapper() plZXmap.SetInput(plZX.GetOutput()) plZXact = vtk.vtkActor() plZXact.SetMapper(plZXmap) plZXact.GetProperty().SetOpacity(0.1) ren.AddActor(plXYact) ren.AddActor(plYZact) ren.AddActor(plZXact) ax = vtk.vtkAxesActor() ax.GetXAxisCaptionActor2D().GetProperty().SetColor(0, 0, 0) ax.GetYAxisCaptionActor2D().GetProperty().SetColor(0, 0, 0) ax.GetZAxisCaptionActor2D().GetProperty().SetColor(0, 0, 0) ow = vtk.vtkOrientationMarkerWidget() ow.SetOrientationMarker(ax) ow.SetInteractor(iren) ow.SetViewport(0.0, 0.0, 0.4, 0.4) ow.SetEnabled(1) ow.InteractiveOn() lut = vtk.vtkLookupTable() lut.SetHueRange(0.66667, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetNumberOfColors(50) # len(self.plotables)) lut.SetTableRange(paint.getMinValue(), paint.getMaxValue()) lut.Build() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetOrientationToHorizontal() scalar_bar.SetLookupTable(lut) scalar_bar.SetTitle("Imperfection value") scalar_bar.SetNumberOfLabels(11) scalar_bar_widget = vtk.vtkScalarBarWidget() scalar_bar_widget.SetInteractor(iren) scalar_bar_widget.SetScalarBarActor(scalar_bar) scalar_bar_widget.On() iren.Initialize() renWin.Render() iren.Start()
def testReconstructSurface(self): # Read some points. Use a programmable filter to read them. # pointSource = vtk.vtkProgrammableSource() def readPoints(): fp = open(VTK_DATA_ROOT + "/Data/cactus.3337.pts", "r") points = vtk.vtkPoints() while True: line = fp.readline().split() if len(line) == 0: break if line[0] == "p": points.InsertNextPoint(float(line[1]), float(line[2]), float(line[3])) pointSource.GetPolyDataOutput().SetPoints(points) pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface # surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper() map.SetInputConnection(reverse.GetOutputPort()) map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(.4) surfaceActor.GetProperty().SetSpecularPower(50) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # Add the actors to the renderer, set the background and size # ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(300, 300) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(1, 0, 0) ren.GetActiveCamera().SetViewUp(0, 0, 1) ren.ResetCamera() ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Elevation(30) ren.GetActiveCamera().Dolly(1.2) ren.ResetCameraClippingRange() # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "reconstructSurface.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def reconstruct_surface(): """Example of constructing a surface from a point cloud https://github.com/Kitware/VTK/blob/a1a94d0ca96854fe72480cf2ec031a533b129b04/Examples/Modelling/Python/reconstructSurface.py """ pointSource = vtk.vtkProgrammableSource() def readPoints(): output = pointSource.GetPolyDataOutput() points = vtk.vtkPoints() output.SetPoints(points) fname = open('./data/point_clouds/cactus.3337.pts') line = fname.readline() while line: data = line.split() if data and data[0] == 'p': x, y, z = float(data[1]), float(data[2]), float(data[3]) points.InsertNextPoint(x, y, z) line = fname.readline() pointSource.SetExecuteMethod(readPoints) surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper() map.SetInputConnection(reverse.GetOutputPort()) map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(0.4) surfaceActor.GetProperty().SetSpecularPower(50) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(1, 0, 0) ren.GetActiveCamera().SetViewUp(0, 0, 1) ren.ResetCamera() ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Elevation(30) ren.GetActiveCamera().Dolly(1.2) ren.ResetCameraClippingRange() iren.Initialize() renWin.Render() iren.Start()
def testReconstructSurface(self): # Read some points. Use a programmable filter to read them. # pointSource = vtk.vtkProgrammableSource() def readPoints(): fp = open(VTK_DATA_ROOT + "/Data/cactus.3337.pts", "r") points = vtk.vtkPoints() while True: line = fp.readline().split() if len(line) == 0: break if line[0] == "p": points.InsertNextPoint(float(line[1]), float(line[2]), float(line[3])) pointSource.GetPolyDataOutput().SetPoints(points) pointSource.SetExecuteMethod(readPoints) # Construct the surface and create isosurface # surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputConnection(pointSource.GetOutputPort()) cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() map = vtk.vtkPolyDataMapper() map.SetInputConnection(reverse.GetOutputPort()) map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(.4) surfaceActor.GetProperty().SetSpecularPower(50) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # Add the actors to the renderer, set the background and size # ren.AddActor(surfaceActor) ren.SetBackground(1, 1, 1) renWin.SetSize(300, 300) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(1, 0, 0) ren.GetActiveCamera().SetViewUp(0, 0, 1) ren.ResetCamera() ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Elevation(30) ren.GetActiveCamera().Dolly(1.2) ren.ResetCameraClippingRange() # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "reconstructSurface.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()