def visQuadFunc(): """ vtk sample scene with iso contours """ # VTK supports implicit functions of the form f(x,y,z)=constant. These # functions can represent things spheres, cones, etc. Here we use a # general form for a quadric to create an elliptical data field. quadric = vtk.vtkQuadric() quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0) # vtkSampleFunction samples an implicit function over the x-y-z range # specified (here it defaults to -1,1 in the x,y,z directions). sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(30, 30, 30) sample.SetImplicitFunction(quadric) # Create five surfaces F(x,y,z) = constant between range specified. The # GenerateValues() method creates n isocontour values between the range # specified. contours = vtk.vtkContourFilter() contours.SetInputConnection(sample.GetOutputPort()) contours.GenerateValues(8, 0.0, 1.2) contMapper = vtk.vtkPolyDataMapper() contMapper.SetInputConnection(contours.GetOutputPort()) contMapper.SetScalarRange(0.0, 1.2) contActor = vtk.vtkActor() contActor.SetMapper(contMapper) # We'll put a simple outline around the data. outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(1, 0.5, 0) # extract data from the volume extract = vtk.vtkExtractVOI() extract.SetInputConnection(sample.GetOutputPort()) extract.SetVOI(0, 29, 0, 29, 15, 15) extract.SetSampleRate(1, 2, 3) contours2 = vtk.vtkContourFilter() contours2.SetInputConnection(extract.GetOutputPort()) contours2.GenerateValues(8, 0.0, 1.2) contMapper2 = vtk.vtkPolyDataMapper() contMapper2.SetInputConnection(contours2.GetOutputPort()) contMapper2.SetScalarRange(0.0, 1.2) contActor2 = vtk.vtkActor() contActor2.SetMapper(contMapper2) return contActor, contActor2, outlineActor, contours, contours2
def get_isosurface(self, iso_value=500): if not self.flag_read: sys.stderr.write('No Image Loaded!\n') return contour = vtk.vtkContourFilter() normals = vtk.vtkPolyDataNormals() stripper = vtk.vtkStripper() mapper = vtk.vtkPolyDataMapper() contour.SetInputData(self.reader) contour.SetValue(0, iso_value) normals.SetInputConnection(contour.GetOutputPort()) normals.SetFeatureAngle(60.0) normals.ReleaseDataFlagOn() stripper.SetInputConnection(normals.GetOutputPort()) stripper.ReleaseDataFlagOn() mapper.SetInputConnection(stripper.GetOutputPort()) mapper.SetScalarVisibility(False) actor = vtk.vtkActor() actor.SetMapper(mapper) # Default colour, should be changed. actor.GetProperty().SetDiffuseColor( [247.0 / 255.0, 150.0 / 255.0, 155.0 / 255.0]) # Look like red actor.GetProperty().SetSpecular(0.3) actor.GetProperty().SetSpecularPower(20) return actor
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 __init__ (self, mod_m): debug ("In CustomGridPlane::__init__ ()") Common.state.busy () Base.Objects.Module.__init__ (self, mod_m) self.act = None out = self.mod_m.GetOutput () if out.IsA('vtkStructuredGrid'): self.plane = vtk.vtkStructuredGridGeometryFilter () elif out.IsA ('vtkStructuredPoints') or out.IsA('vtkImageData'): if hasattr (vtk, 'vtkImageDataGeometryFilter'): self.plane = vtk.vtkImageDataGeometryFilter () else: self.plane = vtk.vtkStructuredPointsGeometryFilter () elif out.IsA ('vtkRectilinearGrid'): self.plane = vtk.vtkRectilinearGridGeometryFilter () else: msg = "This module does not support the %s dataset."%(out.GetClassName()) raise Base.Objects.ModuleException, msg self.cont_fil = vtk.vtkContourFilter () self.mapper = self.map = vtk.vtkPolyDataMapper () self.actor = self.act = vtk.vtkActor () self._initialize () self._gui_init () self.renwin.Render () Common.state.idle ()
def GetXandt(filelist): time = [] X_ns = [] X_fs = [] for files in filelist: data = vtktools.vtu(files) time.append(data.GetScalarField("Time")[0]) # Get X data.ugrid.GetPointData().SetActiveScalars('Temperature') data = data.ugrid contour = vtk.vtkContourFilter() if vtk.vtkVersion.GetVTKMajorVersion() <= 5: contour.SetInput(data) else: contour.SetInputData(data) contour.SetValue(0, 0.0) contour.Update() polydata = contour.GetOutput() bounding_box = polydata.GetBounds() X_ns.append(bounding_box[1]) X_fs.append(bounding_box[0]) return time, X_ns, X_fs
def BuildPolyBallSurface(self): #Build a surface for displaying the polyball if self.PolyBall == None: return #Sample the polyball sampler = vtk.vtkSampleFunction() sampler.SetImplicitFunction(self.PolyBall) #Set the bounds to be slightly larger than those of the mesh meshBounds = self.Mesh.GetBounds() meshCenter = self.Mesh.GetCenter() polyBallBounds = [0, 0, 0, 0, 0, 0] for i in range(0,3): length = 1.2*(meshBounds[2*i+1] - meshCenter[i]) polyBallBounds[2*i] = meshCenter[i] - length polyBallBounds[2*i+1] = meshCenter[i] + length sampler.SetModelBounds(polyBallBounds) sampler.SetSampleDimensions(self.PolyBallResolution) sampler.ComputeNormalsOff() sampler.Update() #Extract the isosurface at 0 contour = vtk.vtkContourFilter() contour.SetInput(sampler.GetOutput()) contour.SetValue(0,0.) contour.Update() #Set the new model as the mapper input self.PolyBallActor.GetMapper().SetInput(contour.GetOutput())
def __init__(self,data_reader,origin,normal,camera_normal): self.axial=self.get_matrix(data_reader,origin,normal,camera_normal) # Extract a slice in the desired orientation self.reslice = vtk.vtkImageReslice() self.reslice.SetInput(data_reader.get_data_set()) self.reslice.SetOutputDimensionality(2) self.reslice.SetResliceAxes(self.axial) self.reslice.SetInterpolationModeToLinear() self.contour=vtk.vtkContourFilter() self.contour.SetInputConnection(self.reslice.GetOutputPort()) self.contour.GenerateValues(25, data_reader.get_scalar_range()) self.contour.ComputeScalarsOn() self.contour.ComputeGradientsOn() self.cutmapper=vtk.vtkPolyDataMapper() self.cutmapper.SetInputConnection(self.contour.GetOutputPort()) self.actor=vtk.vtkActor() self.actor.SetMapper(self.cutmapper) self.actor.PokeMatrix(self.axial) c="c" if origin[0]==c or origin[1]==c or origin[2]==c: origin=self.center origin=(float(origin[0]),float(origin[1]),float(origin[2])) self.actor.SetOrigin(origin)
def test_method_signature(self): """Check if VTK method signatures are parsed correctly.""" p = self.p # Simple tests. o = vtk.vtkProperty() self.assertEqual([(["string"], None)], p.get_method_signature(o.GetClassName)) if hasattr(vtk, "vtkArrayCoordinates"): self.assertEqual( [ ([("float", "float", "float")], None), ([None], (["float", "float", "float"],)), ([None], ("float", "float", "float")), ], p.get_method_signature(o.GetColor), ) else: self.assertEqual( [([("float", "float", "float")], None), ([None], (("float", "float", "float"),))], p.get_method_signature(o.GetColor), ) if hasattr(vtk, "vtkArrayCoordinates"): self.assertEqual( [([None], ("float", "float", "float")), ([None], (["float", "float", "float"],))], p.get_method_signature(o.SetColor), ) else: self.assertEqual( [([None], ("float", "float", "float")), ([None], (("float", "float", "float"),))], p.get_method_signature(o.SetColor), ) # Get VTK version to handle changed APIs. vtk_ver = vtk.vtkVersion().GetVTKVersion() # Test vtkObjects args. o = vtk.vtkContourFilter() sig = p.get_method_signature(o.SetInput) if len(sig) == 1: self.assertEqual([([None], ["vtkDataSet"])], sig) elif vtk_ver[:3] in ["4.2", "4.4"]: self.assertEqual( [ ([None], ["vtkDataObject"]), ([None], ("int", "vtkDataObject")), ([None], ["vtkDataSet"]), ([None], ("int", "vtkDataSet")), ], sig, ) elif vtk_ver[:2] == "5." or vtk_ver[:3] == "4.5": self.assertEqual([([None], ["vtkDataObject"]), ([None], ("int", "vtkDataObject"))], sig) self.assertEqual([(["vtkPolyData"], None), (["vtkPolyData"], ["int"])], p.get_method_signature(o.GetOutput)) # Test if function arguments work. self.assertEqual([(["int"], ("int", "function"))], p.get_method_signature(o.AddObserver)) # This one's for completeness. self.assertEqual([([None], ["int"])], p.get_method_signature(o.RemoveObserver))
def vtk_contours_actor(filename, count=10, color=False): import vtk # read the source file. reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() scalar_range = output.GetScalarRange() # contours contours = vtk.vtkContourFilter() contours.SetInputConnection(reader.GetOutputPort()) contours.GenerateValues(count, scalar_range) # map the contours to graphical primitives contMapper = vtk.vtkPolyDataMapper() contMapper.SetInput(contours.GetOutput()) contMapper.SetScalarVisibility(color) # colored contours contMapper.SetScalarRange(scalar_range) # create an actor for the contours contActor = vtk.vtkActor() contActor.SetMapper(contMapper) contActor.GetProperty().SetColor(0.2, 0.2, 0.2) contActor.GetProperty().SetLineWidth(1) return contActor
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkContourFilter(), 'Processing.', ('vtkDataSet',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def setUp(self): self.vtk_iso = vtkContourFilter() # self.vtk_iso.SetInput(...) self.vtk_dnorm = vtkPolyDataNormals() self.vtk_subdiv = vtkLinearSubdivisionFilter() self.vtk_dmap = vtkPolyDataMapper()
def create_actors_for_skin_and_bone(reader): actors_list = [] for contour_val, color, opacity in SKIN_BONE_LIST: contour = vtk.vtkContourFilter() contour.SetInput(reader.GetOutput()) contour.SetNumberOfContours(1) contour.SetValue(contour_val[0], contour_val[1]) normals = vtk.vtkPolyDataNormals() normals.SetInput(contour.GetOutput()) normals.SetFeatureAngle(60) normals.ConsistencyOff() normals.SplittingOff() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) actor.GetProperty().SetOpacity(opacity) actor.RotateX(-90) actors_list.append(actor) return actors_list
def render_image(vtk_reader): contour = vtk.vtkContourFilter() contour.SetInput(vtk_reader.GetOutput()) contour.GenerateValues(20,20,200) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(contour.GetOutput()) mapper.ScalarVisibilityOn() mapper.SetScalarRange(0,255) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(.5, .5, .5) renderWindow.SetSize(600, 600) renderWindow.Render() renderWindowInteractor.Start()
def getContour(self,value=0.5,arrName='',largestRegion=False): if arrName == '': arrName = self.waterArray[self.solver] contour=vtk.vtkContourFilter() contour.SetValue(0,value) self.pointData.SetActiveScalars(arrName) #contour.SetInputArrayToProcess(1, 0,0, vtkDataObject::FIELD_ASSOCIATION_POINTS , arrName); #something like this may also work contour.SetInputConnection(self.outputPort) contour.Update() if largestRegion: conn=vtk.vtkConnectivityFilter() conn.SetInputConnection(contour.GetOutputPort()) conn.SetExtractionModeToLargestRegion() conn.Update() connOutput = conn.GetOutput() IDs = [] for iC in range(connOutput.GetNumberOfCells()): #it has to be so complicated, no polylines are given cell = connOutput.GetCell(iC) for i in [0,1]: ID = cell.GetPointId(i) if not ID in IDs: IDs.append(ID) points=[connOutput.GetPoint(i) for i in IDs] else: cOutput = contour.GetOutput() points=[cOutput.GetPoint(i) for i in range(cOutput.GetNumberOfPoints())] if not points: sys.exit('vtkextract.py: No contours found - wrong initialization of water fraction?') points = np.array(points) return points
def test_method_signature(self): """Check if VTK method signatures are parsed correctly.""" p = self.p # Simple tests. o = vtk.vtkProperty() self.assertEqual([(['string'], None)], p.get_method_signature(o.GetClassName)) if hasattr(vtk, 'vtkArrayCoordinates'): self.assertEqual([([('float', 'float', 'float')], None), ([None], (['float', 'float', 'float'],)), ([None], ('float', 'float', 'float'))], p.get_method_signature(o.GetColor)) else: self.assertEqual([([('float', 'float', 'float')], None), ([None], (('float', 'float', 'float'),))], p.get_method_signature(o.GetColor)) if hasattr(vtk, 'vtkArrayCoordinates'): self.assertEqual([([None], ('float', 'float', 'float')), ([None], (['float', 'float', 'float'],))], p.get_method_signature(o.SetColor)) else: self.assertEqual([([None], ('float', 'float', 'float')), ([None], (('float', 'float', 'float'),))], p.get_method_signature(o.SetColor)) # Get VTK version to handle changed APIs. vtk_ver = vtk.vtkVersion().GetVTKVersion() # Test vtkObjects args. o = vtk.vtkContourFilter() sig = p.get_method_signature(o.SetInput) if len(sig) == 1: self.assertEqual([([None], ['vtkDataSet'])], sig) elif vtk_ver[:3] in ['4.2', '4.4']: self.assertEqual([([None], ['vtkDataObject']), ([None], ('int', 'vtkDataObject')), ([None], ['vtkDataSet']), ([None], ('int', 'vtkDataSet')) ], sig) elif vtk_ver[:2] == '5.' or vtk_ver[:3] == '4.5': self.assertEqual([([None], ['vtkDataObject']), ([None], ('int', 'vtkDataObject')), ], sig) self.assertEqual([(['vtkPolyData'], None), (['vtkPolyData'], ['int'])], p.get_method_signature(o.GetOutput)) # Test if function arguments work. self.assertEqual([(['int'], ('int', 'function'))], p.get_method_signature(o.AddObserver)) # This one's for completeness. self.assertEqual([([None], ['int'])], p.get_method_signature(o.RemoveObserver))
def test_contours(self): cell = vtk.vtkUnstructuredGrid() cell.ShallowCopy(self.Cell) np = self.Cell.GetNumberOfPoints() ncomb = pow(2, np) scalar = vtk.vtkDoubleArray() scalar.SetName("scalar") scalar.SetNumberOfTuples(np) cell.GetPointData().SetScalars(scalar) incorrectCases = [] for i in range(1,ncomb-1): c = Combination(np, i) for p in range(np): scalar.SetTuple1(p, c[p]) gradientFilter = vtk.vtkGradientFilter() gradientFilter.SetInputData(cell) gradientFilter.SetInputArrayToProcess(0,0,0,0,'scalar') gradientFilter.SetResultArrayName('grad') gradientFilter.Update() contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(gradientFilter.GetOutputPort()) contourFilter.SetNumberOfContours(1) contourFilter.SetValue(0, 0.5) contourFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection(contourFilter.GetOutputPort()) normalsFilter.SetConsistency(0) normalsFilter.SetFlipNormals(0) normalsFilter.SetSplitting(0) calcFilter = vtk.vtkArrayCalculator() calcFilter.SetInputConnection(normalsFilter.GetOutputPort()) calcFilter.SetAttributeTypeToPointData() calcFilter.AddVectorArrayName('grad') calcFilter.AddVectorArrayName('Normals') calcFilter.SetResultArrayName('dir') calcFilter.SetFunction('grad.Normals') calcFilter.Update() out = vtk.vtkUnstructuredGrid() out.ShallowCopy(calcFilter.GetOutput()) numPts = out.GetNumberOfPoints() if numPts > 0: dirArray = out.GetPointData().GetArray('dir') for p in range(numPts): if(dirArray.GetTuple1(p) > 0.0): # all normals are reversed incorrectCases.append(i) break self.assertEquals(','.join([str(i) for i in incorrectCases]), '')
def test_to_tvtk_returns_tvtk_object(self): # Given v = vtk.vtkContourFilter() # When x = tvtk.to_tvtk(v) # Then self.assertEqual(x.class_name, 'vtkContourFilter') self.assertTrue(isinstance(x, tvtk_base.TVTKBase)) self.assertTrue(isinstance(x, tvtk.ContourFilter)) self.assertTrue(v is x._vtk_obj)
def multi_con_h2(filename): # Creating contour for h2 fileld data = vtk.vtkXMLImageDataReader() data.SetFileName(filename)#"/Users/y1275963/Documents/homework/multifield.0060.vti") data.Update() #Getting highest value [low,high] = data.GetOutput().GetPointData().GetArray("H2").GetRange() data_h2 = vtk.vtkAssignAttribute() data_h2.SetInputConnection(data.GetOutputPort()) data_h2.Assign('H2','SCALARS','POINT_DATA') # Create a filter to extract an isosurface from # the dataset. Connect the input of this # filter to the output of the reader. Set the # value for the (one) isosurface that we want # to extract, and tell the filter to compute # normal vectors for each triangle on the # output isosurface. iso = vtk.vtkContourFilter() iso.SetInputConnection(data_h2.GetOutputPort()) iso.ComputeNormalsOn() iso.SetNumberOfContours(10) for i in range(10): iso.SetValue(i, (1.0-0.1*i)*high) #Chnge here to change the isovalue # Create a mapper to traverse the polydata and # generate graphics commands for drawing the # polygons onto the output device. mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(iso.GetOutputPort()) mapper.ScalarVisibilityOff() # Output primitives (i.e. the triangles making # up the isosurface) are managed as an actor; # we specify that all outputs are coloured # red. actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0, 0, 1) actor.GetProperty().SetOpacity(0.3) # Create a renderer which will output the # graphics commands onto a drawing surface within # a window. By default the renderer will fill # all of the window. We set the background # colour of the window to white. return actor
def __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.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create cylinder cylinder = vtk.vtkCylinder() cylinder.SetCenter(0, 0, 0) cylinder.SetRadius(1.0) # Create plane plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, -1, 0) # Cut the cylinder cuted_cylinder = vtk.vtkImplicitBoolean() cuted_cylinder.SetOperationTypeToIntersection() #cuted_cylinder.SetOperationTypeToUnion() cuted_cylinder.AddFunction(cylinder) cuted_cylinder.AddFunction(plane) # Sample sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(cuted_cylinder) sample.SetModelBounds(-1.5 , 1.5 , -1.5 , 1.5 , -1.5 , 1.5) sample.SetSampleDimensions(60, 60, 60) sample.SetComputeNormals(0) # surface = vtk.vtkContourFilter() #surface.SetInput(sample.GetOutput()) surface.SetInputConnection(sample.GetOutputPort()) # Create a mapper mapper = vtk.vtkPolyDataMapper() #mapper.SetInput(surface.GetOutput()) mapper.SetInputConnection(surface.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def get_interface_depth(file): vtu=vtktools.vtu(file) data = vtu.ugrid data.GetPointData().SetActiveScalars("Dense::MaterialVolumeFraction") contour = vtk.vtkContourFilter () contour.SetInput(data) contour.SetValue(0, 0.5) contour.Update() polydata = contour.GetOutput() bounding_box = polydata.GetBounds() interface_depth = bounding_box[2] return interface_depth
def TestDataType(dataType, reader, writer, ext, numTris, useSubdir=False): s = GetSource(dataType) filename = VTK_TEMP_DIR + "/%s.p%s" % (dataType, ext) writer.SetInputConnection(s.GetOutputPort()) npieces = 16 writer.SetNumberOfPieces(npieces) pperrank = npieces // nranks start = pperrank * rank end = start + pperrank - 1 writer.SetStartPiece(start) writer.SetEndPiece(end) writer.SetFileName(filename) if useSubdir: writer.SetUseSubdirectory(True) #writer.SetDataModeToAscii() writer.Write() if contr: contr.Barrier() reader.SetFileName(filename) cf = vtk.vtkContourFilter() cf.SetValue(0, 130) cf.SetComputeNormals(0) cf.SetComputeGradients(0) cf.SetInputConnection(reader.GetOutputPort()) cf.UpdateInformation() cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_NUMBER_OF_PIECES(), nranks) cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_PIECE_NUMBER(), rank) cf.Update() ntris = cf.GetOutput().GetNumberOfCells() da = vtk.vtkIntArray() da.InsertNextValue(ntris) da2 = vtk.vtkIntArray() da2.SetNumberOfTuples(1) contr.AllReduce(da, da2, vtk.vtkCommunicator.SUM_OP) if rank == 0: print(da2.GetValue(0)) import os os.remove(filename) for i in range(npieces): if not useSubdir: os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext)) else: os.remove(VTK_TEMP_DIR + "/%s/%s_%d.%s" %(dataType, dataType, i, ext)) assert da2.GetValue(0) == numTris
def createGeometry(reader, threshold = 0): isoSurface = vtk.vtkContourFilter() isoSurface.SetInputConnection(reader.GetOutputPort()) isoSurface.SetValue(0, threshold) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(isoSurface.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def extract_contour(segmentation_path, contour_path, rgb_data=False): # build pipeline sys.stdout.write('Updating segmentation...'); sys.stdout.flush() segmentation = vtk.vtkMetaImageReader() segmentation.SetFileName(segmentation_path) segmentation.Update() print 'done.' if rgb_data: calculator_function = "mag(MetaImage)" else: calculator_function = "MetaImage * 255" sys.stdout.write('Updating calculator...'); sys.stdout.flush() calculator = vtk.vtkArrayCalculator() calculator.SetInputConnection(segmentation.GetOutputPort()) # Working on point data calculator.SetAttributeModeToUsePointData() calculator.AddScalarArrayName("MetaImage") # magnitude of input calculator.SetFunction("mag(MetaImage)") # The output array will be called resArray calculator.SetResultArrayName("magnitude") # Use AssignAttribute to make resArray the active scalar field aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calculator.GetOutputPort()) aa.Assign("magnitude", "SCALARS", "POINT_DATA") aa.Update() print 'done.' # intensity is either (3 * 255^2)^0.5, or 1 if rgb_data: magnitude = 420.0 else: magnitude = 127 sys.stdout.write('Updating contour...'); sys.stdout.flush() contour = vtk.vtkContourFilter() contour.SetInputConnection(calculator.GetOutputPort()) contour.SetValue(0, magnitude) contour.Update() print 'done.' # write out data file in given format sys.stdout.write('Updating writer...'); sys.stdout.flush() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(contour_path) writer.SetCompressorTypeToZLib() writer.SetInputConnection(contour.GetOutputPort()) writer.Write() print 'done.'
def testAll(self): reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) # write isosurface to file #vtkSynchronizedTemplates3D stemp stemp = vtk.vtkContourFilter() stemp.SetInputConnection(reader.GetOutputPort()) stemp.SetValue(0,1150) stemp.GenerateTrianglesOff() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),38380) stemp.GenerateTrianglesOn() stemp.Update() self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfPoints(),39315) self.failUnlessEqual(stemp.GetOutputDataObject(0).GetNumberOfCells(),78268) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stemp.GetOutputPort()) mapper.ScalarVisibilityOff() head = vtk.vtkActor() head.SetMapper(mapper) head.GetProperty().SetColor(1,0.7,0.6) # Create the RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddActor(head) ren1.SetBackground(1,1,1) renWin.SetSize(400,400) ren1.SetBackground(0.5,0.5,0.6) ren1.GetActiveCamera().SetPosition(99.8847,537.926,15) ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15) ren1.GetActiveCamera().SetViewAngle(20) ren1.GetActiveCamera().SetViewUp(0,0,-1) ren1.ResetCameraClippingRange() # render the image # renWin.Render()
def _update_3d_renderer(self, input_stream): """Calculate the contour based on the input data """ self._config.iso_value = 128 contourFilter = vtk.vtkContourFilter() contourFilter.SetInput(input_stream) contourFilter.Update() data = contourFilter.GetOutput() self.contour_mapper.SetInput(data) self.contour_mapper.Update() self._calculate_selection() self.renderer_3d.ResetCamera() return data
def iso_surfaces(self): min_s, max_s = self.b0.GetScalarRange() contours = vtk.vtkContourFilter() contours.SetInputData(self.b0) contours.GenerateValues(5, (max_s/5, max_s)) print (max_s) contours_mapper = vtk.vtkPolyDataMapper() contours_mapper.SetInputConnection(contours.GetOutputPort()) contours_mapper.ScalarVisibilityOff() self.contours_actor = vtk.vtkActor() self.contours_actor.SetMapper(contours_mapper) self.renderer.AddActor(self.contours_actor) self.contours =contours self.app.set_min_val(max_s / 5)
def contoursFilterOnCutPlane(self, convert, cut): """Create contours on a slice from the 3D computational domain.""" # create the contour filter contours = vtk.vtkContourFilter() # set the plane as input contours.SetInputConnection(cut.GetOutputPort()) # select the variable contours.SetInputArrayToProcess(0,0,0,0,self.opt.variable) # define the iso values self.isoValuesByArray(convert.GetOutput(), contours) contours.Update() return contours
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 testContourQuadraticTetra(self): # Create a reader to load the data (quadratic tetrahedra) reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(VTK_DATA_ROOT + "/Data/quadTetEdgeTest.vtk") tetContours = vtk.vtkContourFilter() tetContours.SetInputConnection(reader.GetOutputPort()) tetContours.SetValue(0, 0.5) aTetContourMapper = vtk.vtkDataSetMapper() aTetContourMapper.SetInputConnection(tetContours.GetOutputPort()) aTetContourMapper.ScalarVisibilityOff() aTetMapper = vtk.vtkDataSetMapper() aTetMapper.SetInputConnection(reader.GetOutputPort()) aTetMapper.ScalarVisibilityOff() aTetActor = vtk.vtkActor() aTetActor.SetMapper(aTetMapper) aTetActor.GetProperty().SetRepresentationToWireframe() aTetActor.GetProperty().SetAmbient(1.0) aTetContourActor = vtk.vtkActor() aTetContourActor.SetMapper(aTetContourMapper) aTetContourActor.GetProperty().SetAmbient(1.0) # Create the rendering related stuff. # Since some of our actors are a single vertex, we need to remove all # cullers so the single vertex actors will render ren1 = vtk.vtkRenderer() ren1.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.SetBackground(.1, .2, .3) renWin.SetSize(400, 250) # specify properties ren1.AddActor(aTetActor) ren1.AddActor(aTetContourActor) ren1.ResetCamera() ren1.GetActiveCamera().Dolly(1.5) ren1.ResetCameraClippingRange() renWin.Render() img_file = "contourQuadraticTetra.png" vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def __init__ (self, mod_m): debug ("In IsoSurface::__init__ ()") Common.state.busy () Base.Objects.Module.__init__ (self, mod_m) self.cont_fil = vtk.vtkContourFilter () self.norm = vtk.vtkPolyDataNormals () self.mapper = self.map = vtk.vtkPolyDataMapper () self.actor = self.act = vtk.vtkActor () self.data_out = self.mod_m.GetOutput () self._initialize () self._gui_init () if not self.mod_m.get_scalar_data_name (): msg = "Warning: No scalar data present to contour!" Common.print_err (msg) self.renwin.Render () Common.state.idle ()
def testFinancialField(self): """ Demonstrate the use and manipulation of fields and use of vtkProgrammableDataObjectSource. This creates fields the hard way (as compared to reading a vtk field file), but shows you how to interface to your own raw data. The image should be the same as financialField.tcl """ xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Parse an ascii file and manually create a field. Then construct a # dataset from the field. dos = vtk.vtkProgrammableDataObjectSource() def parseFile(): f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r") line = f.readline().split() # From the size calculate the number of lines. numPts = int(line[1]) numLines = (numPts - 1) / 8 + 1 # create the data object field = vtk.vtkFieldData() field.AllocateArrays(4) # read TIME_LATE - dependent variable while True: line = f.readline().split() if len(line) > 0: break timeLate = vtk.vtkFloatArray() timeLate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: timeLate.InsertNextValue(float(j)) field.AddArray(timeLate) # MONTHLY_PAYMENT - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyPayment = vtk.vtkFloatArray() monthlyPayment.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyPayment.InsertNextValue(float(j)) field.AddArray(monthlyPayment) # UNPAID_PRINCIPLE - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # LOAN_AMOUNT - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # INTEREST_RATE - independent variable while True: line = f.readline().split() if len(line) > 0: break interestRate = vtk.vtkFloatArray() interestRate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: interestRate.InsertNextValue(float(j)) field.AddArray(interestRate) # MONTHLY_INCOME - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyIncome = vtk.vtkFloatArray() monthlyIncome.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyIncome.InsertNextValue(float(j)) field.AddArray(monthlyIncome) dos.GetOutput().SetFieldData(field) dos.SetExecuteMethod(parseFile) # Create the dataset do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(dos.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() rf = vtk.vtkRearrangeFields() rf.SetInputConnection(do2ds.GetOutputPort()) rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveAllOperations() rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.Update() max = rf.GetOutput().GetPointData().GetArray(scalar).GetRange(0)[1] calc = vtk.vtkArrayCalculator() calc.SetInputConnection(rf.GetOutputPort()) calc.SetAttributeTypeToPointData() calc.SetFunction("s / %f" % max) calc.AddScalarVariable("s", scalar, 0) calc.SetResultArrayName("resArray") aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calc.GetOutputPort()) aa.Assign("resArray", "SCALARS", "POINT_DATA") aa.Update() rf2 = vtk.vtkRearrangeFields() rf2.SetInputConnection(aa.GetOutputPort()) rf2.AddOperation("COPY", "SCALARS", "POINT_DATA", "DATA_OBJECT") # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(rf2.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(aa.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk(-, Field.Data") renWin.SetSize(300, 300) # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "financialField3.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
cell = grid.GetCell(i) ugrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) #There are too many points, let's filter the points subset = vtk.vtkMaskPoints() subset.SetOnRatio(50) subset.RandomModeOn() subset.SetInputData(ugrid) #Make a vtkPolyData with a vertex on each point. pointsGlyph = vtk.vtkVertexGlyphFilter() pointsGlyph.SetInputConnection(subset.GetOutputPort()) #pointsGlyph.SetInputData(ugrid) pointsGlyph.Update() #----------------------------CHALLENGE4---------------------------# scalarRange = ugrid.GetPointData().GetScalars().GetRange() isoFilter = vtk.vtkContourFilter() isoFilter.SetInputData(ugrid) isoFilter.GenerateValues(10, scalarRange) #------------------------------------MAPPERS------------------------------------# #----------------------------CHALLENGE1---------------------------# rectGridOutlineMapper = vtk.vtkPolyDataMapper() rectGridOutlineMapper.SetInputConnection(rectGridOutline.GetOutputPort()) rectGridGeomMapper = vtk.vtkPolyDataMapper() rectGridGeomMapper.SetInputConnection(rectGridGeom.GetOutputPort()) #----------------------------CHALLENGE3---------------------------# pointsMapper = vtk.vtkPolyDataMapper()
aVoxel.GetPointIds().SetId(0, 0) aVoxel.GetPointIds().SetId(1, 1) aVoxel.GetPointIds().SetId(2, 2) aVoxel.GetPointIds().SetId(3, 3) aVoxel.GetPointIds().SetId(4, 4) aVoxel.GetPointIds().SetId(5, 5) aVoxel.GetPointIds().SetId(6, 6) aVoxel.GetPointIds().SetId(7, 7) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelGrid.GetPointData().SetScalars(voxelScalars) voxelContours = vtk.vtkContourFilter() voxelContours.SetInputData(aVoxelGrid) voxelContours.SetValue(0, .5) aVoxelContourMapper = vtk.vtkDataSetMapper() aVoxelContourMapper.SetInputConnection(voxelContours.GetOutputPort()) aVoxelContourMapper.ScalarVisibilityOff() aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelMapper.ScalarVisibilityOff() aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper) aVoxelActor.GetProperty().SetRepresentationToWireframe()
def show(actor, w = 1000, h = 500, zoom = 1.0, isolines = False, cells = True, edges = False, camera_position = None, orientation = [0.0, 0.0, 0.0]): renderer, rendererWindow = make_renderer_and_window(w, h) camera = renderer.GetActiveCamera() if cells: actor.SetVisibility(1) actor.GetProperty().SetRepresentationToSurface(); if edges: actor.GetProperty().EdgeVisibilityOn(); else: actor.GetProperty().EdgeVisibilityOff(); elif edges: actor.SetVisibility(1) actor.GetProperty().SetRepresentationToWireframe(); else: actor.SetVisibility(0) renderer.AddActor(actor) # create axes bounds = actor.GetMapper().GetInput().GetBounds() axes = vtkCubeAxesActor() axes.SetBounds(bounds) axes.SetCamera(camera) axes.XAxisLabelVisibilityOn() axes.YAxisLabelVisibilityOn() axes.ZAxisLabelVisibilityOn() axes.DrawXGridlinesOff() axes.DrawYGridlinesOff() axes.DrawZGridlinesOff() axes.GetLabelTextProperty(0).SetColor(0.1, 0.1, 0.1) axes.GetXAxesGridlinesProperty().SetColor(0.1, 0.1, 0.1) axes.GetYAxesGridlinesProperty().SetColor(0.1, 0.1, 0.1) axes.GetZAxesGridlinesProperty().SetColor(0.1, 0.1, 0.1) axes.GetXAxesLinesProperty().SetColor(0.1, 0.1, 0.1) axes.GetYAxesLinesProperty().SetColor(0.1, 0.1, 0.1) axes.GetZAxesLinesProperty().SetColor(0.1, 0.1, 0.1) renderer.AddActor(axes) if isolines: # create isolines iso = vtkContourFilter() iso.SetInput(actor.GetMapper().GetInput()) iso.SetNumberOfContours(10) r = actor.GetMapper().GetInput().GetPointData().GetScalars().GetRange() start = r[0] delta = 0.1 * (r[1] - start) for i in range(10): iso.SetValue(i, start + delta * i) iso_mapper = vtkPolyDataMapper() iso_mapper.SetInputConnection(iso.GetOutputPort()) iso_actor = vtkActor() iso_actor.SetMapper(iso_mapper) renderer.AddActor(iso_actor) scale_bar = vtkScalarBarActor() scale_bar.SetLookupTable(iso_mapper.GetLookupTable()) scale_bar.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport() scale_bar.GetPositionCoordinate().SetValue(0.1,0.01) scale_bar.SetOrientationToHorizontal() scale_bar.SetWidth(0.8) scale_bar.SetHeight(0.17) renderer.AddActor2D(scale_bar) # 1. The FocalPoint - this controls the point the camera "looks" at. # 2. The Position - this controls _where_ the camera is in space. # 3. The ViewUp - this controls what the "up" direction is (i.e., the direction that goes bottom-to-top in the view). renderer.ResetCamera() camera.Zoom(zoom) a = camera.GetOrientation() camera.Roll(-a[2]) camera.Elevation(-a[0]) camera.Azimuth(a[1]) camera.Elevation(orientation[0]) camera.Azimuth(-orientation[1]) camera.Roll(orientation[2]) camera.ParallelProjectionOff() if camera_position: old_position = camera.GetPosition() camera.SetPosition(camera_position[0], camera_position[1], old_position[2]) camera.SetFocalPoint(camera_position[0], camera_position[1], camera_position[2]) # render rendererWindow.Render() windowToImageFilter = vtkWindowToImageFilter() windowToImageFilter.SetInput(rendererWindow) windowToImageFilter.Update() writer = vtkPNGWriter() writer.SetWriteToMemory(1) writer.SetInputConnection(windowToImageFilter.GetOutputPort()) writer.Write() data = str(buffer(writer.GetResult())) renderer.RemoveActor(actor) renderer.RemoveActor(axes) if isolines: renderer.RemoveActor(iso_actor) from IPython.display import Image return Image(data)
boolean.SetOperationTypeToDifference() # boolean.SetOperationTypeToUnion() # boolean.SetOperationTypeToIntersection() boolean.AddFunction(box) boolean.AddFunction(sphere) # The sample function generates a distance function from the implicit # function. This is then contoured to get a polygonal surface. sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(boolean) sample.SetModelBounds(-1, 2, -1, 1, -1, 1) sample.SetSampleDimensions(40, 40, 40) sample.ComputeNormalsOff() # contour surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0, 0.0) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetEdgeColor(.2, .2, .5) # A renderer and render window renderer = vtk.vtkRenderer() renderer.SetBackground(1, 1, 1)
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] zaxis, taxis = self.getZandT() # Streamline color if (not self._gm.coloredbyvector): ln_tmp = self._gm.linetype if ln_tmp is None: ln_tmp = "default" try: ln_tmp = vcs.getline(ln_tmp) lwidth = ln_tmp.width[0] # noqa lcolor = ln_tmp.color[0] lstyle = ln_tmp.type[0] # noqa except Exception: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor # The unscaled continent bounds were fine in the presence of axis # conversion, so save them here continentBounds = vcs2vtk.computeDrawAreaBounds( self._vtkDataSetBoundsNoMask, self._context_flipX, self._context_flipY) # Only scaling the data in the presence of axis conversion changes # the seed points in any other cases, and thus results in plots # different from the baselines but still fundamentally sound, it # seems. Always scaling the data results in no differences in the # plots between Context2D and the old baselines. # Transform the input data T = vtk.vtkTransform() T.Scale(self._context_xScale, self._context_yScale, 1.) self._vtkDataSetFittedToViewport = vcs2vtk.applyTransformationToDataset( T, self._vtkDataSetFittedToViewport) self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds( ) polydata = self._vtkDataSetFittedToViewport plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) # view and interactive area view = self._context().contextView area = vtk.vtkInteractiveArea() view.GetScene().AddItem(area) drawAreaBounds = vcs2vtk.computeDrawAreaBounds( self._vtkDataSetBoundsNoMask, self._context_flipX, self._context_flipY) [renWinWidth, renWinHeight] = self._context().renWin.GetSize() geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)), int(round(vp[2] * renWinHeight)), int(round((vp[1] - vp[0]) * renWinWidth)), int(round((vp[3] - vp[2]) * renWinHeight))) vcs2vtk.configureContextArea(area, drawAreaBounds, geom) dataLength = polydata.GetLength() if (not self._gm.evenlyspaced): # generate random seeds in a circle centered in the center of # the bounding box for the data. # by default vtkPointSource uses a global random source in vtkMath which is # seeded only once. It makes more sense to seed a random sequence each time you draw # the streamline plot. pointSequence = vtk.vtkMinimalStandardRandomSequence() pointSequence.SetSeedOnly(1177) # replicate the seed from vtkMath seed = vtk.vtkPointSource() seed.SetNumberOfPoints(self._gm.numberofseeds) seed.SetCenter(polydata.GetCenter()) seed.SetRadius(dataLength / 2.0) seed.SetRandomSequence(pointSequence) seed.Update() seedData = seed.GetOutput() # project all points to Z = 0 plane points = seedData.GetPoints() for i in range(0, points.GetNumberOfPoints()): p = list(points.GetPoint(i)) p[2] = 0 points.SetPoint(i, p) if (self._gm.integratortype == 0): integrator = vtk.vtkRungeKutta2() elif (self._gm.integratortype == 1): integrator = vtk.vtkRungeKutta4() else: if (self._gm.evenlyspaced): warnings.warn( "You cannot use RungeKutta45 for evenly spaced streamlines." "Using RungeKutta4 instead") integrator = vtk.vtkRungeKutta4() else: integrator = vtk.vtkRungeKutta45() if (self._gm.evenlyspaced): streamer = vtk.vtkEvenlySpacedStreamlines2D() startseed = self._gm.startseed \ if self._gm.startseed else polydata.GetCenter() streamer.SetStartPosition(startseed) streamer.SetSeparatingDistance(self._gm.separatingdistance) streamer.SetSeparatingDistanceRatio( self._gm.separatingdistanceratio) streamer.SetClosedLoopMaximumDistance( self._gm.closedloopmaximumdistance) else: # integrate streamlines on normalized vector so that # IntegrationTime stores distance streamer = vtk.vtkStreamTracer() streamer.SetSourceData(seedData) streamer.SetIntegrationDirection(self._gm.integrationdirection) streamer.SetMinimumIntegrationStep(self._gm.minimumsteplength) streamer.SetMaximumIntegrationStep(self._gm.maximumsteplength) streamer.SetMaximumError(self._gm.maximumerror) streamer.SetMaximumPropagation(dataLength * self._gm.maximumstreamlinelength) streamer.SetInputData(polydata) streamer.SetInputArrayToProcess(0, 0, 0, 0, "vector") streamer.SetIntegrationStepUnit(self._gm.integrationstepunit) streamer.SetInitialIntegrationStep(self._gm.initialsteplength) streamer.SetMaximumNumberOfSteps(self._gm.maximumsteps) streamer.SetTerminalSpeed(self._gm.terminalspeed) streamer.SetIntegrator(integrator) # add arc_length to streamlines arcLengthFilter = vtk.vtkAppendArcLength() arcLengthFilter.SetInputConnection(streamer.GetOutputPort()) arcLengthFilter.Update() streamlines = arcLengthFilter.GetOutput() # glyph seed points contour = vtk.vtkContourFilter() contour.SetInputConnection(arcLengthFilter.GetOutputPort()) contour.SetValue(0, 0.001) if (streamlines.GetNumberOfPoints()): r = streamlines.GetPointData().GetArray("arc_length").GetRange() numberofglyphsoneside = self._gm.numberofglyphs // 2 for i in range(1, numberofglyphsoneside): contour.SetValue(i, r[1] / numberofglyphsoneside * i) else: warnings.warn( "No streamlines created. " "The 'startseed' parameter needs to be inside the domain and " "not over masked data.") contour.SetInputArrayToProcess(0, 0, 0, 0, "arc_length") # arrow glyph source glyph2DSource = vtk.vtkGlyphSource2D() glyph2DSource.SetGlyphTypeToTriangle() glyph2DSource.SetRotationAngle(-90) glyph2DSource.SetFilled(self._gm.filledglyph) # arrow glyph adjustment transform = vtk.vtkTransform() transform.Scale(1., self._gm.glyphbasefactor, 1.) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputConnection(glyph2DSource.GetOutputPort()) transformFilter.SetTransform(transform) transformFilter.Update() glyphLength = transformFilter.GetOutput().GetLength() # drawing the glyphs at the seed points glyph = vtk.vtkGlyph2D() glyph.SetInputConnection(contour.GetOutputPort()) glyph.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyph.SetSourceData(transformFilter.GetOutput()) glyph.SetScaleModeToDataScalingOff() glyph.SetScaleFactor(dataLength * self._gm.glyphscalefactor / glyphLength) glyph.SetColorModeToColorByVector() glyphMapper = vtk.vtkPolyDataMapper() glyphActor = vtk.vtkActor() mapper = vtk.vtkPolyDataMapper() act = vtk.vtkActor() glyph.Update() glyphDataset = glyph.GetOutput() streamer.Update() lineDataset = streamer.GetOutput() deleteLineColors = False deleteGlyphColors = False # color the streamlines and glyphs cmap = self.getColorMap() if (self._gm.coloredbyvector): numLevels = len(self._contourLevels) - 1 while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b, a = self.getColorIndexOrRGBA(cmap, self._contourColors[i]) lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) lut.SetVectorModeToMagnitude() if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._vectorRange[0] else: lmn = self._contourLevels[0][0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._vectorRange[1] else: lmx = self._contourLevels[-1][-1] lut.SetRange(lmn, lmx) mapper.ScalarVisibilityOn() mapper.SetLookupTable(lut) mapper.UseLookupTableScalarRangeOn() mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray("vector") lineAttrs = lineDataset.GetPointData() lineData = lineAttrs.GetArray("vector") if lineData and numLevels: lineColors = lut.MapScalars(lineData, vtk.VTK_COLOR_MODE_DEFAULT, 0) deleteLineColors = True else: print( 'WARNING: streamline pipeline cannot map scalars for "lineData", using solid color' ) numTuples = lineDataset.GetNumberOfPoints() color = [0, 0, 0, 255] lineColors = vcs2vtk.generateSolidColorArray(numTuples, color) glyphMapper.ScalarVisibilityOn() glyphMapper.SetLookupTable(lut) glyphMapper.UseLookupTableScalarRangeOn() glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SelectColorArray("VectorMagnitude") glyphAttrs = glyphDataset.GetPointData() glyphData = glyphAttrs.GetArray("VectorMagnitude") if glyphData and numLevels: glyphColors = lut.MapScalars(glyphData, vtk.VTK_COLOR_MODE_DEFAULT, 0) deleteGlyphColors = True else: print( 'WARNING: streamline pipeline cannot map scalars for "glyphData", using solid color' ) numTuples = glyphDataset.GetNumberOfPoints() color = [0, 0, 0, 255] glyphColors = vcs2vtk.generateSolidColorArray(numTuples, color) else: mapper.ScalarVisibilityOff() glyphMapper.ScalarVisibilityOff() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) glyphActor.GetProperty().SetColor(r / 100., g / 100., b / 100.) fixedColor = [ int((r / 100.) * 255), int((g / 100.) * 255), int((b / 100.) * 255), 255 ] numTuples = lineDataset.GetNumberOfPoints() lineColors = vcs2vtk.generateSolidColorArray(numTuples, fixedColor) numTuples = glyphDataset.GetNumberOfPoints() glyphColors = vcs2vtk.generateSolidColorArray( numTuples, fixedColor) # Add the streamlines lineItem = vtk.vtkPolyDataItem() lineItem.SetPolyData(lineDataset) lineItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA) lineItem.SetMappedColors(lineColors) if deleteLineColors: lineColors.FastDelete() area.GetDrawAreaItem().AddItem(lineItem) # Add the glyphs glyphItem = vtk.vtkPolyDataItem() glyphItem.SetPolyData(glyphDataset) glyphItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA) glyphItem.SetMappedColors(glyphColors) if deleteGlyphColors: glyphColors.FastDelete() area.GetDrawAreaItem().AddItem(glyphItem) plotting_dataset_bounds = self.getPlottingBounds() vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) kwargs = { 'vtk_backend_grid': self._vtkDataSet, 'dataset_bounds': self._vtkDataSetBounds, 'plotting_dataset_bounds': plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, 'vtk_backend_geo': self._vtkGeoTransform, "vtk_backend_draw_area_bounds": continentBounds, "vtk_backend_viewport_scale": [self._context_xScale, self._context_yScale] } if ('ratio_autot_viewport' in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, taxis, zaxis, **kwargs)) if (self._gm.coloredbyvector): self._resultDict.update(self._context().renderColorBar( self._template, self._contourLevels, self._contourColors, None, self.getColorMap())) kwargs['xaxisconvert'] = self._gm.xaxisconvert kwargs['yaxisconvert'] = self._gm.yaxisconvert if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis( -2).isLatitude(): self._context().plotContinents( self._plot_kargs.get("continents", self._useContinents), plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs) self._resultDict["vtk_backend_actors"] = [[ lineItem, plotting_dataset_bounds ]] self._resultDict["vtk_backend_luts"] = [[None, None]]
def main(): fileName = get_program_parameters() colors = vtk.vtkNamedColors() # Create the RenderWindow, Renderer and Interactor. # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create the pipeline. # reader = vtk.vtkMetaImageReader() reader.SetFileName(fileName) reader.Update() extractVOI = vtk.vtkExtractVOI() extractVOI.SetInputConnection(reader.GetOutputPort()) extractVOI.SetVOI(0, 255, 0, 255, 45, 45) iso = vtk.vtkContourFilter() iso.SetInputConnection(extractVOI.GetOutputPort()) iso.GenerateValues(12, 500, 1150) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(colors.GetColor3d("Wheat")) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(extractVOI.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Add the actors to the renderer, set the background and size. # ren1.AddActor(outlineActor) ren1.AddActor(isoActor) ren1.SetBackground(colors.GetColor3d("SlateGray")) ren1.ResetCamera() ren1.GetActiveCamera().Dolly(1.5) ren1.ResetCameraClippingRange() renWin.SetSize(640, 480) renWin.Render() iren.Start()
def normal(mcBone, mcSkin): """ Create the default visualisation of the skin. A sphere is clipping the skin near the articulation and is slightly visible using a low opacity. Args: mcBone: vtkMarchingCubes used to create the bone mcSkin: vtkMarchingCubes used to create the skin Returns: vtkAssembly """ # Create a sphere for clipping sphere = vtk.vtkSphere() sphere.SetCenter(80, 20, 120) sphere.SetRadius(60) theSphere = vtk.vtkImplicitBoolean() theSphere.SetOperationTypeToDifference() theSphere.AddFunction(sphere) # Display the sphere theSphereSample = vtk.vtkSampleFunction() theSphereSample.SetImplicitFunction(theSphere) theSphereSample.SetModelBounds(-1000, 1000, -1000, 1000, -1000, 1000) theSphereSample.SetSampleDimensions(120, 120, 120) theSphereSample.ComputeNormalsOff() theSphereSurface = vtk.vtkContourFilter() theSphereSurface.SetInputConnection(theSphereSample.GetOutputPort()) theSphereSurface.SetValue(0, 0.0) mapperSphere = vtk.vtkPolyDataMapper() mapperSphere.SetInputConnection(theSphereSurface.GetOutputPort()) mapperSphere.ScalarVisibilityOff() actorSphere = vtk.vtkActor() actorSphere.SetMapper(mapperSphere) actorSphere.GetProperty().SetColor(white) actorSphere.GetProperty().SetOpacity(0.1) # Clip skin with a sphere clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(mcSkin.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(1) clipper.Update() # Skin mapper and actor mapperSkin = vtk.vtkDataSetMapper() mapperSkin.SetInputConnection(clipper.GetOutputPort()) mapperSkin.ScalarVisibilityOff() actorSkin = vtk.vtkActor() actorSkin.SetMapper(mapperSkin) actorSkin.GetProperty().SetColor(0.95, 0.64, 0.64) # Bone mapper and actor mapperBone = vtk.vtkDataSetMapper() mapperBone.SetInputConnection(mcBone.GetOutputPort()) mapperBone.ScalarVisibilityOff() actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorBone.GetProperty().SetColor(0.9, 0.9, 0.9) # Group the actors assembly = vtk.vtkAssembly() assembly.AddPart(actorSkin) assembly.AddPart(actorBone) assembly.AddPart(actorSphere) return assembly
pvTemp200 = vtk.vtkMetaImageWriter() pvTemp200.SetFileName("mhdWriter.mhd") pvTemp200.SetInputData(reader.GetOutput()) pvTemp200.Write() pvTemp90 = vtk.vtkMetaImageReader() pvTemp90.SetFileName("mhdWriter.mhd") pvTemp90.Update() pvTemp109 = vtk.vtkLookupTable() pvTemp109.SetNumberOfTableValues(256) pvTemp109.SetHueRange(0.6667, 0) pvTemp109.SetSaturationRange(1, 1) pvTemp109.SetValueRange(1, 1) pvTemp109.SetTableRange(37.3531, 260) pvTemp109.SetVectorComponent(0) pvTemp109.Build() pvTemp110 = vtk.vtkContourFilter() pvTemp110.SetInputData(pvTemp90.GetOutput(0)) pvTemp110.SetValue(0, 1150) pvTemp110.SetComputeNormals(1) pvTemp110.SetComputeGradients(0) pvTemp110.SetComputeScalars(0) pvTemp114 = vtk.vtkPolyDataMapper() pvTemp114.SetInputConnection(pvTemp110.GetOutputPort()) pvTemp114.SetImmediateModeRendering(1) pvTemp114.SetScalarRange(0, 1) pvTemp114.UseLookupTableScalarRangeOn() pvTemp114.SetScalarVisibility(1) pvTemp114.SetScalarModeToUsePointFieldData() pvTemp114.SelectColorArray("ImageFile") pvTemp114.SetLookupTable(pvTemp109) pvTemp115 = vtk.vtkActor()
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInput(self.Mesh) self.Clipper.GenerateClippedOutputOn() self.Clipper.SetInsideOut(self.InsideOut) if self.Interactive: self.Planes = vtk.vtkPlanes() self.Clipper.SetClipFunction(self.Planes) self.Cutter = vtk.vtkCutter() self.Cutter.SetInput(self.Mesh) self.Cutter.SetCutFunction(self.Planes) self.ClippedMesh = vtk.vtkUnstructuredGrid() self.Surface = vtk.vtkPolyData() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) mapper = vtk.vtkDataSetMapper() mapper.SetInput(self.Mesh) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) self.BoxWidget = vtk.vtkBoxWidget() self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.BoxWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) self.BoxWidget.GetFaceProperty().SetOpacity(0.25) self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback) self.vmtkRenderer.AddKeyBinding('space','Clip.', self.ClipCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() else: self.Mesh.GetPointData().SetActiveScalars(self.ClipArrayName) self.Clipper.GenerateClipScalarsOff() self.Clipper.SetValue(self.ClipValue) self.Clipper.Update() self.Cutter = vtk.vtkContourFilter() self.Cutter.SetInput(self.Mesh) self.Cutter.SetValue(0,self.ClipValue) self.Cutter.Update() self.Mesh = self.Clipper.GetOutput() self.Surface = self.Cutter.GetOutput() self.ClippedMesh = self.Clipper.GetClippedOutput() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs()
def CreateRen2(slcr, cam, viewport, background): # Create Bone contourBone = vtk.vtkContourFilter() contourBone.SetInputConnection(slcr.GetOutputPort()) contourBone.SetValue(0, 75.0) mapperBone = vtk.vtkPolyDataMapper() mapperBone.SetInputConnection(contourBone.GetOutputPort()) mapperBone.SetScalarVisibility(0) #Create Outliner outliner = vtk.vtkOutlineFilter() outliner.SetInputConnection(slcr.GetOutputPort()) outliner.Update() mapperOutliner = vtk.vtkPolyDataMapper() mapperOutliner.SetInputConnection(outliner.GetOutputPort()) # Create Skin contourSkin = vtk.vtkContourFilter() contourSkin.SetInputConnection(slcr.GetOutputPort()) contourSkin.SetValue(0, 50.0) sphere = vtk.vtkSphere() sphere.SetCenter(80, 10, 120) sphere.SetRadius(55) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(contourSkin.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(0) clipper.Update() mapperSkin = vtk.vtkPolyDataMapper() mapperSkin.SetInputConnection(clipper.GetOutputPort()) mapperSkin.SetScalarVisibility(0) # Define Opacity for back skin back = vtk.vtkProperty() back.SetOpacity(1) back.SetColor(0.74, 0.55, 0.55) # Create Actor actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorSkin = vtk.vtkActor() actorSkin.SetMapper(mapperSkin) actorSkin.GetProperty().SetColor(0.74, 0.55, 0.55) actorSkin.GetProperty().SetOpacity(0.7) actorSkin.SetBackfaceProperty(back) actorOutliner = vtk.vtkActor() actorOutliner.SetMapper(mapperOutliner) ren = vtk.vtkRenderer() ren.AddActor(actorBone) ren.AddActor(actorSkin) ren.AddActor(actorOutliner) ren.SetViewport(viewport) ren.SetActiveCamera(cam) ren.ResetCamera() ren.SetBackground(background) return ren
cutPlane.SetOrigin(reader.GetOutput().GetBlock(0).GetCenter()) cutPlane.SetNormal(1, 0, 0) planeCut = vtk.vtkCutter() planeCut.SetInputData(toRectilinearGrid.GetRectilinearGridOutput()) planeCut.SetCutFunction(cutPlane) cutMapper = vtk.vtkDataSetMapper() cutMapper.SetInputConnection(planeCut.GetOutputPort()) cutMapper.SetScalarRange( reader.GetOutput().GetBlock(0).GetPointData().GetScalars().GetRange()) cutActor = vtk.vtkActor() cutActor.SetMapper(cutMapper) iso = vtk.vtkContourFilter() iso.SetInputData(toRectilinearGrid.GetRectilinearGridOutput()) iso.SetValue(0, 0.7) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(iso.GetOutputPort()) normals.SetFeatureAngle(45) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(normals.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(GetRGBColor('bisque')) isoActor.GetProperty().SetRepresentationToWireframe()
# usese the FilePrefix in combination with the slice number to construct # filenames using the format FilePrefix.%d. (In this case the FilePrefix # is the root name of the file: quarter.) v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter") v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient. Once generated, a vtkPolyDataNormals filter is # is used to create normals for smooth surface shading during rendering. # The triangle stripper is used to create triangle strips from the # isosurface these render much faster on may systems. skinExtractor = vtk.vtkContourFilter() skinExtractor.SetInputConnection(v16.GetOutputPort()) skinExtractor.SetValue(0, 500) skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) skinNormals.SetFeatureAngle(60.0) skinMapper = vtk.vtkPolyDataMapper() skinMapper.SetInputConnection(skinNormals.GetOutputPort()) skinMapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skinMapper) # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(v16.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper()
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 main(): colors = vtk.vtkNamedColors() # Set the colors. colors.SetColor("AzimuthArrowColor", [255, 77, 77, 255]) colors.SetColor("ElevationArrowColor", [77, 255, 77, 255]) colors.SetColor("RollArrowColor", [255, 255, 77, 255]) colors.SetColor("SpikeColor", [255, 77, 255, 255]) colors.SetColor("UpSpikeColor", [77, 255, 255, 255]) # Create a rendering window, renderer and interactor. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create a camera model. camCS = vtk.vtkConeSource() camCS.SetHeight(1.5) camCS.SetResolution(12) camCS.SetRadius(0.4) camCBS = vtk.vtkCubeSource() camCBS.SetXLength(1.5) camCBS.SetZLength(0.8) camCBS.SetCenter(0.4, 0, 0) camAPD = vtk.vtkAppendPolyData() camAPD.AddInputConnection(camCBS.GetOutputPort()) camAPD.AddInputConnection(camCS.GetOutputPort()) camMapper = vtk.vtkPolyDataMapper() camMapper.SetInputConnection(camAPD.GetOutputPort()) camActor = vtk.vtkLODActor() camActor.SetMapper(camMapper) camActor.SetScale(2, 2, 2) # Draw the arrows. pd = vtk.vtkPolyData() ca = vtk.vtkCellArray() pts = vtk.vtkPoints() pts.InsertNextPoint(0, 1, 0) pts.InsertNextPoint(8, 1, 0) pts.InsertNextPoint(8, 2, 0) pts.InsertNextPoint(10, 0, 0) pts.InsertNextPoint(8, -2, 0) pts.InsertNextPoint(8, -1, 0) pts.InsertNextPoint(0, -1, 0) ca.InsertNextCell(7) ca.InsertCellPoint(0) ca.InsertCellPoint(1) ca.InsertCellPoint(2) ca.InsertCellPoint(3) ca.InsertCellPoint(4) ca.InsertCellPoint(5) ca.InsertCellPoint(6) pd.SetPoints(pts) pd.SetPolys(ca) pd2 = vtk.vtkPolyData() ca2 = vtk.vtkCellArray() pts2 = vtk.vtkPoints() pts2.InsertNextPoint(0, 1, 0) pts2.InsertNextPoint(8, 1, 0) pts2.InsertNextPoint(8, 2, 0) pts2.InsertNextPoint(10, 0.01, 0) ca2.InsertNextCell(4) ca2.InsertCellPoint(0) ca2.InsertCellPoint(1) ca2.InsertCellPoint(2) ca2.InsertCellPoint(3) pd2.SetPoints(pts2) pd2.SetLines(ca2) arrowIM = vtk.vtkImplicitModeller() arrowIM.SetInputData(pd) arrowIM.SetSampleDimensions(50, 20, 8) arrowCF = vtk.vtkContourFilter() arrowCF.SetInputConnection(arrowIM.GetOutputPort()) arrowCF.SetValue(0, 0.2) arrowWT = vtk.vtkWarpTo() arrowWT.SetInputConnection(arrowCF.GetOutputPort()) arrowWT.SetPosition(5, 0, 5) arrowWT.SetScaleFactor(0.85) arrowWT.AbsoluteOn() arrowT = vtk.vtkTransform() arrowT.RotateY(60) arrowT.Translate(-1.33198, 0, -1.479) arrowT.Scale(1, 0.5, 1) arrowTF = vtk.vtkTransformFilter() arrowTF.SetInputConnection(arrowWT.GetOutputPort()) arrowTF.SetTransform(arrowT) arrowMapper = vtk.vtkDataSetMapper() arrowMapper.SetInputConnection(arrowTF.GetOutputPort()) arrowMapper.ScalarVisibilityOff() # Draw the azimuth arrows. a1Actor = vtk.vtkLODActor() a1Actor.SetMapper(arrowMapper) a1Actor.SetPosition(-9, 0, -1) a1Actor.GetProperty().SetColor(colors.GetColor3d("AzimuthArrowColor")) a1Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a1Actor.GetProperty().SetSpecular(0.3) a1Actor.GetProperty().SetSpecularPower(20) a1Actor.GetProperty().SetAmbient(0.2) a1Actor.GetProperty().SetDiffuse(0.8) a2Actor = vtk.vtkLODActor() a2Actor.SetMapper(arrowMapper) a2Actor.RotateX(180) a2Actor.SetPosition(-9, 0, 1) a2Actor.GetProperty().SetColor(colors.GetColor3d("AzimuthArrowColor")) a2Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a2Actor.GetProperty().SetSpecular(0.3) a2Actor.GetProperty().SetSpecularPower(20) a2Actor.GetProperty().SetAmbient(0.2) a2Actor.GetProperty().SetDiffuse(0.8) # Draw the elevation arrows. a3Actor = vtk.vtkLODActor() a3Actor.SetMapper(arrowMapper) a3Actor.RotateX(-90) a3Actor.SetPosition(-9, -1, 0) a3Actor.GetProperty().SetColor(colors.GetColor3d("ElevationArrowColor")) a3Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a3Actor.GetProperty().SetSpecular(0.3) a3Actor.GetProperty().SetSpecularPower(20) a3Actor.GetProperty().SetAmbient(0.2) a3Actor.GetProperty().SetDiffuse(0.8) a4Actor = vtk.vtkLODActor() a4Actor.SetMapper(arrowMapper) a4Actor.RotateX(90) a4Actor.SetPosition(-9, 1, 0) a4Actor.GetProperty().SetColor(colors.GetColor3d("ElevationArrowColor")) a4Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a4Actor.GetProperty().SetSpecular(0.3) a4Actor.GetProperty().SetSpecularPower(20) a4Actor.GetProperty().SetAmbient(0.2) a4Actor.GetProperty().SetDiffuse(0.8) # Draw the DOP. arrowT2 = vtk.vtkTransform() arrowT2.Scale(1, 0.6, 1) arrowT2.RotateY(90) arrowTF2 = vtk.vtkTransformPolyDataFilter() arrowTF2.SetInputData(pd2) arrowTF2.SetTransform(arrowT2) arrowREF = vtk.vtkRotationalExtrusionFilter() arrowREF.SetInputConnection(arrowTF2.GetOutputPort()) arrowREF.CappingOff() arrowREF.SetResolution(30) spikeMapper = vtk.vtkPolyDataMapper() spikeMapper.SetInputConnection(arrowREF.GetOutputPort()) a5Actor = vtk.vtkLODActor() a5Actor.SetMapper(spikeMapper) a5Actor.SetScale(0.3, 0.3, 0.6) a5Actor.RotateY(-90) a5Actor.SetPosition(-8, 0, 0) a5Actor.GetProperty().SetColor(colors.GetColor3d("SpikeColor")) a5Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a5Actor.GetProperty().SetSpecular(0.3) a5Actor.GetProperty().SetAmbient(0.2) a5Actor.GetProperty().SetDiffuse(0.8) a5Actor.GetProperty().SetSpecularPower(20) a7Actor = vtk.vtkLODActor() a7Actor.SetMapper(spikeMapper) a7Actor.SetScale(0.2, 0.2, 0.7) a7Actor.RotateZ(90) a7Actor.RotateY(-90) a7Actor.SetPosition(-9, 1, 0) a7Actor.GetProperty().SetColor(colors.GetColor3d("UpSpikeColor")) a7Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a7Actor.GetProperty().SetSpecular(0.3) a7Actor.GetProperty().SetAmbient(0.2) a7Actor.GetProperty().SetDiffuse(0.8) a7Actor.GetProperty().SetSpecularPower(20) # Focal point. ss = vtk.vtkSphereSource() ss.SetRadius(0.5) fpMapper = vtk.vtkPolyDataMapper() fpMapper.SetInputConnection(ss.GetOutputPort()) fpActor = vtk.vtkLODActor() fpActor.SetMapper(fpMapper) fpActor.SetPosition(-9, 0, 0) fpActor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) fpActor.GetProperty().SetSpecular(0.3) fpActor.GetProperty().SetAmbient(0.2) fpActor.GetProperty().SetDiffuse(0.8) fpActor.GetProperty().SetSpecularPower(20) # Create the roll arrows. arrowWT2 = vtk.vtkWarpTo() arrowWT2.SetInputConnection(arrowCF.GetOutputPort()) arrowWT2.SetPosition(5, 0, 2.5) arrowWT2.SetScaleFactor(0.95) arrowWT2.AbsoluteOn() arrowT3 = vtk.vtkTransform() arrowT3.Translate(-2.50358, 0, -1.70408) arrowT3.Scale(0.5, 0.3, 1) arrowTF3 = vtk.vtkTransformFilter() arrowTF3.SetInputConnection(arrowWT2.GetOutputPort()) arrowTF3.SetTransform(arrowT3) arrowMapper2 = vtk.vtkDataSetMapper() arrowMapper2.SetInputConnection(arrowTF3.GetOutputPort()) arrowMapper2.ScalarVisibilityOff() # Draw the roll arrows. a6Actor = vtk.vtkLODActor() a6Actor.SetMapper(arrowMapper2) a6Actor.RotateZ(90) a6Actor.SetPosition(-4, 0, 0) a6Actor.SetScale(1.5, 1.5, 1.5) a6Actor.GetProperty().SetColor(colors.GetColor3d("RollArrowColor")) a6Actor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) a6Actor.GetProperty().SetSpecular(0.3) a6Actor.GetProperty().SetSpecularPower(20) a6Actor.GetProperty().SetAmbient(0.2) a6Actor.GetProperty().SetDiffuse(0.8) # Add the actors to the renderer, set the background and size. ren.AddActor(camActor) ren.AddActor(a1Actor) ren.AddActor(a2Actor) ren.AddActor(a3Actor) ren.AddActor(a4Actor) ren.AddActor(a5Actor) ren.AddActor(a6Actor) ren.AddActor(a7Actor) ren.AddActor(fpActor) ren.SetBackground(colors.GetColor3d("SlateGray")) renWin.SetSize(640, 480) # Render the image. cam1 = (ren.GetActiveCamera()) ren.ResetCamera() cam1.Azimuth(150) cam1.Elevation(30) cam1.Dolly(1.5) ren.ResetCameraClippingRange() # Create a TextActor for Yaw (a1 and a2 actor's color). text = vtk.vtkTextActor() text.SetInput("Yaw") tprop = text.GetTextProperty() tprop.SetFontFamilyToArial() tprop.ShadowOff() tprop.SetLineSpacing(1.0) tprop.SetFontSize(36) tprop.SetColor(a1Actor.GetProperty().GetColor()) text.SetDisplayPosition(20, 50) ren.AddActor2D(text) # Create a TextActor for Pitch (a3 and a4 actor's color). text2 = vtk.vtkTextActor() text2.SetInput("Pitch") tprop = text2.GetTextProperty() tprop.SetFontFamilyToArial() tprop.ShadowOff() tprop.SetLineSpacing(1.0) tprop.SetFontSize(36) tprop.SetColor(a3Actor.GetProperty().GetColor()) text2.SetDisplayPosition(20, 100) ren.AddActor2D(text2) # Create a TextActor for roll (a6 actor's color). text3 = vtk.vtkTextActor() text3.SetInput("Roll") tprop = text3.GetTextProperty() tprop.SetFontFamilyToArial() tprop.ShadowOff() tprop.SetLineSpacing(1.0) tprop.SetFontSize(36) tprop.SetColor(a6Actor.GetProperty().GetColor()) text3.SetDisplayPosition(20, 150) ren.AddActor2D(text3) iren.Initialize() iren.Start()
def contour_from_roi(data, affine=None, color=np.array([1, 0, 0]), opacity=1): """Generate surface actor from a binary ROI. The color and opacity of the surface can be customized. Parameters ---------- data : array, shape (X, Y, Z) An ROI file that will be binarized and displayed. affine : array, shape (4, 4) Grid to space (usually RAS 1mm) transformation matrix. Default is None. If None then the identity matrix is used. color : (1, 3) ndarray RGB values in [0,1]. opacity : float Opacity of surface between 0 and 1. Returns ------- contour_assembly : vtkAssembly ROI surface object displayed in space coordinates as calculated by the affine parameter. """ if data.ndim != 3: raise ValueError('Only 3D arrays are currently supported.') else: nb_components = 1 data = (data > 0) * 1 vol = np.interp(data, xp=[data.min(), data.max()], fp=[0, 255]) vol = vol.astype('uint8') im = vtk.vtkImageData() di, dj, dk = vol.shape[:3] im.SetDimensions(di, dj, dk) voxsz = (1., 1., 1.) # im.SetOrigin(0,0,0) im.SetSpacing(voxsz[2], voxsz[0], voxsz[1]) im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, nb_components) # copy data vol = np.swapaxes(vol, 0, 2) vol = np.ascontiguousarray(vol) if nb_components == 1: vol = vol.ravel() else: vol = np.reshape(vol, [np.prod(vol.shape[:3]), vol.shape[3]]) uchar_array = numpy_support.numpy_to_vtk(vol, deep=0) im.GetPointData().SetScalars(uchar_array) if affine is None: affine = np.eye(4) # Set the transform (identity if none given) transform = vtk.vtkTransform() transform_matrix = vtk.vtkMatrix4x4() transform_matrix.DeepCopy( (affine[0][0], affine[0][1], affine[0][2], affine[0][3], affine[1][0], affine[1][1], affine[1][2], affine[1][3], affine[2][0], affine[2][1], affine[2][2], affine[2][3], affine[3][0], affine[3][1], affine[3][2], affine[3][3])) transform.SetMatrix(transform_matrix) transform.Inverse() # Set the reslicing image_resliced = vtk.vtkImageReslice() set_input(image_resliced, im) image_resliced.SetResliceTransform(transform) image_resliced.AutoCropOutputOn() # Adding this will allow to support anisotropic voxels # and also gives the opportunity to slice per voxel coordinates rzs = affine[:3, :3] zooms = np.sqrt(np.sum(rzs * rzs, axis=0)) image_resliced.SetOutputSpacing(*zooms) image_resliced.SetInterpolationModeToLinear() image_resliced.Update() skin_extractor = vtk.vtkContourFilter() skin_extractor.SetInputData(image_resliced.GetOutput()) skin_extractor.SetValue(0, 1) skin_normals = vtk.vtkPolyDataNormals() skin_normals.SetInputConnection(skin_extractor.GetOutputPort()) skin_normals.SetFeatureAngle(60.0) skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin_normals.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin_actor = vtk.vtkActor() skin_actor.SetMapper(skin_mapper) skin_actor.GetProperty().SetOpacity(opacity) skin_actor.GetProperty().SetColor(color[0], color[1], color[2]) return skin_actor
def Main(): global ren print "data: %s" % sys.argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(sys.argv[1]) isosurfaces = [ [500,0.1,0.3,1,0.3], [1158,0.1,0.6,1,0.5], [2750,0.1,1,1,1] ] ren = vtk.vtkRenderer() for surface in isosurfaces: lut = vtk.vtkColorTransferFunction() lut.SetColorSpaceToHSV() lut.AddHSVPoint(surface[0],surface[1],surface[2],surface[3]) contours = vtk.vtkContourFilter() contours.SetInputConnection(reader.GetOutputPort()); contours.ComputeNormalsOn() contours.SetValue(0, surface[0]) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(contours.GetOutputPort()) mapper.SetLookupTable(lut) mapper.ImmediateModeRenderingOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(surface[4]) ren.AddActor(actor) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.RemoveObservers('RightButtonPressEvent') iren.AddObserver('RightButtonPressEvent', print_camera_settings, 1.0) iren.AddObserver('RightButtonPressEvent', after_print_camera_settings, -1.0) # for depth peeling ren.SetUseDepthPeeling(1) ren.SetMaximumNumberOfPeels(4) # default 4 ren.SetOcclusionRatio(0) # default 0 ren.ResetCamera() ren.SetBackground(0,0,0) ren.ResetCameraClippingRange() ren.GetActiveCamera().SetViewUp(-0.033792287793636924, 0.000854723562570334, -0.9994285120674231) ren.GetActiveCamera().SetPosition(-308.155681140229, -119.92183136577268, 117.3094068139949 ) ren.GetActiveCamera().SetFocalPoint(91.14654767513275, 104.1683804243803, 104.0) ren.GetActiveCamera().SetClippingRange(191.00826351112892, 795.369621458024) # for depth peeling renWin.SetAlphaBitPlanes(1) renWin.SetMultiSamples(0) renWin.SetSize(1600, 900) # Render iren.Initialize() renWin.Render() iren.Start()
def contour(dataset, isosurfaces=10, scalars=None, compute_normals=False, compute_gradients=False, compute_scalars=True, rng=None, preference='point'): """Contours an input dataset by an array. ``isosurfaces`` can be an integer specifying the number of isosurfaces in the data range or an iterable set of values for explicitly setting the isosurfaces. Parameters ---------- isosurfaces : int or iterable Number of isosurfaces to compute across valid data range or an iterable of float values to explicitly use as the isosurfaces. scalars : str, optional Name of scalars to threshold on. Defaults to currently active scalars. compute_normals : bool, optional compute_gradients : bool, optional Desc compute_scalars : bool, optional Preserves the scalar values that are being contoured rng : tuple(float), optional If an integer number of isosurfaces is specified, this is the range over which to generate contours. Default is the scalar arrays's full data range. preference : str, optional When scalars is specified, this is the perfered scalar type to search for in the dataset. Must be either ``'point'`` or ``'cell'`` """ # Make sure the input has scalars to contour on if dataset.n_scalars < 1: raise AssertionError('Input dataset for the contour filter must have scalar data.') alg = vtk.vtkContourFilter() alg.SetInputDataObject(dataset) alg.SetComputeNormals(compute_normals) alg.SetComputeGradients(compute_gradients) alg.SetComputeScalars(compute_scalars) # set the array to contour on if scalars is None: field, scalars = dataset.active_scalar_info else: _, field = get_scalar(dataset, scalars, preference=preference, info=True) # NOTE: only point data is allowed? well cells works but seems buggy? if field != vtki.POINT_DATA_FIELD: raise AssertionError('Contour filter only works on Point data. Array ({}) is in the Cell data.'.format(scalars)) alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name) # set the isosurfaces if isinstance(isosurfaces, int): # generate values if rng is None: rng = dataset.get_data_range(scalars) alg.GenerateValues(isosurfaces, rng) elif isinstance(isosurfaces, collections.Iterable): alg.SetNumberOfContours(len(isosurfaces)) for i, val in enumerate(isosurfaces): alg.SetValue(i, val) else: raise RuntimeError('isosurfaces not understood.') alg.Update() return _get_output(alg)
def generateIsosurface(reader): isoSurface = vtk.vtkContourFilter() isoSurface.SetInputConnection(reader.GetOutputPort()) isoSurface.GenerateValues(1, threshold) return isoSurface
readerSS.SetInputData(reader.GetGridOutput()) readerSS.SetShift(min * -1) readerSS.SetScale(255 / (max - min)) readerSS.SetOutputScalarTypeToUnsignedChar() bounds = vtk.vtkOutlineFilter() bounds.SetInputData(reader.GetGridOutput()) boundsMapper = vtk.vtkPolyDataMapper() boundsMapper.SetInputConnection(bounds.GetOutputPort()) boundsActor = vtk.vtkActor() boundsActor.SetMapper(boundsMapper) boundsActor.GetProperty().SetColor(0, 0, 0) contour = vtk.vtkContourFilter() contour.SetInputData(reader.GetGridOutput()) contour.GenerateValues(5, 0, .05) contourMapper = vtk.vtkPolyDataMapper() contourMapper.SetInputConnection(contour.GetOutputPort()) contourMapper.SetScalarRange(0, .1) contourMapper.GetLookupTable().SetHueRange(0.32, 0) contourActor = vtk.vtkActor() contourActor.SetMapper(contourMapper) contourActor.GetProperty().SetOpacity(.5) # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(0, 0.01)
def Main(): global isovalue, contours, planeSource1, planeSource2, planeSource3, plane1, plane2, plane3, clipper1, clipper2, clipper3, clipX, clipY, clipZ print "data: %s" % sys.argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(sys.argv[1]) reader.Update() clipX = 0 clipY = 0 clipZ = 0 r = reader.GetOutput().GetScalarRange() datamin = r[0] datamax = r[1] isovalue = (datamax+datamin)/2.0 for i in range(2, len(sys.argv)): if sys.argv[i] == "--val": isovalue = float(sys.argv[i+1]) print "isovalue: %f"%isovalue if sys.argv[i] == "--clip": clipX = float(sys.argv[i+1]) clipY = float(sys.argv[i+2]) clipZ = float(sys.argv[i+3]) print "clip (%f,%f,%f)" %(clipX,clipY,clipZ) contours = vtk.vtkContourFilter() contours.SetInputConnection(reader.GetOutputPort()); contours.ComputeNormalsOn() contours.SetValue(0, isovalue) lut = vtk.vtkColorTransferFunction() lut.SetColorSpaceToHSV() lut.AddHSVPoint(datamin,0,1,1) dis = (datamax-datamin)/7 for i in range(0,8): lut.AddHSVPoint(datamin+dis*i,0.1*i,1,1) planeSource1 = vtk.vtkPlaneSource() planeSource1.SetNormal(1,0,0) planeSource1.SetOrigin(clipX,0,0) planeSource2 = vtk.vtkPlaneSource() planeSource2.SetNormal(0,1,0) planeSource2.SetOrigin(0,clipY,0) planeSource3 = vtk.vtkPlaneSource() planeSource3.SetNormal(0,0,1) planeSource3.SetOrigin(0,0,clipZ) plane1 = vtk.vtkPlane() plane1.SetNormal(planeSource1.GetNormal()) plane1.SetOrigin(planeSource1.GetOrigin()) clipper1 = vtk.vtkClipPolyData() clipper1.SetClipFunction(plane1) clipper1.SetInputConnection(contours.GetOutputPort()) clipper1.Update() plane2 = vtk.vtkPlane() plane2.SetNormal(planeSource2.GetNormal()) plane2.SetOrigin(planeSource2.GetOrigin()) clipper2 = vtk.vtkClipPolyData() clipper2.SetClipFunction(plane2) clipper2.SetInputConnection(clipper1.GetOutputPort()) clipper2.Update() plane3 = vtk.vtkPlane() plane3.SetNormal(planeSource3.GetNormal()) plane3.SetOrigin(planeSource3.GetOrigin()) clipper3 = vtk.vtkClipPolyData() clipper3.SetClipFunction(plane3) clipper3.SetInputConnection(clipper2.GetOutputPort()) clipper3.Update() clipperMapper = vtk.vtkPolyDataMapper() clipperMapper.SetLookupTable(lut) clipperMapper.SetInputConnection(clipper3.GetOutputPort()) colorBar = vtkScalarBarActor() colorBar.SetLookupTable(clipperMapper.GetLookupTable()) colorBar.SetTitle("isovalue") colorBar.SetNumberOfLabels(6) colorBar.SetLabelFormat("%4.0f") colorBar.SetPosition(0.9, 0.1) colorBar.SetWidth(0.1) colorBar.SetHeight(0.7) clipperActor=vtk.vtkActor() clipperActor.GetProperty().SetRepresentationToWireframe() clipperActor.SetMapper(clipperMapper) backFaces = vtk.vtkProperty() backFaces.SetSpecular(0) backFaces.SetDiffuse(0) backFaces.SetAmbient(0) backFaces.SetAmbientColor(1,0,0) clipperActor.SetBackfaceProperty(backFaces) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.AddActor(clipperActor) ren.AddActor(colorBar) ren.ResetCamera() ren.SetBackground(0.2,0.3,0.4) ren.ResetCameraClippingRange() renWin.SetSize(1200, 600) isovalueSlider = vtk.vtkSliderRepresentation2D() isovalueSlider.SetMinimumValue(datamin) isovalueSlider.SetMaximumValue(datamax) isovalueSlider.SetValue(isovalue) isovalueSlider.SetTitleText("isovalue") isovalueSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() isovalueSlider.GetPoint1Coordinate().SetValue(0.0, 0.4) isovalueSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() isovalueSlider.GetPoint2Coordinate().SetValue(0.2, 0.4) isovalueSlider.SetSliderLength(0.02) isovalueSlider.SetSliderWidth(0.03) isovalueSlider.SetEndCapLength(0.01) isovalueSlider.SetEndCapWidth(0.03) isovalueSlider.SetTubeWidth(0.005) isovalueSlider.SetLabelFormat("%3.0lf") isovalueSlider.SetTitleHeight(0.02) isovalueSlider.SetLabelHeight(0.02) SliderWidget1 = vtk.vtkSliderWidget() SliderWidget1.SetInteractor(iren) SliderWidget1.SetRepresentation(isovalueSlider) SliderWidget1.KeyPressActivationOff() SliderWidget1.SetAnimationModeToAnimate() SliderWidget1.SetEnabled(True) SliderWidget1.AddObserver("InteractionEvent", isovalueSliderHandler) clipXSlider = vtk.vtkSliderRepresentation2D() clipXSlider.SetMinimumValue(0) clipXSlider.SetMaximumValue(300) clipXSlider.SetValue(clipX) clipXSlider.SetTitleText("X") clipXSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipXSlider.GetPoint1Coordinate().SetValue(0.0, 0.3) clipXSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipXSlider.GetPoint2Coordinate().SetValue(0.2, 0.3) clipXSlider.SetSliderLength(0.02) clipXSlider.SetSliderWidth(0.03) clipXSlider.SetEndCapLength(0.01) clipXSlider.SetEndCapWidth(0.03) clipXSlider.SetTubeWidth(0.005) clipXSlider.SetLabelFormat("%1.2lf") clipXSlider.SetTitleHeight(0.02) clipXSlider.SetLabelHeight(0.02) SliderWidget2 = vtk.vtkSliderWidget() SliderWidget2.SetInteractor(iren) SliderWidget2.SetRepresentation(clipXSlider) SliderWidget2.KeyPressActivationOff() SliderWidget2.SetAnimationModeToAnimate() SliderWidget2.SetEnabled(True) SliderWidget2.AddObserver("InteractionEvent", clipXSliderHandler) clipYSlider = vtk.vtkSliderRepresentation2D() clipYSlider.SetMinimumValue(0) clipYSlider.SetMaximumValue(300) clipYSlider.SetValue(clipY) clipYSlider.SetTitleText("Y") clipYSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipYSlider.GetPoint1Coordinate().SetValue(0.0, 0.2) clipYSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipYSlider.GetPoint2Coordinate().SetValue(0.2, 0.2) clipYSlider.SetSliderLength(0.02) clipYSlider.SetSliderWidth(0.03) clipYSlider.SetEndCapLength(0.01) clipYSlider.SetEndCapWidth(0.03) clipYSlider.SetTubeWidth(0.005) clipYSlider.SetLabelFormat("%1.2lf") clipYSlider.SetTitleHeight(0.02) clipYSlider.SetLabelHeight(0.02) SliderWidget3 = vtk.vtkSliderWidget() SliderWidget3.SetInteractor(iren) SliderWidget3.SetRepresentation(clipYSlider) SliderWidget3.KeyPressActivationOff() SliderWidget3.SetAnimationModeToAnimate() SliderWidget3.SetEnabled(True) SliderWidget3.AddObserver("InteractionEvent", clipYSliderHandler) clipZSlider = vtk.vtkSliderRepresentation2D() clipZSlider.SetMinimumValue(0) clipZSlider.SetMaximumValue(300) clipZSlider.SetValue(clipZ) clipZSlider.SetTitleText("Z") clipZSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() clipZSlider.GetPoint1Coordinate().SetValue(0.0, 0.1) clipZSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() clipZSlider.GetPoint2Coordinate().SetValue(0.2, 0.1) clipZSlider.SetSliderLength(0.02) clipZSlider.SetSliderWidth(0.03) clipZSlider.SetEndCapLength(0.01) clipZSlider.SetEndCapWidth(0.03) clipZSlider.SetTubeWidth(0.005) clipZSlider.SetLabelFormat("%1.2lf") clipZSlider.SetTitleHeight(0.02) clipZSlider.SetLabelHeight(0.02) SliderWidget4 = vtk.vtkSliderWidget() SliderWidget4.SetInteractor(iren) SliderWidget4.SetRepresentation(clipZSlider) SliderWidget4.KeyPressActivationOff() SliderWidget4.SetAnimationModeToAnimate() SliderWidget4.SetEnabled(True) SliderWidget4.AddObserver("InteractionEvent", clipZSliderHandler) # Render iren.Initialize() renWin.Render() iren.Start()
def main(): colors = vtk.vtkNamedColors() # Create implicit function primitives. These have been carefully placed to # give the effect that we want. We are going to use various combinations of # these functions to create the shape we want for example, we use planes # intersected with a cone (which is infinite in extent) to get a finite # cone. # cone = vtk.vtkCone() cone.SetAngle(20) vertPlane = vtk.vtkPlane() vertPlane.SetOrigin(.1, 0, 0) vertPlane.SetNormal(-1, 0, 0) basePlane = vtk.vtkPlane() basePlane.SetOrigin(1.2, 0, 0) basePlane.SetNormal(1, 0, 0) iceCream = vtk.vtkSphere() iceCream.SetCenter(1.333, 0, 0) iceCream.SetRadius(0.5) bite = vtk.vtkSphere() bite.SetCenter(1.5, 0, 0.5) bite.SetRadius(0.25) # Combine primitives to build ice-cream cone. Clip the cone with planes. theCone = vtk.vtkImplicitBoolean() theCone.SetOperationTypeToIntersection() theCone.AddFunction(cone) theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) # Take a bite out of the ice cream. theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # The sample function generates a distance function from the # implicit function (which in this case is the cone). This is # then contoured to get a polygonal surface. # theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25) theConeSample.SetSampleDimensions(128, 128, 128) theConeSample.ComputeNormalsOff() theConeSurface = vtk.vtkContourFilter() theConeSurface.SetInputConnection(theConeSample.GetOutputPort()) theConeSurface.SetValue(0, 0.0) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(theConeSurface.GetOutputPort()) coneMapper.ScalarVisibilityOff() coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(colors.GetColor3d('Chocolate')) # The same here for the ice cream. # theCreamSample = vtk.vtkSampleFunction() theCreamSample.SetImplicitFunction(theCream) theCreamSample.SetModelBounds(0, 2.5, -1.25, 1.25, -1.25, 1.25) theCreamSample.SetSampleDimensions(128, 128, 128) theCreamSample.ComputeNormalsOff() theCreamSurface = vtk.vtkContourFilter() theCreamSurface.SetInputConnection(theCreamSample.GetOutputPort()) theCreamSurface.SetValue(0, 0.0) creamMapper = vtk.vtkPolyDataMapper() creamMapper.SetInputConnection(theCreamSurface.GetOutputPort()) creamMapper.ScalarVisibilityOff() creamActor = vtk.vtkActor() creamActor.SetMapper(creamMapper) creamActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Mint')) creamActor.GetProperty().SetSpecular(.6) creamActor.GetProperty().SetSpecularPower(50) # Create the usual rendering stuff. # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size. # ren1.AddActor(coneActor) ren1.AddActor(creamActor) ren1.SetBackground(colors.GetColor3d('SlateGray')) renWin.SetSize(640, 480) renWin.SetWindowName('IceCream') ren1.ResetCamera() ren1.GetActiveCamera().Roll(90) ren1.GetActiveCamera().Dolly(1.25) ren1.ResetCameraClippingRange() iren.Initialize() # render the image # renWin.Render() iren.Start()
def main(): # setup the dataset filepath path = "D:/data/" files = os.listdir(path); time_index = []; for i in range(266, 300): if(i%3==0): time_index.append(i); #print(files); daryName = "v02"; for i in range(0, len(time_index)): #for i in range(0, 1): filename = path+ files[time_index[i]]; print(filename); #filename = "yC31/pv_insitu_300x300x300_29072.vti" # the name of data array which is used in this example daryName = "v02"; # for accessomg build-in color access colors = vtk.vtkNamedColors(); # Create the renderer, the render window, and the interactor. # The renderer draws into the render window. # The interactor enables mouse and keyboard-based interaction # with the data within the render windows. aRenderer = vtk.vtkRenderer(); renWin = vtk.vtkRenderWindow(); renWin.AddRenderer(aRenderer); iren = vtk.vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); # Set a background color for the renderer # and set the size of the render window. aRenderer.SetBackground(colors.GetColor3d("Silver")); renWin.SetSize(600, 600); # data reader reader = vtk.vtkXMLImageDataReader(); reader.SetFileName(filename); reader.Update(); # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0); # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars(daryName)); dary = dary[dary!= 0] dMax = np.amax(dary); dMin = np.amin(dary); dRange = dMax - dMin; dMean = np.mean(dary); dMedian = np.median(dary); dstd = np.std(dary); print("Data array max: ", dMax); print("Data array min: ", dMin); print("Data array range: ", dRange); print("Data array mean: ", dMean); print("Data array median: ", dMedian); print("Data array std: ", dstd); ############ setup color map ######### # Now create a loopup table that consists of the full hue circle # (from HSV). hueLut = vtk.vtkLookupTable(); hueLut.SetTableRange(dMin, dMax); hueLut.Build(); # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter(); outlineData.SetInputConnection(reader.GetOutputPort()); outlineData.Update() mapOutline = vtk.vtkPolyDataMapper(); mapOutline.SetInputConnection(outlineData.GetOutputPort()); outline = vtk.vtkActor(); outline.SetMapper(mapOutline); outline.GetProperty().SetColor(colors.GetColor3d("Black")); #################### create isosurface v02 = mean ###################################### # isosurface iso = vtk.vtkContourFilter(); iso.SetInputConnection(reader.GetOutputPort()); iso.Update(); iso.SetValue(0, dMean); normals = vtk.vtkPolyDataNormals(); normals.SetInputConnection(iso.GetOutputPort()); normals.SetFeatureAngle(45); isoMapper = vtk.vtkPolyDataMapper(); isoMapper.SetInputConnection(normals.GetOutputPort()); isoMapper.ScalarVisibilityOff(); isoActor = vtk.vtkActor(); isoActor.SetMapper(isoMapper); isoActor.GetProperty().SetColor(colors.GetColor3d("bisque")); isoActor.GetProperty().SetOpacity(0.5); ############################### create isosurface v02 = median###################################### ''' # isosurface iso2 = vtk.vtkContourFilter(); iso2.SetInputConnection(reader.GetOutputPort()); iso2.Update(); iso2.SetValue(0, dMedian); normals2 = vtk.vtkPolyDataNormals(); normals2.SetInputConnection(iso2.GetOutputPort()); normals2.SetFeatureAngle(45); isoMapper2 = vtk.vtkPolyDataMapper(); isoMapper2.SetInputConnection(normals2.GetOutputPort()); isoMapper2.ScalarVisibilityOff(); isoActor2 = vtk.vtkActor(); isoActor2.SetMapper(isoMapper2); isoActor2.GetProperty().SetColor(0.0, 0.9, 0.9); isoActor2.GetProperty().SetOpacity(0.2); ''' ############################################################################### aCamera = vtk.vtkCamera(); aCamera.SetViewUp(0, 0, 1); aCamera.SetPosition(1, 1, 2); aCamera.SetFocalPoint(0, 0, 0); aCamera.ComputeViewPlaneNormal(); aCamera.Azimuth(45.0); aCamera.Elevation(-140.0); ######################## create a text ##################### # create a text actor txt = vtk.vtkTextActor() txt_str = "isosurface value(bisque) (mean) = "+str(dMean)[:5] txt.SetInput(txt_str) txtprop=txt.GetTextProperty() txtprop.SetFontFamilyToArial() txtprop.SetFontSize(24) txtprop.SetColor(colors.GetColor3d("bisque")) txt.SetDisplayPosition(50,550) ############################################################ txt2 = vtk.vtkTextActor() txt_str2 = "isosurface value (median)(blue) = "+ str(dMedian)[:5] txt2.SetInput(txt_str2) txtprop2=txt2.GetTextProperty() txtprop2.SetFontFamilyToArial() txtprop2.SetFontSize(24) txtprop2.SetColor(0,0.9,0.9) txt2.SetDisplayPosition(50,525) ########################################################## txt3 = vtk.vtkTextActor() txt_str3 = "timestep = "+filename[30:35] txt3.SetInput(txt_str3) txtprop3=txt3.GetTextProperty() txtprop3.SetFontFamilyToArial() txtprop3.SetFontSize(24) txtprop3.SetColor(0,0,0) txt3.SetDisplayPosition(50,500) # Actors are added to the renderer. aRenderer.AddActor(outline); aRenderer.AddActor(isoActor); #aRenderer.AddActor(isoActor2); aRenderer.AddActor(txt); #aRenderer.AddActor(txt2); aRenderer.AddActor(txt3); # An initial camera view is created. The Dolly() method moves # the camera towards the FocalPoint, thereby enlarging the image. aRenderer.SetActiveCamera(aCamera); # Calling Render() directly on a vtkRenderer is strictly forbidden. # Only calling Render() on the vtkRenderWindow is a valid call. renWin.Render(); aRenderer.ResetCamera(); aCamera.Dolly(-2.0); #################################################################### # screenshot code: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.Update() writer = vtk.vtkPNGWriter() saveName = "plots/yA31/ios/v02/"+daryName+"_t_"+filename[30:35]+".png"; writer.SetFileName(saveName) writer.SetInputData(w2if.GetOutput()) writer.Write() ##################################################################### # Note that when camera movement occurs (as it does in the Dolly() method), # the clipping planes often #need adjusting. # Clipping planes consist of two planes: # near and far along the view direction. # The near plane clips out objects in front of the plane; # the far plane clips out objects behind the plane. # This way only what is drawn between the planes is actually rendered. aRenderer.ResetCameraClippingRange(); # Interact with the data. renWin.Render();
blobbyK = vtk.vtkImplicitModeller() blobbyK.SetInputConnection(letterK.GetOutputPort()) blobbyK.SetMaximumDistance(.2) blobbyK.SetSampleDimensions(50, 50, 12) blobbyK.SetModelBounds(-0.5, 1.5, -0.5, 1.5, -0.5, 0.5) # Interpolate the data interpolate = vtk.vtkInterpolateDataSetAttributes() interpolate.AddInputConnection(blobbyV.GetOutputPort()) interpolate.AddInputConnection(blobbyT.GetOutputPort()) interpolate.AddInputConnection(blobbyK.GetOutputPort()) interpolate.SetT(0.0) # extract an iso surface blobbyIso = vtk.vtkContourFilter() blobbyIso.SetInputConnection(interpolate.GetOutputPort()) blobbyIso.SetValue(0, 0.1) # map to rendering primitives blobbyMapper = vtk.vtkPolyDataMapper() blobbyMapper.SetInputConnection(blobbyIso.GetOutputPort()) blobbyMapper.ScalarVisibilityOff() # now an actor blobby = vtk.vtkActor() blobby.SetMapper(blobbyMapper) blobby.GetProperty().SetDiffuseColor(GetRGBColor('banana')) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer()
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape, mask_dtype, roi, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, from_binary, algorithm, imagedata_resolution, fill_border_holes): log_path = tempfile.mktemp('vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) pad_bottom = (roi.start == 0) pad_top = (roi.stop >= shape[0]) if fill_border_holes: padding = (1, 1, pad_bottom) else: padding = (0, 0, 0) if from_binary: mask = numpy.memmap(mask_filename, mode='r', dtype=mask_dtype, shape=mask_shape) if fill_border_holes: a_mask = pad_image(mask[roi.start + 1:roi.stop + 1, 1:, 1:], 0, pad_bottom, pad_top) else: a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:]) image = converters.to_vtk(a_mask, spacing, roi.start, "AXIAL", padding=padding) del a_mask else: image = numpy.memmap(filename, mode='r', dtype=dtype, shape=shape) mask = numpy.memmap(mask_filename, mode='r', dtype=mask_dtype, shape=mask_shape) if fill_border_holes: a_image = pad_image(image[roi], numpy.iinfo(image.dtype).min, pad_bottom, pad_top) else: a_image = numpy.array(image[roi]) # if z_iadd: # a_image[0, 1:-1, 1:-1] = image[0] # if z_eadd: # a_image[-1, 1:-1, 1:-1] = image[-1] if algorithm == u'InVesalius 3.b2': a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:]) a_image[a_mask == 1] = a_image.min() - 1 a_image[a_mask == 254] = (min_value + max_value) / 2.0 image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding) gauss = vtk.vtkImageGaussianSmooth() gauss.SetInputData(image) gauss.SetRadiusFactor(0.3) gauss.ReleaseDataFlagOn() gauss.Update() del image image = gauss.GetOutput() del gauss del a_mask else: # if z_iadd: # origin = -spacing[0], -spacing[1], -spacing[2] # else: # origin = 0, -spacing[1], -spacing[2] image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding) del a_image if imagedata_resolution: image = ResampleImage3D(image, imagedata_resolution) flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.ReleaseDataFlagOn() flip.Update() # writer = vtk.vtkXMLImageDataWriter() # writer.SetFileName('/tmp/camboja.vti') # writer.SetInputData(flip.GetOutput()) # writer.Write() del image image = flip.GetOutput() del flip contour = vtk.vtkContourFilter() contour.SetInputData(image) if from_binary: contour.SetValue(0, 127) # initial threshold else: contour.SetValue(0, min_value) # initial threshold contour.SetValue(1, max_value) # final threshold # contour.ComputeScalarsOn() # contour.ComputeGradientsOn() # contour.ComputeNormalsOn() contour.ReleaseDataFlagOn() contour.Update() polydata = contour.GetOutput() del image del contour filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop)) writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(polydata) writer.SetFileName(filename) writer.Write() print("Writing piece", roi, "to", filename) print("MY PID MC", os.getpid()) return filename
renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create pipeline # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName("" + str(VTK_DATA_ROOT) + "/Data/combxyz.bin") pl3d.SetQFileName("" + str(VTK_DATA_ROOT) + "/Data/combq.bin") pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() output = pl3d.GetOutput().GetBlock(0) vx = vtk.vtkExtractVectorComponents() vx.SetInputData(output) vx.Update() isoVx = vtk.vtkContourFilter() isoVx.SetInputData(vx.GetVxComponent()) isoVx.SetValue(0, .38) normalsVx = vtk.vtkPolyDataNormals() normalsVx.SetInputConnection(isoVx.GetOutputPort()) normalsVx.SetFeatureAngle(45) isoVxMapper = vtk.vtkPolyDataMapper() isoVxMapper.SetInputConnection(normalsVx.GetOutputPort()) isoVxMapper.ScalarVisibilityOff() isoVxMapper.ImmediateModeRenderingOn() isoVxActor = vtk.vtkActor() isoVxActor.SetMapper(isoVxMapper) isoVxActor.GetProperty().SetColor(1, 0.7, 0.6) vy = vtk.vtkExtractVectorComponents() vy.SetInputData(output) vy.Update()
def main(): colors = vtk.vtkNamedColors() # Create and populate the AMR dataset # The dataset should look like # Level 0 # uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9) # Level 1 - refinement ratio : 2 # uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9) # uniform grid, dimensions 11, 11, 11, AMR box (10, 10, 10) - (19, 19, 19) # Use MakeScalars() above to fill the scalar arrays amr = vtk.vtkOverlappingAMR() blocksPerLevel = [1, 2] amr.Initialize(2, blocksPerLevel) origin = [0.0, 0.0, 0.0] spacing = [1.0, 1.0, 1.0] dims = [11, 11, 11] ug1 = vtk.vtkUniformGrid() # Geometry ug1.SetOrigin(origin) ug1.SetSpacing(spacing) ug1.SetDimensions(dims) # Data scalars = vtk.vtkFloatArray() ug1.GetPointData().SetScalars(scalars) MakeScalars(dims, origin, spacing, scalars) lo = [0, 0, 0] hi = [9, 9, 9] box1 = vtk.vtkAMRBox() amr.SetAMRBox(0, 0, box1) amr.SetDataSet(0, 0, ug1) spacing2 = [0.5, 0.5, 0.5] ug2 = vtk.vtkUniformGrid() # Geometry ug2.SetOrigin(origin) ug2.SetSpacing(spacing2) ug2.SetDimensions(dims) # Data scalars = vtk.vtkFloatArray() ug2.GetPointData().SetScalars(scalars) MakeScalars(dims, origin, spacing2, scalars) lo2 = [0, 0, 0] hi2 = [9, 9, 9] box2 = vtk.vtkAMRBox() amr.SetAMRBox(1, 0, box2) amr.SetDataSet(1, 0, ug2) origin3 = [5, 5, 5] ug3 = vtk.vtkUniformGrid() # Geometry ug3.SetOrigin(origin3) ug3.SetSpacing(spacing2) ug3.SetDimensions(dims) # Data scalars = vtk.vtkFloatArray() ug3.GetPointData().SetScalars(scalars) MakeScalars(dims, origin3, spacing2, scalars) lo3 = [10, 10, 10] hi3 = [19, 19, 19] box3 = vtk.vtkAMRBox() amr.SetAMRBox(1, 1, box3) amr.SetDataSet(1, 1, ug3) amr.SetRefinementRatio(0, 2) # Render the amr data here. of = vtk.vtkOutlineFilter() of.SetInputData(amr) geomFilter = vtk.vtkCompositeDataGeometryFilter() geomFilter.SetInputConnection(of.GetOutputPort()) # Create an iso-surface - at 10. cf = vtk.vtkContourFilter() cf.SetInputData(amr) cf.SetNumberOfContours(1) cf.SetValue(0, 10.0) geomFilter2 = vtk.vtkCompositeDataGeometryFilter() geomFilter2.SetInputConnection(cf.GetOutputPort()) # Create the render window, renderer, and interactor. aren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Associate the geometry with a mapper and the mapper to an actor. mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(geomFilter.GetOutputPort()) actor1 = vtk.vtkActor() actor1.GetProperty().SetColor(colors.GetColor3d("Yellow")) actor1.SetMapper(mapper) # Associate the geometry with a mapper and the mapper to an actor. mapper2 = vtk.vtkPolyDataMapper() mapper2.SetInputConnection(geomFilter2.GetOutputPort()) actor2 = vtk.vtkActor() actor2.SetMapper(mapper2) # Add the actor to the renderer and start handling events. aren.AddActor(actor1) aren.AddActor(actor2) aren.SetBackground(colors.GetColor3d("CornflowerBlue")) renWin.Render() iren.Start()
if RESAMPLE: KNEE_COLOR_FILE = "colorationBoneResampled.vtp" resample = vtk.vtkImageResample() resample.SetInputData(reader.GetOutput()) resample.SetDimensionality(3) resample.SetMagnificationFactors(0.5, 0.5, 0.5) imageData = resample.GetOutputPort() else: KNEE_COLOR_FILE = "colorationBone.vtp" imageData = reader.GetOutputPort() # utulise le volume pour en faire une isosurface pour l'os boneSurface = vtk.vtkContourFilter() boneSurface.SetInputConnection(imageData) boneSurface.SetValue(0, 73) boneSurface.ComputeScalarsOff() boneSurface.Update() # utulise le volume pour en faire une isosurface pour la peau skinSurface = vtk.vtkContourFilter() skinSurface.SetInputConnection(imageData) skinSurface.SetValue(0, 40) skinSurface.ComputeScalarsOff() skinSurface.Update() # création des mappers boneMapper = vtk.vtkPolyDataMapper() boneMapper.SetInputConnection(boneSurface.GetOutputPort())
def main(): xyzFile, qFile = get_program_parameters() colors = vtk.vtkNamedColors() # Create the RenderWindow, Renderer and Interactor. # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create the pipeline. # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(xyzFile) pl3d.SetQFileName(qFile) pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() iso = vtk.vtkContourFilter() iso.SetInputData(pl3d.GetOutput().GetBlock(0)) iso.SetValue(0, 0.38) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(iso.GetOutputPort()) normals.SetFeatureAngle(45) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(normals.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(colors.GetColor3d('WhiteSmoke')) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputConnection(pl3d.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Add the actors to the renderer, set the background and size. # ren1.AddActor(outlineActor) ren1.AddActor(isoActor) ren1.SetBackground(colors.GetColor3d('DarkSlateGray')) renWin.SetSize(640, 480) renWin.SetWindowName('CombustorIsosurface') ren1.GetActiveCamera().SetFocalPoint(9.71821, 0.458166, 29.3999) ren1.GetActiveCamera().SetPosition(2.7439, -37.3196, 38.7167) ren1.GetActiveCamera().SetViewUp(-0.16123, 0.264271, 0.950876) ren1.GetActiveCamera().Zoom(1.3) ren1.ResetCameraClippingRange() # Render the image. # renWin.Render() iren.Start()
def from_volume(cls, lattice, colour, args, *args_, **kwargs_): """Initialiase a VTKMesh object from a binarised ``numpy.ndarray`` :param lattice: a mask (3D matrix) :type lattice: ``numpy.ndarray`` :param colour: the segment colour :type colour: ``sfftkrw.SFFRGBA`` :param args: parsed arguments :type args: ``argparse.Namespace`` :return vtkmesh: an VTKMesh object :rtype vtkmesh: ``VTKMesh`` """ vtkmesh = cls(colour, args, *args_, **kwargs_) # try and figure out the lattice value if not specified if args.mask_value is not None: mask_value = args.mask_value else: mask_values = filter(lambda x: x != 0, set(lattice.flatten().tolist())) if len(mask_values) == 1: mask_value = mask_values[0] else: # use the mean mask_value = sum(mask_values) / len(mask_values) vol = vtk.vtkImageData() z_size, y_size, x_size = lattice.shape vol.SetExtent(0, x_size - 1, 0, y_size - 1, 0, z_size - 1) # vtkmesh.vol_extent = 0, x_size - 1, 0, y_size - 1, 0, z_size - 1 vol.SetOrigin(0.0, 0.0, 0.0) sp_x = 1.0 # /(x_size - 1) sp_y = 1.0 # /(y_size - 1) sp_z = 1.0 # /(z_size - 1) vol.SetSpacing(sp_x, sp_y, sp_z) vol.AllocateScalars(vtk.VTK_FLOAT, 1) voxels = vtk.vtkFloatArray() voxels.SetNumberOfComponents(1) for m in lattice.flatten().tolist(): voxels.InsertNextValue(float(m)) vol.GetPointData().SetScalars(voxels) # convert the volume to a surface contours = vtk.vtkContourFilter() contours.SetInputData(vol) contours.SetValue(0, mask_value) contours.Update() contoursOutput = contours.GetOutput() vtkmesh.vtk_obj.SetPoints(contoursOutput.GetPoints()) vtkmesh.vtk_obj.SetPolys(contoursOutput.GetPolys()) # triangulate triangleMesh = vtk.vtkTriangleFilter() triangleMesh.SetInputData(contoursOutput) triangleMesh.Update() triangleMeshOutput = triangleMesh.GetOutput() # decimate decimateMesh = vtk.vtkDecimatePro() decimateMesh.SetInputData(triangleMeshOutput) decimateMesh.SetTargetReduction(0.9) decimateMesh.PreserveTopologyOn() decimateMesh.Update() decimateMeshOutput = decimateMesh.GetOutput() # smooth smoothedMesh = vtk.vtkSmoothPolyDataFilter() smoothedMesh.SetInputData(decimateMeshOutput) smoothedMesh.SetNumberOfIterations(200) smoothedMesh.Update() smoothedMeshOutput = smoothedMesh.GetOutput() # triangle strips triangleStrips = vtk.vtkStripper() triangleStrips.SetInputData(smoothedMeshOutput) triangleStrips.SetMaximumLength(1000) triangleStrips.Update() triangleStripsOutput = triangleStrips.GetOutput() # finally set things if not args.normals_off: # normals normals = vtk.vtkPolyDataNormals() normals.SetInputData(triangleStripsOutput) # normals.ComputeCellNormalsOn() normals.ConsistencyOn() normals.AutoOrientNormalsOn() normals.ComputePointNormalsOn() normals.SplittingOff() normals.SetFeatureAngle(240.0) normals.Update() normalsOutput = normals.GetOutput() # print(vtkmesh_n.GetPointData().GetNormals()) vtkmesh.vtk_obj.SetPoints(normals.GetOutput().GetPoints()) vtkmesh.vtk_obj.SetPolys(normals.GetOutput().GetPolys()) vtkmesh.vtk_obj.GetPointData().SetNormals( normalsOutput.GetPointData().GetNormals()) return vtkmesh else: vtkmesh.vtk_obj.SetPoints(triangleStripsOutput.GetPoints()) vtkmesh.vtk_obj.SetPolys(triangleStripsOutput.GetPolys()) return vtkmesh