def exportWindow(fileoutput, binary=False, speed=None, html=True): ''' Exporter which writes out the renderered scene into an OBJ or X3D file. X3D is an XML-based format for representation 3D scenes (similar to VRML). Check out http://www.web3d.org/x3d for more details. :param float speed: set speed for x3d files. :param bool html: generate a test html page for x3d files. |export_x3d| |export_x3d.py|_ `generated webpage <https://vtkplotter.embl.es/examples/embryo.html>`_ See also: FEniCS test `webpage <https://vtkplotter.embl.es/examples/fenics_elasticity.html>`_. ''' fr = fileoutput.lower() if ".obj" in fr: w = vtk.vtkOBJExporter() w.SetInputData(settings.plotter_instance.window) w.Update() colors.printc("~save Saved file:", fileoutput, c="g") elif ".x3d" in fr: exporter = vtk.vtkX3DExporter() exporter.SetBinary(binary) exporter.FastestOff() if speed: exporter.SetSpeed(speed) exporter.SetInput(settings.plotter_instance.window) exporter.SetFileName(fileoutput) exporter.Update() exporter.Write() if not html: return from vtkplotter.docs import x3d_html x3d_html = x3d_html.replace("~fileoutput", fileoutput) wsize = settings.plotter_instance.window.GetSize() x3d_html = x3d_html.replace("~width", str(wsize[0])) x3d_html = x3d_html.replace("~height", str(wsize[1])) #b = settings.plotter_instance.renderer.ComputeVisiblePropBounds() #s = max(b[1] - b[0], b[3] - b[2], b[5] - b[4]) #c = (b[1] + b[0])/2, (b[3] + b[2])/2, (b[5] + b[4])/2 #x3d_html = x3d_html.replace("~size", str(s*2)) #x3d_html = x3d_html.replace("~center", str(c[0])+" "+str(c[1])+" "+str(c[2])) outF = open(fileoutput.replace('.x3d', '.html'), "w") outF.write(x3d_html) outF.close() colors.printc("~save Saved files:", fileoutput, fileoutput.replace('.x3d', '.html'), c="g") return
def exportScene(scene, filePrefix, ext='x3d', names=[]): renWin = scene['window'] ren = scene['renderer'] if ext == 'x3d': writer = vtk.vtkX3DExporter() writer.SetInput(renWin) writer.SetFileName(filePrefix + '.x3d') writer.Update() writer.Write() elif ext == 'obj': writer = vtk.vtkOBJExporter() writer.SetFilePrefix(filePrefix) writer.SetInput(renWin) writer.Write() elif ext == 'vtm': actors = ren.GetActors() actors.InitTraversal() mb = vtk.vtkMultiBlockDataSet() mb.SetNumberOfBlocks(actors.GetNumberOfItems()) for i in range(actors.GetNumberOfItems()): actor = actors.GetNextItem() block = actor.GetMapper().GetInput() mb.GetMetaData(i).Set(vtk.vtkCompositeDataSet.NAME(), names[i]) mb.SetBlock(i, block) writer = vtk.vtkXMLMultiBlockDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(mb) else: writer.SetInputData(mb) writer.SetFileName(filePrefix + '.vtm') writer.Write()
def setup_brain(render_window, renderer, name): file = name + ".nii.gz" # print(file) brain = NiiObject() brain.file = file brain.reader = read_volume(brain.file) brain.labels.append( NiiLabel(BRAIN_COLORS[0], BRAIN_OPACITY, BRAIN_SMOOTHNESS)) brain.labels[0].extractor = create_brain_extractor(brain) brain.extent = brain.reader.GetDataExtent() scalar_range = brain.reader.GetOutput().GetScalarRange() bw_lut = vtk.vtkLookupTable() bw_lut.SetTableRange(scalar_range) bw_lut.SetSaturationRange(0, 0) bw_lut.SetHueRange(0, 0) bw_lut.SetValueRange(0, 2) bw_lut.Build() # print('step1') view_colors = vtk.vtkImageMapToColors() view_colors.SetInputConnection(brain.reader.GetOutputPort()) view_colors.SetLookupTable(bw_lut) view_colors.Update() brain.image_mapper = view_colors brain.scalar_range = scalar_range # print('step2') add_surface_rendering(brain, 0, sum(scalar_range) / 2) # render index, default extractor value renderer.AddActor(brain.labels[0].actor) objWriter = vtk.vtkOBJExporter() objWriter.SetFilePrefix(name) objWriter.SetInput(render_window) objWriter.Write()
def write_obj(infile='./data/itokawa_low.obj', outfile='./data/point_clouds/itokawa_low_vtkwriter'): """Read from a OBJ and then write to a different one """ reader = vtk.vtkOBJReader() reader.SetFileName(infile) # write the stl file to a disk objWriter = vtk.vtkOBJExporter() objWriter.SetFilePrefix(outfile) mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(reader.GetOutput()) else: mapper.SetInputConnection(reader.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.AddActor(actor) iren.Initialize() renWin.Render() iren.Start() objWriter.SetRenderWindow(renWin) objWriter.Write()
def save_wavefront (self, file_name=""): """Save scene to a Wavefront OBJ file. Two files are generated. One with a .obj extension and another with a .mtl extension which contains the material proerties. Keyword Arguments: file_name -- Optional file name to save to (default ''). If no file name is given then a dialog will pop up asking for the file name. """ debug ("In RenderWindow::save_wavefront ()") if not file_name: file_name = tk_fsave (title="Export to Wavefront OBJ", initialdir=Common.config.initial_dir, defaultextension=".obj", filetypes=[("Wavefront OBJ files", "*.obj"), ("All files", "*")]) if len (file_name) != 0: Common.state.busy () ex = vtk.vtkOBJExporter () self.lift () ex.SetInput (self.renwin) f_pref = os.path.splitext (file_name)[0] ex.SetFilePrefix(f_pref) ex.Write () Common.state.idle ()
def write(obj, fileoutput): ''' Write 3D object to file. Possile extensions are: .vtk, .ply, .obj, .stl, .byu, .vtp ''' fr = fileoutput.lower() if '.vtk' in fr: w = vtk.vtkPolyDataWriter() elif '.ply' in fr: w = vtk.vtkPLYWriter() elif '.obj' in fr: w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace('.obj', '')) vc.printc('Please use write(vp.renderWin)', 3) w.SetInput(obj) w.Update() vc.printc("Saved file: " + fileoutput, 'g') return elif '.stl' in fr: w = vtk.vtkSTLWriter() elif '.byu' in fr or '.g' in fr: w = vtk.vtkBYUWriter() elif '.vtp' in fr: w = vtk.vtkXMLPolyDataWriter() else: vc.printc('Unavailable format in file ' + fileoutput, c='r') exit(1) try: vu.setInput(w, vu.polydata(obj, True)) w.SetFileName(fileoutput) w.Write() vc.printc("Saved file: " + fileoutput, 'g') except: vc.printc("Error saving: " + fileoutput, 'r')
def OnExportSurface(self, pubsub_evt): filename, filetype = pubsub_evt.data fileprefix = filename.split(".")[-2] renwin = self.interactor.GetRenderWindow() if filetype == const.FILETYPE_RIB: writer = vtk.vtkRIBExporter() writer.SetFilePrefix(fileprefix) writer.SetTexturePrefix(fileprefix) writer.SetInput(renwin) writer.Write() elif filetype == const.FILETYPE_VRML: writer = vtk.vtkVRMLExporter() writer.SetFileName(filename) writer.SetInput(renwin) writer.Write() elif filetype == const.FILETYPE_X3D: writer = vtk.vtkX3DExporter() writer.SetInput(renwin) writer.SetFileName(filename) writer.Update() writer.Write() elif filetype == const.FILETYPE_OBJ: writer = vtk.vtkOBJExporter() writer.SetFilePrefix(fileprefix) writer.SetInput(renwin) writer.Write() elif filetype == const.FILETYPE_IV: writer = vtk.vtkIVExporter() writer.SetFileName(filename) writer.SetInput(renwin) writer.Write()
def _WriteData(self): objExporter = vtk.vtkOBJExporter(); objExporter.SetFilePrefix(self._FileName[0:self._FileName.rindex(".")]); import vtkDisplay; displayer = vtkDisplay.PolyDisplay(); displayer.addPolyData(self._Data); objExporter.SetRenderWindow(displayer.getWindow()); objExporter.Write();
def save_obj(rw, dir, name): exporter = vtk.vtkOBJExporter() if not os.path.isdir(dir): os.makedirs(dir) path = "%s/%s" % (dir, name) exporter.SetFilePrefix(path) exporter.SetRenderWindow(rw) exporter.Write()
def write_obj(self, postscript=''): output_filename = self.filename render_window = self.visualize_mesh(False) print('Saving PolyData in the OBJ file...') obj_writer = vtk.vtkOBJExporter() obj_writer.SetRenderWindow(render_window) obj_writer.SetFilePrefix(output_filename + postscript) obj_writer.Write() print('{} written succesfully'.format(output_filename + postscript + '.obj'))
def __init__(self): """ Initializes VTK objects for rendering. """ # vtk objects for rendering self.vtkrenderer = vtk.vtkRenderer() self.vtkcamera = vtk.vtkCamera() self.vtkcamera.SetPosition(self.camera_pos) self.vtkcamera.SetFocalPoint(0, 0, 0) self.vtkcamera.SetViewUp(self.camera_up) # lighting self.light1 = vtk.vtkLight() self.light1.SetIntensity(.4) self.light1.SetPosition(10, -10, 10) self.light1.SetDiffuseColor(1, 1, 1) self.light2 = vtk.vtkLight() self.light2.SetIntensity(.4) self.light2.SetPosition(-10, -10, 10) self.light2.SetDiffuseColor(1, 1, 1) self.light3 = vtk.vtkLight() self.light3.SetIntensity(.4) self.light3.SetPosition(10, -10, -10) self.light3.SetDiffuseColor(1, 1, 1) self.light4 = vtk.vtkLight() self.light4.SetIntensity(.4) self.light4.SetPosition(-10, -10, -10) self.light4.SetDiffuseColor(1, 1, 1) self.vtkrenderer.AddLight(self.light1) self.vtkrenderer.AddLight(self.light2) self.vtkrenderer.AddLight(self.light3) self.vtkrenderer.AddLight(self.light4) self.vtkrenderer.SetBackground(0.1, 0.1, 0.1) # Background color self.vtkrender_window = vtk.vtkRenderWindow() self.vtkrender_window.AddRenderer(self.vtkrenderer) self.vtkrender_window.SetSize(self.render_size) self.vtkrender_window_interactor = vtk.vtkRenderWindowInteractor() self.vtkrender_window_interactor.SetRenderWindow(self.vtkrender_window) # vtk objects for reading, and rendering object parts self.part_source = vtk.vtkCubeSource() self.part_output = self.part_source.GetOutput() self.part_mapper = vtk.vtkPolyDataMapper() self.part_mapper.SetInput(self.part_output) # exporters self.vtkvrml_exporter = vtk.vtkVRMLExporter() self.vtkobj_exporter = vtk.vtkOBJExporter() self.stl_writer = vtk.vtkSTLWriter()
def write(obj, fileoutput): ''' Write 3D object to file. Possile extensions are: .vtk, .ply, .obj, .stl, .byu, .vtp, .xyz, .tif ''' fr = fileoutput.lower() if '.vtk' in fr: w = vtk.vtkPolyDataWriter() elif '.ply' in fr: w = vtk.vtkPLYWriter() elif '.stl' in fr: w = vtk.vtkSTLWriter() elif '.vtp' in fr: w = vtk.vtkXMLPolyDataWriter() elif '.xyz' in fr: w = vtk.vtkSimplePointsWriter() elif '.byu' in fr or fr.endswith('.g'): w = vtk.vtkBYUWriter() elif '.obj' in fr: obj = vu.polydata(obj, True) w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace('.obj', '')) vc.printc('Please use write(vp.renderWin)', c=3) w.SetInput(obj) w.Update() vc.printc("Saved file: " + fileoutput, c='g') return elif '.tif' in fr: wr = vtk.vtkTIFFWriter() wr.SetFileDimensionality(len(obj.GetDimensions())) vu.setInput(wr, obj) wr.SetFileName(fileoutput) wr.Write() vc.printc("TIFF stack saved as: " + fileoutput, c='g') return else: vc.printc('Unavailable format in file ' + fileoutput, c='r') exit(1) try: obj = vu.polydata(obj, True) vu.setInput(w, vu.polydata(obj, True)) w.SetFileName(fileoutput) w.Write() vc.printc("Saved file: " + fileoutput, c='g') except: vc.printc("Error saving: " + fileoutput, c='r')
def render_mesh(objects, dim, saveAs=None): actors = [] for i, o in enumerate(objects): actors.append( create_actor(o['data'], dim, o['color'], o['opacity'], o['name'], saveAs=saveAs)) window = vtk.vtkRenderWindow() window.SetSize(500, 500) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(window) renderer = vtk.vtkRenderer() renderer.SetBackground(1.0, 1.0, 1.0) window.AddRenderer(renderer) for actor in actors: renderer.AddActor(actor) # A simple function to be called when the user decides to quit the application. def exitCheck(obj, event): if obj.GetEventPending() != 0: obj.SetAbortRender(1) window.AddObserver('AbortCheckEvent', exitCheck) interactor.Initialize() window.Render() interactor.Start() # Create mtl and obj file if saveAs: exporter = vtk.vtkOBJExporter() exporter.SetRenderWindow(window) exporter.SetFilePrefix(os.path.join('./output/models', saveAs)) exporter.Write()
def testCells(self): # Demonstrates all cell types # # NOTE: the use of NewInstance/DeepCopy is included to increase # regression coverage. It is not required in most applications. ren = vtk.vtkRenderer() # turn off all cullers ren.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(300, 150) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # create a scene with one of each cell type # Voxel voxelPoints = vtk.vtkPoints() voxelPoints.SetNumberOfPoints(8) voxelPoints.InsertPoint(0, 0, 0, 0) voxelPoints.InsertPoint(1, 1, 0, 0) voxelPoints.InsertPoint(2, 0, 1, 0) voxelPoints.InsertPoint(3, 1, 1, 0) voxelPoints.InsertPoint(4, 0, 0, 1) voxelPoints.InsertPoint(5, 1, 0, 1) voxelPoints.InsertPoint(6, 0, 1, 1) voxelPoints.InsertPoint(7, 1, 1, 1) aVoxel = vtk.vtkVoxel() 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) bVoxel = aVoxel.NewInstance() bVoxel.DeepCopy(aVoxel) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper) aVoxelActor.GetProperty().BackfaceCullingOn() # Hexahedron hexahedronPoints = vtk.vtkPoints() hexahedronPoints.SetNumberOfPoints(8) hexahedronPoints.InsertPoint(0, 0, 0, 0) hexahedronPoints.InsertPoint(1, 1, 0, 0) hexahedronPoints.InsertPoint(2, 1, 1, 0) hexahedronPoints.InsertPoint(3, 0, 1, 0) hexahedronPoints.InsertPoint(4, 0, 0, 1) hexahedronPoints.InsertPoint(5, 1, 0, 1) hexahedronPoints.InsertPoint(6, 1, 1, 1) hexahedronPoints.InsertPoint(7, 0, 1, 1) aHexahedron = vtk.vtkHexahedron() aHexahedron.GetPointIds().SetId(0, 0) aHexahedron.GetPointIds().SetId(1, 1) aHexahedron.GetPointIds().SetId(2, 2) aHexahedron.GetPointIds().SetId(3, 3) aHexahedron.GetPointIds().SetId(4, 4) aHexahedron.GetPointIds().SetId(5, 5) aHexahedron.GetPointIds().SetId(6, 6) aHexahedron.GetPointIds().SetId(7, 7) bHexahedron = aHexahedron.NewInstance() bHexahedron.DeepCopy(aHexahedron) aHexahedronGrid = vtk.vtkUnstructuredGrid() aHexahedronGrid.Allocate(1, 1) aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds()) aHexahedronGrid.SetPoints(hexahedronPoints) aHexahedronMapper = vtk.vtkDataSetMapper() aHexahedronMapper.SetInputData(aHexahedronGrid) aHexahedronActor = vtk.vtkActor() aHexahedronActor.SetMapper(aHexahedronMapper) aHexahedronActor.AddPosition(2, 0, 0) aHexahedronActor.GetProperty().BackfaceCullingOn() # Tetra tetraPoints = vtk.vtkPoints() tetraPoints.SetNumberOfPoints(4) tetraPoints.InsertPoint(0, 0, 0, 0) tetraPoints.InsertPoint(1, 1, 0, 0) tetraPoints.InsertPoint(2, .5, 1, 0) tetraPoints.InsertPoint(3, .5, .5, 1) aTetra = vtk.vtkTetra() aTetra.GetPointIds().SetId(0, 0) aTetra.GetPointIds().SetId(1, 1) aTetra.GetPointIds().SetId(2, 2) aTetra.GetPointIds().SetId(3, 3) bTetra = aTetra.NewInstance() bTetra.DeepCopy(aTetra) aTetraGrid = vtk.vtkUnstructuredGrid() aTetraGrid.Allocate(1, 1) aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds()) aTetraGrid.SetPoints(tetraPoints) aTetraCopy = vtk.vtkUnstructuredGrid() aTetraCopy.ShallowCopy(aTetraGrid) aTetraMapper = vtk.vtkDataSetMapper() aTetraMapper.SetInputData(aTetraCopy) aTetraActor = vtk.vtkActor() aTetraActor.SetMapper(aTetraMapper) aTetraActor.AddPosition(4, 0, 0) aTetraActor.GetProperty().BackfaceCullingOn() # Wedge wedgePoints = vtk.vtkPoints() wedgePoints.SetNumberOfPoints(6) wedgePoints.InsertPoint(0, 0, 1, 0) wedgePoints.InsertPoint(1, 0, 0, 0) wedgePoints.InsertPoint(2, 0, .5, .5) wedgePoints.InsertPoint(3, 1, 1, 0) wedgePoints.InsertPoint(4, 1, 0, 0) wedgePoints.InsertPoint(5, 1, .5, .5) aWedge = vtk.vtkWedge() aWedge.GetPointIds().SetId(0, 0) aWedge.GetPointIds().SetId(1, 1) aWedge.GetPointIds().SetId(2, 2) aWedge.GetPointIds().SetId(3, 3) aWedge.GetPointIds().SetId(4, 4) aWedge.GetPointIds().SetId(5, 5) bWedge = aWedge.NewInstance() bWedge.DeepCopy(aWedge) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeCopy = vtk.vtkUnstructuredGrid() aWedgeCopy.DeepCopy(aWedgeGrid) aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeCopy) aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.AddPosition(6, 0, 0) aWedgeActor.GetProperty().BackfaceCullingOn() # Pyramid pyramidPoints = vtk.vtkPoints() pyramidPoints.SetNumberOfPoints(5) pyramidPoints.InsertPoint(0, 0, 0, 0) pyramidPoints.InsertPoint(1, 1, 0, 0) pyramidPoints.InsertPoint(2, 1, 1, 0) pyramidPoints.InsertPoint(3, 0, 1, 0) pyramidPoints.InsertPoint(4, .5, .5, 1) aPyramid = vtk.vtkPyramid() aPyramid.GetPointIds().SetId(0, 0) aPyramid.GetPointIds().SetId(1, 1) aPyramid.GetPointIds().SetId(2, 2) aPyramid.GetPointIds().SetId(3, 3) aPyramid.GetPointIds().SetId(4, 4) bPyramid = aPyramid.NewInstance() bPyramid.DeepCopy(aPyramid) aPyramidGrid = vtk.vtkUnstructuredGrid() aPyramidGrid.Allocate(1, 1) aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds()) aPyramidGrid.SetPoints(pyramidPoints) aPyramidMapper = vtk.vtkDataSetMapper() aPyramidMapper.SetInputData(aPyramidGrid) aPyramidActor = vtk.vtkActor() aPyramidActor.SetMapper(aPyramidMapper) aPyramidActor.AddPosition(8, 0, 0) aPyramidActor.GetProperty().BackfaceCullingOn() # Pixel pixelPoints = vtk.vtkPoints() pixelPoints.SetNumberOfPoints(4) pixelPoints.InsertPoint(0, 0, 0, 0) pixelPoints.InsertPoint(1, 1, 0, 0) pixelPoints.InsertPoint(2, 0, 1, 0) pixelPoints.InsertPoint(3, 1, 1, 0) aPixel = vtk.vtkPixel() aPixel.GetPointIds().SetId(0, 0) aPixel.GetPointIds().SetId(1, 1) aPixel.GetPointIds().SetId(2, 2) aPixel.GetPointIds().SetId(3, 3) bPixel = aPixel.NewInstance() bPixel.DeepCopy(aPixel) aPixelGrid = vtk.vtkUnstructuredGrid() aPixelGrid.Allocate(1, 1) aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds()) aPixelGrid.SetPoints(pixelPoints) aPixelMapper = vtk.vtkDataSetMapper() aPixelMapper.SetInputData(aPixelGrid) aPixelActor = vtk.vtkActor() aPixelActor.SetMapper(aPixelMapper) aPixelActor.AddPosition(0, 0, 2) aPixelActor.GetProperty().BackfaceCullingOn() # Quad quadPoints = vtk.vtkPoints() quadPoints.SetNumberOfPoints(4) quadPoints.InsertPoint(0, 0, 0, 0) quadPoints.InsertPoint(1, 1, 0, 0) quadPoints.InsertPoint(2, 1, 1, 0) quadPoints.InsertPoint(3, 0, 1, 0) aQuad = vtk.vtkQuad() aQuad.GetPointIds().SetId(0, 0) aQuad.GetPointIds().SetId(1, 1) aQuad.GetPointIds().SetId(2, 2) aQuad.GetPointIds().SetId(3, 3) bQuad = aQuad.NewInstance() bQuad.DeepCopy(aQuad) aQuadGrid = vtk.vtkUnstructuredGrid() aQuadGrid.Allocate(1, 1) aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds()) aQuadGrid.SetPoints(quadPoints) aQuadMapper = vtk.vtkDataSetMapper() aQuadMapper.SetInputData(aQuadGrid) aQuadActor = vtk.vtkActor() aQuadActor.SetMapper(aQuadMapper) aQuadActor.AddPosition(2, 0, 2) aQuadActor.GetProperty().BackfaceCullingOn() # Triangle trianglePoints = vtk.vtkPoints() trianglePoints.SetNumberOfPoints(3) trianglePoints.InsertPoint(0, 0, 0, 0) trianglePoints.InsertPoint(1, 1, 0, 0) trianglePoints.InsertPoint(2, .5, .5, 0) triangleTCoords = vtk.vtkFloatArray() triangleTCoords.SetNumberOfComponents(2) triangleTCoords.SetNumberOfTuples(3) triangleTCoords.InsertTuple2(0, 1, 1) triangleTCoords.InsertTuple2(1, 2, 2) triangleTCoords.InsertTuple2(2, 3, 3) aTriangle = vtk.vtkTriangle() aTriangle.GetPointIds().SetId(0, 0) aTriangle.GetPointIds().SetId(1, 1) aTriangle.GetPointIds().SetId(2, 2) bTriangle = aTriangle.NewInstance() bTriangle.DeepCopy(aTriangle) aTriangleGrid = vtk.vtkUnstructuredGrid() aTriangleGrid.Allocate(1, 1) aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds()) aTriangleGrid.SetPoints(trianglePoints) aTriangleGrid.GetPointData().SetTCoords(triangleTCoords) aTriangleMapper = vtk.vtkDataSetMapper() aTriangleMapper.SetInputData(aTriangleGrid) aTriangleActor = vtk.vtkActor() aTriangleActor.SetMapper(aTriangleMapper) aTriangleActor.AddPosition(4, 0, 2) aTriangleActor.GetProperty().BackfaceCullingOn() # Polygon polygonPoints = vtk.vtkPoints() polygonPoints.SetNumberOfPoints(4) polygonPoints.InsertPoint(0, 0, 0, 0) polygonPoints.InsertPoint(1, 1, 0, 0) polygonPoints.InsertPoint(2, 1, 1, 0) polygonPoints.InsertPoint(3, 0, 1, 0) aPolygon = vtk.vtkPolygon() aPolygon.GetPointIds().SetNumberOfIds(4) aPolygon.GetPointIds().SetId(0, 0) aPolygon.GetPointIds().SetId(1, 1) aPolygon.GetPointIds().SetId(2, 2) aPolygon.GetPointIds().SetId(3, 3) bPolygon = aPolygon.NewInstance() bPolygon.DeepCopy(aPolygon) aPolygonGrid = vtk.vtkUnstructuredGrid() aPolygonGrid.Allocate(1, 1) aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds()) aPolygonGrid.SetPoints(polygonPoints) aPolygonMapper = vtk.vtkDataSetMapper() aPolygonMapper.SetInputData(aPolygonGrid) aPolygonActor = vtk.vtkActor() aPolygonActor.SetMapper(aPolygonMapper) aPolygonActor.AddPosition(6, 0, 2) aPolygonActor.GetProperty().BackfaceCullingOn() # Triangle Strip triangleStripPoints = vtk.vtkPoints() triangleStripPoints.SetNumberOfPoints(5) triangleStripPoints.InsertPoint(0, 0, 1, 0) triangleStripPoints.InsertPoint(1, 0, 0, 0) triangleStripPoints.InsertPoint(2, 1, 1, 0) triangleStripPoints.InsertPoint(3, 1, 0, 0) triangleStripPoints.InsertPoint(4, 2, 1, 0) triangleStripTCoords = vtk.vtkFloatArray() triangleStripTCoords.SetNumberOfComponents(2) triangleStripTCoords.SetNumberOfTuples(3) triangleStripTCoords.InsertTuple2(0, 1, 1) triangleStripTCoords.InsertTuple2(1, 2, 2) triangleStripTCoords.InsertTuple2(2, 3, 3) triangleStripTCoords.InsertTuple2(3, 4, 4) triangleStripTCoords.InsertTuple2(4, 5, 5) aTriangleStrip = vtk.vtkTriangleStrip() aTriangleStrip.GetPointIds().SetNumberOfIds(5) aTriangleStrip.GetPointIds().SetId(0, 0) aTriangleStrip.GetPointIds().SetId(1, 1) aTriangleStrip.GetPointIds().SetId(2, 2) aTriangleStrip.GetPointIds().SetId(3, 3) aTriangleStrip.GetPointIds().SetId(4, 4) bTriangleStrip = aTriangleStrip.NewInstance() bTriangleStrip.DeepCopy(aTriangleStrip) aTriangleStripGrid = vtk.vtkUnstructuredGrid() aTriangleStripGrid.Allocate(1, 1) aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds()) aTriangleStripGrid.SetPoints(triangleStripPoints) aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords) aTriangleStripMapper = vtk.vtkDataSetMapper() aTriangleStripMapper.SetInputData(aTriangleStripGrid) aTriangleStripActor = vtk.vtkActor() aTriangleStripActor.SetMapper(aTriangleStripMapper) aTriangleStripActor.AddPosition(8, 0, 2) aTriangleStripActor.GetProperty().BackfaceCullingOn() # Line linePoints = vtk.vtkPoints() linePoints.SetNumberOfPoints(2) linePoints.InsertPoint(0, 0, 0, 0) linePoints.InsertPoint(1, 1, 1, 0) aLine = vtk.vtkLine() aLine.GetPointIds().SetId(0, 0) aLine.GetPointIds().SetId(1, 1) bLine = aLine.NewInstance() bLine.DeepCopy(aLine) aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) aLineGrid.SetPoints(linePoints) aLineMapper = vtk.vtkDataSetMapper() aLineMapper.SetInputData(aLineGrid) aLineActor = vtk.vtkActor() aLineActor.SetMapper(aLineMapper) aLineActor.AddPosition(0, 0, 4) aLineActor.GetProperty().BackfaceCullingOn() # Poly line polyLinePoints = vtk.vtkPoints() polyLinePoints.SetNumberOfPoints(3) polyLinePoints.InsertPoint(0, 0, 0, 0) polyLinePoints.InsertPoint(1, 1, 1, 0) polyLinePoints.InsertPoint(2, 1, 0, 0) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(3) aPolyLine.GetPointIds().SetId(0, 0) aPolyLine.GetPointIds().SetId(1, 1) aPolyLine.GetPointIds().SetId(2, 2) bPolyLine = aPolyLine.NewInstance() bPolyLine.DeepCopy(aPolyLine) aPolyLineGrid = vtk.vtkUnstructuredGrid() aPolyLineGrid.Allocate(1, 1) aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) aPolyLineMapper = vtk.vtkDataSetMapper() aPolyLineMapper.SetInputData(aPolyLineGrid) aPolyLineActor = vtk.vtkActor() aPolyLineActor.SetMapper(aPolyLineMapper) aPolyLineActor.AddPosition(2, 0, 4) aPolyLineActor.GetProperty().BackfaceCullingOn() # Vertex vertexPoints = vtk.vtkPoints() vertexPoints.SetNumberOfPoints(1) vertexPoints.InsertPoint(0, 0, 0, 0) aVertex = vtk.vtkVertex() aVertex.GetPointIds().SetId(0, 0) bVertex = aVertex.NewInstance() bVertex.DeepCopy(aVertex) aVertexGrid = vtk.vtkUnstructuredGrid() aVertexGrid.Allocate(1, 1) aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds()) aVertexGrid.SetPoints(vertexPoints) aVertexMapper = vtk.vtkDataSetMapper() aVertexMapper.SetInputData(aVertexGrid) aVertexActor = vtk.vtkActor() aVertexActor.SetMapper(aVertexMapper) aVertexActor.AddPosition(0, 0, 6) aVertexActor.GetProperty().BackfaceCullingOn() # Poly Vertex polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(3) polyVertexPoints.InsertPoint(0, 0, 0, 0) polyVertexPoints.InsertPoint(1, 1, 0, 0) polyVertexPoints.InsertPoint(2, 1, 1, 0) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(3) aPolyVertex.GetPointIds().SetId(0, 0) aPolyVertex.GetPointIds().SetId(1, 1) aPolyVertex.GetPointIds().SetId(2, 2) bPolyVertex = aPolyVertex.NewInstance() bPolyVertex.DeepCopy(aPolyVertex) aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexMapper = vtk.vtkDataSetMapper() aPolyVertexMapper.SetInputData(aPolyVertexGrid) aPolyVertexActor = vtk.vtkActor() aPolyVertexActor.SetMapper(aPolyVertexMapper) aPolyVertexActor.AddPosition(2, 0, 6) aPolyVertexActor.GetProperty().BackfaceCullingOn() # Pentagonal prism pentaPoints = vtk.vtkPoints() pentaPoints.SetNumberOfPoints(10) pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0) pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0) pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0) pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0) pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0) pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0) pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0) pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0) pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0) pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0) aPenta = vtk.vtkPentagonalPrism() aPenta.GetPointIds().SetId(0, 0) aPenta.GetPointIds().SetId(1, 1) aPenta.GetPointIds().SetId(2, 2) aPenta.GetPointIds().SetId(3, 3) aPenta.GetPointIds().SetId(4, 4) aPenta.GetPointIds().SetId(5, 5) aPenta.GetPointIds().SetId(6, 6) aPenta.GetPointIds().SetId(7, 7) aPenta.GetPointIds().SetId(8, 8) aPenta.GetPointIds().SetId(9, 9) bPenta = aPenta.NewInstance() bPenta.DeepCopy(aPenta) aPentaGrid = vtk.vtkUnstructuredGrid() aPentaGrid.Allocate(1, 1) aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds()) aPentaGrid.SetPoints(pentaPoints) aPentaCopy = vtk.vtkUnstructuredGrid() aPentaCopy.DeepCopy(aPentaGrid) aPentaMapper = vtk.vtkDataSetMapper() aPentaMapper.SetInputData(aPentaCopy) aPentaActor = vtk.vtkActor() aPentaActor.SetMapper(aPentaMapper) aPentaActor.AddPosition(10, 0, 0) aPentaActor.GetProperty().BackfaceCullingOn() # Hexagonal prism hexaPoints = vtk.vtkPoints() hexaPoints.SetNumberOfPoints(12) hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0) hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0) hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0) hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0) hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0) hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0) hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0) hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0) hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0) hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0) hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0) hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0) aHexa = vtk.vtkHexagonalPrism() aHexa.GetPointIds().SetId(0, 0) aHexa.GetPointIds().SetId(1, 1) aHexa.GetPointIds().SetId(2, 2) aHexa.GetPointIds().SetId(3, 3) aHexa.GetPointIds().SetId(4, 4) aHexa.GetPointIds().SetId(5, 5) aHexa.GetPointIds().SetId(6, 6) aHexa.GetPointIds().SetId(7, 7) aHexa.GetPointIds().SetId(8, 8) aHexa.GetPointIds().SetId(9, 9) aHexa.GetPointIds().SetId(10, 10) aHexa.GetPointIds().SetId(11, 11) bHexa = aHexa.NewInstance() bHexa.DeepCopy(aHexa) aHexaGrid = vtk.vtkUnstructuredGrid() aHexaGrid.Allocate(1, 1) aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds()) aHexaGrid.SetPoints(hexaPoints) aHexaCopy = vtk.vtkUnstructuredGrid() aHexaCopy.DeepCopy(aHexaGrid) aHexaMapper = vtk.vtkDataSetMapper() aHexaMapper.SetInputData(aHexaCopy) aHexaActor = vtk.vtkActor() aHexaActor.SetMapper(aHexaMapper) aHexaActor.AddPosition(12, 0, 0) aHexaActor.GetProperty().BackfaceCullingOn() # RIB property if hasattr(vtk, 'vtkRIBProperty'): aRIBProperty = vtk.vtkRIBProperty() aRIBProperty.SetVariable("Km", "float") aRIBProperty.SetSurfaceShader("LGVeinedmarble") aRIBProperty.SetVariable("veinfreq", "float") aRIBProperty.AddVariable("warpfreq", "float") aRIBProperty.AddVariable("veincolor", "color") aRIBProperty.AddSurfaceShaderParameter("veinfreq", " 2") aRIBProperty.AddSurfaceShaderParameter("veincolor", "1.0000 1.0000 0.9412") bRIBProperty = vtk.vtkRIBProperty() bRIBProperty.SetVariable("Km", "float") bRIBProperty.SetSurfaceShaderParameter("Km", "1.0") bRIBProperty.SetDisplacementShader("dented") bRIBProperty.SetSurfaceShader("plastic") aProperty = vtk.vtkProperty() bProperty = vtk.vtkProperty() aTriangleActor.SetProperty(aProperty) aTriangleStripActor.SetProperty(bProperty) ren.SetBackground(.1, .2, .4) ren.AddActor(aVoxelActor) aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0) ren.AddActor(aHexahedronActor) aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0) ren.AddActor(aTetraActor) aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0) ren.AddActor(aWedgeActor) aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aPyramidActor) aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aPixelActor) aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aQuadActor) aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aTriangleActor) aTriangleActor.GetProperty().SetDiffuseColor(.3, 1, .5) ren.AddActor(aPolygonActor) aPolygonActor.GetProperty().SetDiffuseColor(1, .4, .5) ren.AddActor(aTriangleStripActor) aTriangleStripActor.GetProperty().SetDiffuseColor(.3, .7, 1) ren.AddActor(aLineActor) aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1) ren.AddActor(aPolyLineActor) aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aVertexActor) aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPolyVertexActor) aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPentaActor) aPentaActor.GetProperty().SetDiffuseColor(.2, .4, .7) ren.AddActor(aHexaActor) aHexaActor.GetProperty().SetDiffuseColor(.7, .5, 1) if hasattr(vtk, 'vtkRIBLight'): aRIBLight = vtk.vtkRIBLight() aRIBLight.SetIntensity(0.7) ren.AddLight(aRIBLight) aLight = vtk.vtkLight() aLight.PositionalOn() aLight.SetConeAngle(10.0) aLight.SetIntensity(0.7) ren.AddLight(aLight) ren.ResetCamera() ren.GetActiveCamera().Azimuth(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Dolly(2.8) ren.ResetCameraClippingRange() dir = VTK_TEMP_DIR atext = vtk.vtkTexture() pnmReader = vtk.vtkBMPReader() pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp") atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOff() aTriangleActor.SetTexture(atext) aRIBLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aRIBLight.SetPosition(ren.GetActiveCamera().GetPosition()) aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aLight.SetPosition(ren.GetActiveCamera().GetPosition()) # bascially have IO/Export ? if hasattr(vtk, 'vtkRIBExporter'): rib = vtk.vtkRIBExporter() rib.SetInput(renWin) rib.SetFilePrefix(dir + '/cells') rib.SetTexturePrefix(dir + '/cells') rib.Write() iv = vtk.vtkIVExporter() iv.SetInput(renWin) iv.SetFileName(dir + "/cells.iv") iv.Write() os.remove(dir + '/cells.iv') obj = vtk.vtkOBJExporter() obj.SetInput(renWin) obj.SetFilePrefix(dir + "/cells") obj.Write() os.remove(dir + '/cells.obj') os.remove(dir + '/cells.mtl') vrml = vtk.vtkVRMLExporter() vrml.SetInput(renWin) #vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl")) #vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl")) vrml.SetFileName(dir + "/cells.wrl") vrml.SetSpeed(5.5) vrml.Write() os.remove(dir + '/cells.wrl') oogl = vtk.vtkOOGLExporter() oogl.SetInput(renWin) oogl.SetFileName(dir + "/cells.oogl") oogl.Write() os.remove(dir + '/cells.oogl') # the UnRegister calls are because make object is the same as New, # and causes memory leaks. (Python does not treat NewInstance the same as New). def DeleteCopies(): bVoxel.UnRegister(None) bHexahedron.UnRegister(None) bTetra.UnRegister(None) bWedge.UnRegister(None) bPyramid.UnRegister(None) bPixel.UnRegister(None) bQuad.UnRegister(None) bTriangle.UnRegister(None) bPolygon.UnRegister(None) bTriangleStrip.UnRegister(None) bLine.UnRegister(None) bPolyLine.UnRegister(None) bVertex.UnRegister(None) bPolyVertex.UnRegister(None) bPenta.UnRegister(None) bHexa.UnRegister(None) DeleteCopies() # render and interact with data renWin.Render() img_file = "cells.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file)) vtk.test.Testing.interact()
def exportModel(self, inputItem, outputFolder=None, reductionFactor=None, outputFormat=None): if outputFormat is None: outputFormat = "glTF" if reductionFactor is not None: self.reductionFactor = reductionFactor self._exportToFile = (outputFormat != "scene") if outputFolder is None: if self._exportToFile: raise ValueError( "Output folder must be specified if output format is not 'scene'" ) shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode( slicer.mrmlScene) inputName = shNode.GetItemName(inputItem) # Get input as a subject hierarchy folder owner = shNode.GetItemOwnerPluginName(inputItem) if owner == "Folder": # Input is already a model hiearachy inputShFolderItemId = inputItem self._outputShFolderItemId = shNode.CreateFolderItem( shNode.GetSceneItemID(), inputName + " export") elif owner == "Segmentations": # Export segmentation to model hierarchy segLogic = slicer.modules.segmentations.logic() folderName = inputName + '_Models' inputShFolderItemId = shNode.CreateFolderItem( shNode.GetSceneItemID(), folderName) inputSegmentationNode = shNode.GetItemDataNode(inputItem) self.addLog( 'Export segmentation to models. This may take a few minutes.') success = segLogic.ExportAllSegmentsToModels( inputSegmentationNode, inputShFolderItemId) self._outputShFolderItemId = inputShFolderItemId else: raise ValueError( "Input item must be a segmentation node or a folder containing model nodes" ) modelNodes = vtk.vtkCollection() shNode.GetDataNodesInBranch(inputShFolderItemId, modelNodes, "vtkMRMLModelNode") self._numberOfExpectedModels = modelNodes.GetNumberOfItems() self._numberOfProcessedModels = 0 self._gltfNodes = [] self._gltfMeshes = [] # Add models to a self._renderer self.addModelsToRenderer(inputShFolderItemId, boostGouraudColor=(outputFormat == "glTF")) if self._exportToFile: outputFileName = inputName # import datetime # dateTimeStr = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # outputFileName += dateTimeStr outputFilePathBase = os.path.join(outputFolder, outputFileName) if outputFormat == "glTF": exporter = vtk.vtkGLTFExporter() outputFilePath = outputFilePathBase + '.gltf' exporter.SetFileName(outputFilePath) exporter.InlineDataOn() # save to single file exporter.SaveNormalOn() # save surface normals elif outputFormat == "OBJ": exporter = vtk.vtkOBJExporter() outputFilePath = outputFilePathBase + '.obj' exporter.SetFilePrefix(outputFilePathBase) else: raise ValueError("Output format must be scene, glTF, or OBJ") self.addLog(f"Writing file {outputFilePath}...") exporter.SetRenderWindow(self._renderWindow) exporter.Write() if outputFormat == "glTF": # Fix up the VTK-generated glTF file import json with open(outputFilePath, 'r') as f: jsonData = json.load(f) # Update mesh names for meshIndex, mesh in enumerate(self._gltfMeshes): jsonData['meshes'][meshIndex]['name'] = mesh['name'] # VTK uses "OPAQUE" alpha mode for all meshes, which would make all nodes appear opaque. # Replace alpha mode by "BLEND" for semi-transparent meshes. for material in jsonData['materials']: rgbaColor = material['pbrMetallicRoughness'][ 'baseColorFactor'] if rgbaColor[3] < 1.0: material['alphaMode'] = 'BLEND' # Add camera nodes from the VTK-exported file for node in enumerate(self._gltfNodes): if 'camera' in node: self._gltfNodes.append(node) # Replace the entire hierarchy jsonData['nodes'] = self._gltfNodes # Set up root node rootNodeIndex = len(self._gltfNodes) - 1 # View up direction in glTF is +Y. # We map that to anatomical S direction by this transform (LSA coordinate system). jsonData['nodes'][rootNodeIndex]['matrix'] = [ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] # The scene root is the last node in the self._gltfNodes list jsonData['scenes'][0]['nodes'] = [rootNodeIndex] jsonData['asset'][ 'generator'] = f"{slicer.app.applicationName} {slicer.app.applicationVersion}" with open(outputFilePath, 'w') as f: f.write(json.dumps(jsonData, indent=3)) # TODO: # - Add scene view states as scenes # - Add option to change up vector (glTF defines the y axis as up, https://github.com/KhronosGroup/glTF/issues/1043 # https://castle-engine.io/manual_up.php) # # Preview # iren = vtk.vtkRenderWindowInteractor() # iren.SetRenderWindow(renderWindow) # iren.Initialize() # renderer.ResetCamera() # renderer.GetActiveCamera().Zoom(1.5) # renderWindow.Render() # iren.Start() # Remove temporary nodes for node in self._temporaryExportNodes: slicer.mrmlScene.RemoveNode(node) self._temporaryExportNodes = [] self._numberOfExpectedModels = 0 self._numberOfProcessedModels = 0 self._renderer = None self._renderWindow = None self._decimationParameterNode = None if self._exportToFile: shNode.RemoveItem(self._outputShFolderItemId)
def testCells(self): # Demonstrates all cell types # # NOTE: the use of NewInstance/DeepCopy is included to increase # regression coverage. It is not required in most applications. ren = vtk.vtkRenderer() # turn off all cullers ren.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(300, 150) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # create a scene with one of each cell type # Voxel voxelPoints = vtk.vtkPoints() voxelPoints.SetNumberOfPoints(8) voxelPoints.InsertPoint(0, 0, 0, 0) voxelPoints.InsertPoint(1, 1, 0, 0) voxelPoints.InsertPoint(2, 0, 1, 0) voxelPoints.InsertPoint(3, 1, 1, 0) voxelPoints.InsertPoint(4, 0, 0, 1) voxelPoints.InsertPoint(5, 1, 0, 1) voxelPoints.InsertPoint(6, 0, 1, 1) voxelPoints.InsertPoint(7, 1, 1, 1) aVoxel = vtk.vtkVoxel() 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) bVoxel = aVoxel.NewInstance() bVoxel.DeepCopy(aVoxel) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper) aVoxelActor.GetProperty().BackfaceCullingOn() # Hexahedron hexahedronPoints = vtk.vtkPoints() hexahedronPoints.SetNumberOfPoints(8) hexahedronPoints.InsertPoint(0, 0, 0, 0) hexahedronPoints.InsertPoint(1, 1, 0, 0) hexahedronPoints.InsertPoint(2, 1, 1, 0) hexahedronPoints.InsertPoint(3, 0, 1, 0) hexahedronPoints.InsertPoint(4, 0, 0, 1) hexahedronPoints.InsertPoint(5, 1, 0, 1) hexahedronPoints.InsertPoint(6, 1, 1, 1) hexahedronPoints.InsertPoint(7, 0, 1, 1) aHexahedron = vtk.vtkHexahedron() aHexahedron.GetPointIds().SetId(0, 0) aHexahedron.GetPointIds().SetId(1, 1) aHexahedron.GetPointIds().SetId(2, 2) aHexahedron.GetPointIds().SetId(3, 3) aHexahedron.GetPointIds().SetId(4, 4) aHexahedron.GetPointIds().SetId(5, 5) aHexahedron.GetPointIds().SetId(6, 6) aHexahedron.GetPointIds().SetId(7, 7) bHexahedron = aHexahedron.NewInstance() bHexahedron.DeepCopy(aHexahedron) aHexahedronGrid = vtk.vtkUnstructuredGrid() aHexahedronGrid.Allocate(1, 1) aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds()) aHexahedronGrid.SetPoints(hexahedronPoints) aHexahedronMapper = vtk.vtkDataSetMapper() aHexahedronMapper.SetInputData(aHexahedronGrid) aHexahedronActor = vtk.vtkActor() aHexahedronActor.SetMapper(aHexahedronMapper) aHexahedronActor.AddPosition(2, 0, 0) aHexahedronActor.GetProperty().BackfaceCullingOn() # Tetra tetraPoints = vtk.vtkPoints() tetraPoints.SetNumberOfPoints(4) tetraPoints.InsertPoint(0, 0, 0, 0) tetraPoints.InsertPoint(1, 1, 0, 0) tetraPoints.InsertPoint(2, 0.5, 1, 0) tetraPoints.InsertPoint(3, 0.5, 0.5, 1) aTetra = vtk.vtkTetra() aTetra.GetPointIds().SetId(0, 0) aTetra.GetPointIds().SetId(1, 1) aTetra.GetPointIds().SetId(2, 2) aTetra.GetPointIds().SetId(3, 3) bTetra = aTetra.NewInstance() bTetra.DeepCopy(aTetra) aTetraGrid = vtk.vtkUnstructuredGrid() aTetraGrid.Allocate(1, 1) aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds()) aTetraGrid.SetPoints(tetraPoints) aTetraCopy = vtk.vtkUnstructuredGrid() aTetraCopy.ShallowCopy(aTetraGrid) aTetraMapper = vtk.vtkDataSetMapper() aTetraMapper.SetInputData(aTetraCopy) aTetraActor = vtk.vtkActor() aTetraActor.SetMapper(aTetraMapper) aTetraActor.AddPosition(4, 0, 0) aTetraActor.GetProperty().BackfaceCullingOn() # Wedge wedgePoints = vtk.vtkPoints() wedgePoints.SetNumberOfPoints(6) wedgePoints.InsertPoint(0, 0, 1, 0) wedgePoints.InsertPoint(1, 0, 0, 0) wedgePoints.InsertPoint(2, 0, 0.5, 0.5) wedgePoints.InsertPoint(3, 1, 1, 0) wedgePoints.InsertPoint(4, 1, 0, 0) wedgePoints.InsertPoint(5, 1, 0.5, 0.5) aWedge = vtk.vtkWedge() aWedge.GetPointIds().SetId(0, 0) aWedge.GetPointIds().SetId(1, 1) aWedge.GetPointIds().SetId(2, 2) aWedge.GetPointIds().SetId(3, 3) aWedge.GetPointIds().SetId(4, 4) aWedge.GetPointIds().SetId(5, 5) bWedge = aWedge.NewInstance() bWedge.DeepCopy(aWedge) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeCopy = vtk.vtkUnstructuredGrid() aWedgeCopy.DeepCopy(aWedgeGrid) aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeCopy) aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.AddPosition(6, 0, 0) aWedgeActor.GetProperty().BackfaceCullingOn() # Pyramid pyramidPoints = vtk.vtkPoints() pyramidPoints.SetNumberOfPoints(5) pyramidPoints.InsertPoint(0, 0, 0, 0) pyramidPoints.InsertPoint(1, 1, 0, 0) pyramidPoints.InsertPoint(2, 1, 1, 0) pyramidPoints.InsertPoint(3, 0, 1, 0) pyramidPoints.InsertPoint(4, 0.5, 0.5, 1) aPyramid = vtk.vtkPyramid() aPyramid.GetPointIds().SetId(0, 0) aPyramid.GetPointIds().SetId(1, 1) aPyramid.GetPointIds().SetId(2, 2) aPyramid.GetPointIds().SetId(3, 3) aPyramid.GetPointIds().SetId(4, 4) bPyramid = aPyramid.NewInstance() bPyramid.DeepCopy(aPyramid) aPyramidGrid = vtk.vtkUnstructuredGrid() aPyramidGrid.Allocate(1, 1) aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds()) aPyramidGrid.SetPoints(pyramidPoints) aPyramidMapper = vtk.vtkDataSetMapper() aPyramidMapper.SetInputData(aPyramidGrid) aPyramidActor = vtk.vtkActor() aPyramidActor.SetMapper(aPyramidMapper) aPyramidActor.AddPosition(8, 0, 0) aPyramidActor.GetProperty().BackfaceCullingOn() # Pixel pixelPoints = vtk.vtkPoints() pixelPoints.SetNumberOfPoints(4) pixelPoints.InsertPoint(0, 0, 0, 0) pixelPoints.InsertPoint(1, 1, 0, 0) pixelPoints.InsertPoint(2, 0, 1, 0) pixelPoints.InsertPoint(3, 1, 1, 0) aPixel = vtk.vtkPixel() aPixel.GetPointIds().SetId(0, 0) aPixel.GetPointIds().SetId(1, 1) aPixel.GetPointIds().SetId(2, 2) aPixel.GetPointIds().SetId(3, 3) bPixel = aPixel.NewInstance() bPixel.DeepCopy(aPixel) aPixelGrid = vtk.vtkUnstructuredGrid() aPixelGrid.Allocate(1, 1) aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds()) aPixelGrid.SetPoints(pixelPoints) aPixelMapper = vtk.vtkDataSetMapper() aPixelMapper.SetInputData(aPixelGrid) aPixelActor = vtk.vtkActor() aPixelActor.SetMapper(aPixelMapper) aPixelActor.AddPosition(0, 0, 2) aPixelActor.GetProperty().BackfaceCullingOn() # Quad quadPoints = vtk.vtkPoints() quadPoints.SetNumberOfPoints(4) quadPoints.InsertPoint(0, 0, 0, 0) quadPoints.InsertPoint(1, 1, 0, 0) quadPoints.InsertPoint(2, 1, 1, 0) quadPoints.InsertPoint(3, 0, 1, 0) aQuad = vtk.vtkQuad() aQuad.GetPointIds().SetId(0, 0) aQuad.GetPointIds().SetId(1, 1) aQuad.GetPointIds().SetId(2, 2) aQuad.GetPointIds().SetId(3, 3) bQuad = aQuad.NewInstance() bQuad.DeepCopy(aQuad) aQuadGrid = vtk.vtkUnstructuredGrid() aQuadGrid.Allocate(1, 1) aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds()) aQuadGrid.SetPoints(quadPoints) aQuadMapper = vtk.vtkDataSetMapper() aQuadMapper.SetInputData(aQuadGrid) aQuadActor = vtk.vtkActor() aQuadActor.SetMapper(aQuadMapper) aQuadActor.AddPosition(2, 0, 2) aQuadActor.GetProperty().BackfaceCullingOn() # Triangle trianglePoints = vtk.vtkPoints() trianglePoints.SetNumberOfPoints(3) trianglePoints.InsertPoint(0, 0, 0, 0) trianglePoints.InsertPoint(1, 1, 0, 0) trianglePoints.InsertPoint(2, 0.5, 0.5, 0) triangleTCoords = vtk.vtkFloatArray() triangleTCoords.SetNumberOfComponents(2) triangleTCoords.SetNumberOfTuples(3) triangleTCoords.InsertTuple2(0, 1, 1) triangleTCoords.InsertTuple2(1, 2, 2) triangleTCoords.InsertTuple2(2, 3, 3) aTriangle = vtk.vtkTriangle() aTriangle.GetPointIds().SetId(0, 0) aTriangle.GetPointIds().SetId(1, 1) aTriangle.GetPointIds().SetId(2, 2) bTriangle = aTriangle.NewInstance() bTriangle.DeepCopy(aTriangle) aTriangleGrid = vtk.vtkUnstructuredGrid() aTriangleGrid.Allocate(1, 1) aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds()) aTriangleGrid.SetPoints(trianglePoints) aTriangleGrid.GetPointData().SetTCoords(triangleTCoords) aTriangleMapper = vtk.vtkDataSetMapper() aTriangleMapper.SetInputData(aTriangleGrid) aTriangleActor = vtk.vtkActor() aTriangleActor.SetMapper(aTriangleMapper) aTriangleActor.AddPosition(4, 0, 2) aTriangleActor.GetProperty().BackfaceCullingOn() # Polygon polygonPoints = vtk.vtkPoints() polygonPoints.SetNumberOfPoints(4) polygonPoints.InsertPoint(0, 0, 0, 0) polygonPoints.InsertPoint(1, 1, 0, 0) polygonPoints.InsertPoint(2, 1, 1, 0) polygonPoints.InsertPoint(3, 0, 1, 0) aPolygon = vtk.vtkPolygon() aPolygon.GetPointIds().SetNumberOfIds(4) aPolygon.GetPointIds().SetId(0, 0) aPolygon.GetPointIds().SetId(1, 1) aPolygon.GetPointIds().SetId(2, 2) aPolygon.GetPointIds().SetId(3, 3) bPolygon = aPolygon.NewInstance() bPolygon.DeepCopy(aPolygon) aPolygonGrid = vtk.vtkUnstructuredGrid() aPolygonGrid.Allocate(1, 1) aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds()) aPolygonGrid.SetPoints(polygonPoints) aPolygonMapper = vtk.vtkDataSetMapper() aPolygonMapper.SetInputData(aPolygonGrid) aPolygonActor = vtk.vtkActor() aPolygonActor.SetMapper(aPolygonMapper) aPolygonActor.AddPosition(6, 0, 2) aPolygonActor.GetProperty().BackfaceCullingOn() # Triangle Strip triangleStripPoints = vtk.vtkPoints() triangleStripPoints.SetNumberOfPoints(5) triangleStripPoints.InsertPoint(0, 0, 1, 0) triangleStripPoints.InsertPoint(1, 0, 0, 0) triangleStripPoints.InsertPoint(2, 1, 1, 0) triangleStripPoints.InsertPoint(3, 1, 0, 0) triangleStripPoints.InsertPoint(4, 2, 1, 0) triangleStripTCoords = vtk.vtkFloatArray() triangleStripTCoords.SetNumberOfComponents(2) triangleStripTCoords.SetNumberOfTuples(3) triangleStripTCoords.InsertTuple2(0, 1, 1) triangleStripTCoords.InsertTuple2(1, 2, 2) triangleStripTCoords.InsertTuple2(2, 3, 3) triangleStripTCoords.InsertTuple2(3, 4, 4) triangleStripTCoords.InsertTuple2(4, 5, 5) aTriangleStrip = vtk.vtkTriangleStrip() aTriangleStrip.GetPointIds().SetNumberOfIds(5) aTriangleStrip.GetPointIds().SetId(0, 0) aTriangleStrip.GetPointIds().SetId(1, 1) aTriangleStrip.GetPointIds().SetId(2, 2) aTriangleStrip.GetPointIds().SetId(3, 3) aTriangleStrip.GetPointIds().SetId(4, 4) bTriangleStrip = aTriangleStrip.NewInstance() bTriangleStrip.DeepCopy(aTriangleStrip) aTriangleStripGrid = vtk.vtkUnstructuredGrid() aTriangleStripGrid.Allocate(1, 1) aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds()) aTriangleStripGrid.SetPoints(triangleStripPoints) aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords) aTriangleStripMapper = vtk.vtkDataSetMapper() aTriangleStripMapper.SetInputData(aTriangleStripGrid) aTriangleStripActor = vtk.vtkActor() aTriangleStripActor.SetMapper(aTriangleStripMapper) aTriangleStripActor.AddPosition(8, 0, 2) aTriangleStripActor.GetProperty().BackfaceCullingOn() # Line linePoints = vtk.vtkPoints() linePoints.SetNumberOfPoints(2) linePoints.InsertPoint(0, 0, 0, 0) linePoints.InsertPoint(1, 1, 1, 0) aLine = vtk.vtkLine() aLine.GetPointIds().SetId(0, 0) aLine.GetPointIds().SetId(1, 1) bLine = aLine.NewInstance() bLine.DeepCopy(aLine) aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) aLineGrid.SetPoints(linePoints) aLineMapper = vtk.vtkDataSetMapper() aLineMapper.SetInputData(aLineGrid) aLineActor = vtk.vtkActor() aLineActor.SetMapper(aLineMapper) aLineActor.AddPosition(0, 0, 4) aLineActor.GetProperty().BackfaceCullingOn() # Poly line polyLinePoints = vtk.vtkPoints() polyLinePoints.SetNumberOfPoints(3) polyLinePoints.InsertPoint(0, 0, 0, 0) polyLinePoints.InsertPoint(1, 1, 1, 0) polyLinePoints.InsertPoint(2, 1, 0, 0) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(3) aPolyLine.GetPointIds().SetId(0, 0) aPolyLine.GetPointIds().SetId(1, 1) aPolyLine.GetPointIds().SetId(2, 2) bPolyLine = aPolyLine.NewInstance() bPolyLine.DeepCopy(aPolyLine) aPolyLineGrid = vtk.vtkUnstructuredGrid() aPolyLineGrid.Allocate(1, 1) aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) aPolyLineMapper = vtk.vtkDataSetMapper() aPolyLineMapper.SetInputData(aPolyLineGrid) aPolyLineActor = vtk.vtkActor() aPolyLineActor.SetMapper(aPolyLineMapper) aPolyLineActor.AddPosition(2, 0, 4) aPolyLineActor.GetProperty().BackfaceCullingOn() # Vertex vertexPoints = vtk.vtkPoints() vertexPoints.SetNumberOfPoints(1) vertexPoints.InsertPoint(0, 0, 0, 0) aVertex = vtk.vtkVertex() aVertex.GetPointIds().SetId(0, 0) bVertex = aVertex.NewInstance() bVertex.DeepCopy(aVertex) aVertexGrid = vtk.vtkUnstructuredGrid() aVertexGrid.Allocate(1, 1) aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds()) aVertexGrid.SetPoints(vertexPoints) aVertexMapper = vtk.vtkDataSetMapper() aVertexMapper.SetInputData(aVertexGrid) aVertexActor = vtk.vtkActor() aVertexActor.SetMapper(aVertexMapper) aVertexActor.AddPosition(0, 0, 6) aVertexActor.GetProperty().BackfaceCullingOn() # Poly Vertex polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(3) polyVertexPoints.InsertPoint(0, 0, 0, 0) polyVertexPoints.InsertPoint(1, 1, 0, 0) polyVertexPoints.InsertPoint(2, 1, 1, 0) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(3) aPolyVertex.GetPointIds().SetId(0, 0) aPolyVertex.GetPointIds().SetId(1, 1) aPolyVertex.GetPointIds().SetId(2, 2) bPolyVertex = aPolyVertex.NewInstance() bPolyVertex.DeepCopy(aPolyVertex) aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexMapper = vtk.vtkDataSetMapper() aPolyVertexMapper.SetInputData(aPolyVertexGrid) aPolyVertexActor = vtk.vtkActor() aPolyVertexActor.SetMapper(aPolyVertexMapper) aPolyVertexActor.AddPosition(2, 0, 6) aPolyVertexActor.GetProperty().BackfaceCullingOn() # Pentagonal prism pentaPoints = vtk.vtkPoints() pentaPoints.SetNumberOfPoints(10) pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0) pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0) pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0) pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0) pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0) pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0) pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0) pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0) pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0) pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0) aPenta = vtk.vtkPentagonalPrism() aPenta.GetPointIds().SetId(0, 0) aPenta.GetPointIds().SetId(1, 1) aPenta.GetPointIds().SetId(2, 2) aPenta.GetPointIds().SetId(3, 3) aPenta.GetPointIds().SetId(4, 4) aPenta.GetPointIds().SetId(5, 5) aPenta.GetPointIds().SetId(6, 6) aPenta.GetPointIds().SetId(7, 7) aPenta.GetPointIds().SetId(8, 8) aPenta.GetPointIds().SetId(9, 9) bPenta = aPenta.NewInstance() bPenta.DeepCopy(aPenta) aPentaGrid = vtk.vtkUnstructuredGrid() aPentaGrid.Allocate(1, 1) aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds()) aPentaGrid.SetPoints(pentaPoints) aPentaCopy = vtk.vtkUnstructuredGrid() aPentaCopy.DeepCopy(aPentaGrid) aPentaMapper = vtk.vtkDataSetMapper() aPentaMapper.SetInputData(aPentaCopy) aPentaActor = vtk.vtkActor() aPentaActor.SetMapper(aPentaMapper) aPentaActor.AddPosition(10, 0, 0) aPentaActor.GetProperty().BackfaceCullingOn() # Hexagonal prism hexaPoints = vtk.vtkPoints() hexaPoints.SetNumberOfPoints(12) hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0) hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0) hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0) hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0) hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0) hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0) hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0) hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0) hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0) hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0) hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0) hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0) aHexa = vtk.vtkHexagonalPrism() aHexa.GetPointIds().SetId(0, 0) aHexa.GetPointIds().SetId(1, 1) aHexa.GetPointIds().SetId(2, 2) aHexa.GetPointIds().SetId(3, 3) aHexa.GetPointIds().SetId(4, 4) aHexa.GetPointIds().SetId(5, 5) aHexa.GetPointIds().SetId(6, 6) aHexa.GetPointIds().SetId(7, 7) aHexa.GetPointIds().SetId(8, 8) aHexa.GetPointIds().SetId(9, 9) aHexa.GetPointIds().SetId(10, 10) aHexa.GetPointIds().SetId(11, 11) bHexa = aHexa.NewInstance() bHexa.DeepCopy(aHexa) aHexaGrid = vtk.vtkUnstructuredGrid() aHexaGrid.Allocate(1, 1) aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds()) aHexaGrid.SetPoints(hexaPoints) aHexaCopy = vtk.vtkUnstructuredGrid() aHexaCopy.DeepCopy(aHexaGrid) aHexaMapper = vtk.vtkDataSetMapper() aHexaMapper.SetInputData(aHexaCopy) aHexaActor = vtk.vtkActor() aHexaActor.SetMapper(aHexaMapper) aHexaActor.AddPosition(12, 0, 0) aHexaActor.GetProperty().BackfaceCullingOn() # RIB property aRIBProperty = vtk.vtkRIBProperty() aRIBProperty.SetVariable("Km", "float") aRIBProperty.SetSurfaceShader("LGVeinedmarble") aRIBProperty.SetVariable("veinfreq", "float") aRIBProperty.AddVariable("warpfreq", "float") aRIBProperty.AddVariable("veincolor", "color") aRIBProperty.AddParameter("veinfreq", " 2") aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412") bRIBProperty = vtk.vtkRIBProperty() bRIBProperty.SetVariable("Km", "float") bRIBProperty.SetParameter("Km", "1.0") bRIBProperty.SetDisplacementShader("dented") bRIBProperty.SetSurfaceShader("plastic") aProperty = vtk.vtkProperty() bProperty = vtk.vtkProperty() aTriangleActor.SetProperty(aProperty) aTriangleStripActor.SetProperty(bProperty) ren.SetBackground(0.1, 0.2, 0.4) ren.AddActor(aVoxelActor) aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0) ren.AddActor(aHexahedronActor) aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0) ren.AddActor(aTetraActor) aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0) ren.AddActor(aWedgeActor) aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aPyramidActor) aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aPixelActor) aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aQuadActor) aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aTriangleActor) aTriangleActor.GetProperty().SetDiffuseColor(0.3, 1, 0.5) ren.AddActor(aPolygonActor) aPolygonActor.GetProperty().SetDiffuseColor(1, 0.4, 0.5) ren.AddActor(aTriangleStripActor) aTriangleStripActor.GetProperty().SetDiffuseColor(0.3, 0.7, 1) ren.AddActor(aLineActor) aLineActor.GetProperty().SetDiffuseColor(0.2, 1, 1) ren.AddActor(aPolyLineActor) aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aVertexActor) aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPolyVertexActor) aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPentaActor) aPentaActor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.7) ren.AddActor(aHexaActor) aHexaActor.GetProperty().SetDiffuseColor(0.7, 0.5, 1) aRIBLight = vtk.vtkRIBLight() aRIBLight.ShadowsOn() aLight = vtk.vtkLight() aLight.PositionalOn() aLight.SetConeAngle(25) ren.AddLight(aLight) ren.ResetCamera() ren.GetActiveCamera().Azimuth(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Dolly(2.8) ren.ResetCameraClippingRange() aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aLight.SetPosition(ren.GetActiveCamera().GetPosition()) # write to the temp directory if possible, otherwise use . dir = tempfile.gettempdir() atext = vtk.vtkTexture() pnmReader = vtk.vtkBMPReader() pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp") atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOff() aTriangleActor.SetTexture(atext) rib = vtk.vtkRIBExporter() rib.SetInput(renWin) rib.SetFilePrefix(dir + "/cells") rib.SetTexturePrefix(dir + "/cells") rib.Write() os.remove(dir + "/cells.rib") iv = vtk.vtkIVExporter() iv.SetInput(renWin) iv.SetFileName(dir + "/cells.iv") iv.Write() os.remove(dir + "/cells.iv") obj = vtk.vtkOBJExporter() obj.SetInput(renWin) obj.SetFilePrefix(dir + "/cells") obj.Write() os.remove(dir + "/cells.obj") os.remove(dir + "/cells.mtl") vrml = vtk.vtkVRMLExporter() vrml.SetInput(renWin) # vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl")) # vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl")) vrml.SetFileName(dir + "/cells.wrl") vrml.SetSpeed(5.5) vrml.Write() os.remove(dir + "/cells.wrl") oogl = vtk.vtkOOGLExporter() oogl.SetInput(renWin) oogl.SetFileName(dir + "/cells.oogl") oogl.Write() os.remove(dir + "/cells.oogl") # the UnRegister calls are because make object is the same as New, # and causes memory leaks. (Python does not treat NewInstance the same as New). def DeleteCopies(): bVoxel.UnRegister(None) bHexahedron.UnRegister(None) bTetra.UnRegister(None) bWedge.UnRegister(None) bPyramid.UnRegister(None) bPixel.UnRegister(None) bQuad.UnRegister(None) bTriangle.UnRegister(None) bPolygon.UnRegister(None) bTriangleStrip.UnRegister(None) bLine.UnRegister(None) bPolyLine.UnRegister(None) bVertex.UnRegister(None) bPolyVertex.UnRegister(None) bPenta.UnRegister(None) bHexa.UnRegister(None) DeleteCopies() # render and interact with data renWin.Render() img_file = "cells.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
tube.SetInputData( polydata ) tube.SetRadius( 0.01 ) tube.SetNumberOfSides( 64 ) tube.CappingOn() #smoother = vtk.vtkSmoothPolyDataFilter() #smoother.SetInputConnection( tube.GetOutputPort () ) #smoother.SetNumberOfIterations( 1 ) polyDataMapper = vtk.vtkPolyDataMapper() polyDataMapper.SetInputConnection( tube.GetOutputPort( )) polylineActor = vtk.vtkActor() polylineActor.SetMapper( polyDataMapper ) polylineExport = vtk.vtkOBJExporter() # }}} # ball actors {{{ balls = vtk.vtkSphereSource() balls.SetRadius(0.2) balls.SetPhiResolution(10) balls.SetThetaResolution(10) glyphPoints = vtk.vtkGlyph3D() glyphPoints.SetInputData( polydata ) glyphPoints.SetSourceConnection( balls.GetOutputPort() ) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection( glyphPoints.GetOutputPort() )
reader.SetFileName(sys.argv[1]) reader.Update() poly_data = reader.GetOutput() poly_data = ApplySmoothFilter(poly_data, 15, 0.1) #print(type(poly_data)) # Create a mapper and actor for initial dataset mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(poly_data) actor = vtk.vtkActor() actor.SetMapper(mapper) # Visualise renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add actors and render renderer.AddActor(actor) renderer.SetBackground(0, 0, 0) # Background color white renderWindow.SetSize(800, 800) #renderWindow.Render() #renderWindowInteractor.Start() exporter = vtk.vtkOBJExporter() exporter.SetRenderWindow(renderWindow) exporter.SetFilePrefix(sys.argv[2]) #create mtl and obj file. exporter.Write()
def display3dobj(self): colors = vtk.vtkNamedColors() h = self.normalmap.shape[0] w = self.normalmap.shape[1] # Create a triangle points = vtk.vtkPoints() for x in range(0, h): for y in range(0, w): points.InsertNextPoint(x, y, self.Z[x, y]) triangle = vtk.vtkTriangle() triangles = vtk.vtkCellArray() for i in range(0, h): for j in range(0, w): triangle.GetPointIds().SetId(0, j + (i * w)) triangle.GetPointIds().SetId(1, (i + 1) * w + j) triangle.GetPointIds().SetId(2, j + (i * w) + 1) triangles.InsertNextCell(triangle) triangle.GetPointIds().SetId(0, (i + 1) * w + j) triangle.GetPointIds().SetId(1, (i + 1) * w + j + 1) triangle.GetPointIds().SetId(2, j + (i * w) + 1) triangles.InsertNextCell(triangle) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) # Create mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(trianglePolyData) actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d("Cyan")) actor.SetMapper(mapper) # Create a renderer, render window, and an interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Triangle") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d("DarkGreen")) # Render and interact renderWindow.Render() renderWindowInteractor.Start() filename = "test" # Write the stl file to disk stlWriter = vtk.vtkOBJExporter() stlWriter.SetFilePrefix(filename) stlWriter.SetInput(renderWindow) stlWriter.Write()
renderer = vtk.vtkRenderer() window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(PdbInteractorStyle()) interactor.SetRenderWindow(window) renderer.SetBackground(1.0,1.0,1.0) renderer.AddActor(actor) renderer.AddActor2D(scalarBar) if args.show: window.Render() interactor.Start() if args.output: obj = vtk.vtkOBJExporter() obj.SetInput(window) file_name = args.output if file_name[-4:] == ".obj": file_prefix = file_name[:-4] obj.SetFilePrefix(file_prefix) obj.Write() ############################# #############################
def ExportObj(self,file_name): exporter = vtk.vtkOBJExporter()
def write(obj, fileoutput, binary=True): ''' Write 3D object to file. Possile extensions are: vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp ''' if isinstance(obj, Actor): obj = obj.polydata(True) elif isinstance(obj, vtk.vtkActor): obj = obj.GetMapper().GetInput() fr = fileoutput.lower() if '.vtk' in fr: w = vtk.vtkPolyDataWriter() elif '.ply' in fr: w = vtk.vtkPLYWriter() elif '.stl' in fr: w = vtk.vtkSTLWriter() elif '.vtp' in fr: w = vtk.vtkXMLPolyDataWriter() elif '.xyz' in fr: w = vtk.vtkSimplePointsWriter() elif '.byu' in fr or fr.endswith('.g'): w = vtk.vtkBYUWriter() elif '.obj' in fr: obj = obj.polydata(True) w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace('.obj', '')) colors.printc('Please use write(vp.renderWin)', c=3) w.SetInputData(obj) w.Update() colors.printc("Saved file: " + fileoutput, c='g') return elif '.tif' in fr: w = vtk.vtkTIFFWriter() w.SetFileDimensionality(len(obj.GetDimensions())) elif '.vti' in fr: w = vtk.vtkXMLImageDataWriter() elif '.png' in fr: w = vtk.vtkPNGWriter() elif '.jpg' in fr: w = vtk.vtkJPEGWriter() elif '.bmp' in fr: w = vtk.vtkBMPWriter() else: colors.printc('Unknown format', fileoutput, 'file not saved.', c='r') return try: if binary: w.SetFileTypeToBinary() else: w.SetFileTypeToASCII() w.SetInputData(obj) w.SetFileName(fileoutput) w.Write() colors.printc("Saved file: " + fileoutput, c='g') except Exception as e: colors.printc("Error saving: " + fileoutput, '\n', e, c='r') return
def main(): #Importing file frontView1 = cv2.imread("4_f_f.jpeg", 1) img_side_view1 = cv2.imread("4_s.jpg", 1) #kernal definition for preprocessing kernel = np.ones((3, 3), np.uint8) #converting colorspace for images original_image = cv2.cvtColor(frontView1, cv2.COLOR_BGR2GRAY) img_side_view = cv2.cvtColor(img_side_view1, cv2.COLOR_BGR2GRAY) # Creating a binary image for thresholding ret, original_image = cv2.threshold(original_image, 250, 255, cv2.THRESH_BINARY) # closing the gaps in the foreground and retaining only the hollow portion closing = cv2.morphologyEx(original_image, cv2.MORPH_CLOSE, kernel) # gradient = cv2.morphologyEx(closing, cv2.MORPH_GRADIENT, kernel) # Median filtering gray_image_mf = median_filter(closing, 1) # Calculate the Laplacian lap = cv2.Laplacian(gray_image_mf, cv2.CV_64F) # Calculate the sharpened image sharp = closing - 0.7 * lap # Saturate the pixels in either direction sharp[sharp > 255] = 255 sharp[sharp < 0] = 0 # for the main frame #Storing the pixel information for the thresholded image of front view list = [] xCoordinate = [] yCoordinate = [] sortedYcoordinates = [] for x in range(sharp.shape[0]): for y in range(sharp.shape[1]): if sharp[x, y] != 255: xCoordinate.append(x) yCoordinate.append(y) sortedYcoordinates.append(y) list.append(xCoordinate) list.append(yCoordinate) sortedYcoordinates.sort() count = 0 for x in range(150): if sortedYcoordinates[x] == sortedYcoordinates[0]: count += 1 count = int(count / 2) print(original_image.shape) ##Showing the front view image cv2.imshow('front', frontView1) cv2.waitKey(0) cv2.destroyAllWindows() # process handle image # The Preprocessing of sideview img_side_view = cv2.resize(img_side_view,(original_image.shape[1],original_image.shape[0])) print(img_side_view.shape) # Creating a binary image ret, img_side_view = cv2.threshold(img_side_view, 200, 255, cv2.THRESH_BINARY) # closing the gaps in the foreground and retaining only the hollow portion closing1 = cv2.morphologyEx(img_side_view, cv2.MORPH_CLOSE, kernel) # gradient = cv2.morphologyEx(closing, cv2.MORPH_GRADIENT, kernel) # Median filtering gray_image_mf1 = median_filter(closing1, 1) # Calculate the Laplacian lap1 = cv2.Laplacian(gray_image_mf1, cv2.CV_64F) # Calculate the sharpened image sharp1 = closing1 - 0.7 * lap1 # Saturate the pixels in either direction sharp1[sharp1 > 255] = 255 sharp1[sharp1 < 0] = 0 #Storing the pixel information of the sideview xCoordinate_side_view = [] yCoordinate_side_view = [] ycoordinateTemp = [] xcoordinateTemp = [] for x in range(sharp1.shape[0]): for y in range(sharp1.shape[1]): if sharp1[x, y] != 255: xCoordinate_side_view.append(x) yCoordinate_side_view.append(y) ycoordinateTemp.append(y) xcoordinateTemp.append(x) #Sorting the list, which provides very first pixel information in either x-axis or y-axis ycoordinateTemp.sort() xcoordinateTemp.sort() #Getting the distance of the first pixel from top margin adjustmentInYdirection = xCoordinate_side_view[0]- xCoordinate[yCoordinate.index(sortedYcoordinates[0])] #Showing the sideview of image cv2.imshow('side_view', img_side_view1) cv2.waitKey(0) cv2.destroyAllWindows() colors = vtk.vtkNamedColors() # Defining the points points = vtk.vtkPoints() idx = 0 for x in range(len(xCoordinate)): points.InsertNextPoint(yCoordinate[x], -xCoordinate[x], 0) idx += 1 #adding points in the polydata polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Create anything you want here, we will use a cube for the demo. cubeSource = vtk.vtkCubeSource() cubeSource.SetZLength(20.0) #assigning the cubesorce in the glyph glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceConnection(cubeSource.GetOutputPort()) glyph3D.SetInputData(polydata) glyph3D.Update() # storing all the pixel information in the side view points1 = vtk.vtkPoints() idx = 0 for x in range(len(xCoordinate_side_view)): points1.InsertNextPoint(sortedYcoordinates[0], -xCoordinate_side_view[x]+adjustmentInYdirection , yCoordinate_side_view[x] -ycoordinateTemp[0]) idx += 1 #Creating polydata for sideview polydata1 = vtk.vtkPolyData() polydata1.SetPoints(points1) # Create anything you want here, we will use a cube for the demo. cubeSource1 = vtk.vtkCubeSource() cubeSource1.SetXLength(20.0) #Glyph for sideview glyph3D1 = vtk.vtkGlyph3D() glyph3D1.SetSourceConnection(cubeSource1.GetOutputPort()) glyph3D1.SetInputData(polydata1) glyph3D1.Update() # copying information from the same handle to generate the other handle of the sunglass points2 = vtk.vtkPoints() idx = 0 for x in range(len(xCoordinate_side_view)): points2.InsertNextPoint(sortedYcoordinates[-1] - cubeSource1.GetXLength() / 2, -xCoordinate_side_view[x] + adjustmentInYdirection, yCoordinate_side_view[x]-ycoordinateTemp[0]) idx += 1 #Creating polydata for the remaining handle polydata2 = vtk.vtkPolyData() polydata2.SetPoints(points2) glyph3D2 = vtk.vtkGlyph3D() glyph3D2.SetSourceConnection(cubeSource1.GetOutputPort()) glyph3D2.SetInputData(polydata2) glyph3D2.Update() # Adding mapper for the distinct three polydatas mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph3D.GetOutputPort()) mapper1 = vtk.vtkPolyDataMapper() mapper1.SetInputConnection(glyph3D1.GetOutputPort()) mapper2 = vtk.vtkPolyDataMapper() mapper2.SetInputConnection(glyph3D2.GetOutputPort()) #Defining actors for the three mappers separately actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d("alizarin_crimson")) actor.SetMapper(mapper) actor1 = vtk.vtkActor() #actor1.GetProperty().SetColor(colors.GetColor3d("midnight_blue")) actor1.SetMapper(mapper1) actor2 = vtk.vtkActor() actor2.GetProperty().SetColor(colors.GetColor3d("MistyRose")) actor2.SetMapper(mapper2) #Grouping the three parts and scaling so that it is usable in unity3D or other 3D application assembly = vtk.vtkAssembly() assembly.AddPart(actor) assembly.AddPart(actor1) assembly.AddPart(actor2) assembly.SetScale(.01,.01,.01) #We tried to reduce the size of mesh, apparently it does not work without triangulated surface inputPoly = vtk.vtkPolyData() inputPoly.ShallowCopy(glyph3D.GetOutput()) print("Before decimation\n" "-----------------\n" "There are " + str(inputPoly.GetNumberOfPoints()) + "points.\n" "There are " + str( inputPoly.GetNumberOfPolys()) + "polygons.\n") decimate = vtk.vtkDecimatePro() decimate.SetInputData(inputPoly) decimate.SetTargetReduction(.10) decimate.Update() decimatedPoly = vtk.vtkPolyData() decimatedPoly.ShallowCopy(decimate.GetOutput()) print("After decimation \n" "-----------------\n" "There are " + str(decimatedPoly.GetNumberOfPoints()) + "points.\n" "There are " + str( decimatedPoly.GetNumberOfPolys()) + "polygons.\n") # Set object properties prop = actor.GetProperty() prop.SetInterpolationToPhong() # Set shading to Phong prop.ShadingOn() # prop.SetColor(0, 15, 26) prop.SetDiffuse(0.8) # 0.8 prop.SetAmbient(0.3) # 0.3 prop.SetSpecular(1.0) # 1.0 prop.SetSpecularPower(100.0) # 100.0 # Set object properties prop = actor1.GetProperty() prop.SetInterpolationToPhong() # Set shading to Phong prop.ShadingOn() # prop.SetColor(0, 51, 0) prop.SetDiffuse(0.8) # 0.8 prop.SetAmbient(0.3) # 0.3 prop.SetSpecular(1.0) # 1.0 prop.SetSpecularPower(100.0) # 100.0 # Set object properties prop = actor2.GetProperty() prop.SetInterpolationToPhong() # Set shading to Phong prop.ShadingOn() # prop.SetColor(1, 1, 0) prop.SetDiffuse(0.8) # 0.8 prop.SetAmbient(0.3) # 0.3 prop.SetSpecular(1.0) # 1.0 prop.SetSpecularPower(100.0) # 100.0 # Define light light = vtk.vtkLight() light.SetLightTypeToSceneLight() light.SetAmbientColor(1, 1, 1) light.SetDiffuseColor(1, 1, 1) light.SetSpecularColor(1, 1, 1) light.SetPosition(-100, 100, 25) light.SetFocalPoint(0, 0, 0) light.SetIntensity(1.0) # 0.8 # Define light light1 = vtk.vtkLight() light1.SetLightTypeToSceneLight() light1.SetAmbientColor(1, 1, 1) light1.SetDiffuseColor(1, 1, 1) light1.SetSpecularColor(1, 1, 1) light1.SetPosition(100, -100, -25) light1.SetFocalPoint(0, 0, 0) light1.SetIntensity(1.0) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(700, 700) renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.AddLight(light) renderer.AddLight(light1) renderer.AddActor(actor1) renderer.AddLight(light) renderer.AddActor(actor2) renderer.AddLight(light) renderer.SetBackground(colors.GetColor3d("slate_grey_light")) #Write the Obj file to disk objWriter = vtk.vtkOBJExporter() objWriter.SetFilePrefix("glass") objWriter.SetRenderWindow(renderWindow) objWriter.SetInputConnection(renderer) objWriter.Write() renderWindow.Render() renderWindowInteractor.Start()
def exportWindow(fileoutput, binary=False, speed=None, html=True): ''' Exporter which writes out the renderered scene into an OBJ, X3D or Numpy file. X3D is an XML-based format for representation 3D scenes (similar to VRML). Check out http://www.web3d.org/x3d for more details. :param float speed: set speed for x3d files. :param bool html: generate a test html page for x3d files. |export_x3d| |export_x3d.py|_ `generated webpage <https://vtkplotter.embl.es/examples/embryo.html>`_ See also: FEniCS test `webpage <https://vtkplotter.embl.es/examples/fenics_elasticity.html>`_. .. note:: the rendering window can also be exported to `numpy` file `scene.npy` by pressing ``E`` keyboard at any moment during visualization. ''' fr = fileoutput.lower() if ".obj" in fr: w = vtk.vtkOBJExporter() w.SetInputData(settings.plotter_instance.window) w.Update() colors.printc("~save Saved file:", fileoutput, c="g") elif ".x3d" in fr: exporter = vtk.vtkX3DExporter() exporter.SetBinary(binary) exporter.FastestOff() if speed: exporter.SetSpeed(speed) exporter.SetInput(settings.plotter_instance.window) exporter.SetFileName(fileoutput) exporter.Update() exporter.Write() if not html: return from vtkplotter.docs import x3d_html x3d_html = x3d_html.replace("~fileoutput", fileoutput) wsize = settings.plotter_instance.window.GetSize() x3d_html = x3d_html.replace("~width", str(wsize[0])) x3d_html = x3d_html.replace("~height", str(wsize[1])) #b = settings.plotter_instance.renderer.ComputeVisiblePropBounds() #s = max(b[1] - b[0], b[3] - b[2], b[5] - b[4]) #c = (b[1] + b[0])/2, (b[3] + b[2])/2, (b[5] + b[4])/2 #x3d_html = x3d_html.replace("~size", str(s*2)) #x3d_html = x3d_html.replace("~center", str(c[0])+" "+str(c[1])+" "+str(c[2])) outF = open(fileoutput.replace('.x3d', '.html'), "w") outF.write(x3d_html) outF.close() colors.printc("~save Saved files:", fileoutput, fileoutput.replace('.x3d', '.html'), c="g") elif ".npy" in fr: sdict = dict() vp = settings.plotter_instance sdict['shape'] = vp.shape #todo sdict['sharecam'] = vp.sharecam #todo sdict['camera'] = None #todo sdict['position'] = vp.pos sdict['size'] = vp.size sdict['axes'] = vp.axes sdict['title'] = vp.title sdict['xtitle'] = vp.xtitle sdict['ytitle'] = vp.ytitle sdict['ztitle'] = vp.ztitle sdict['backgrcol'] = colors.getColor(vp.backgrcol) sdict['useDepthPeeling'] = settings.useDepthPeeling sdict['renderPointsAsSpheres'] = settings.renderPointsAsSpheres sdict['renderLinesAsTubes'] = settings.renderLinesAsTubes sdict['hiddenLineRemoval'] = settings.hiddenLineRemoval sdict['visibleGridEdges'] = settings.visibleGridEdges sdict['interactorStyle'] = settings.interactorStyle sdict['useParallelProjection'] = settings.useParallelProjection sdict['objects'] = [] for a in vp.getActors() + vp.getVolumes(): sdict['objects'].append(_np_dump(a)) np.save(fileoutput, [sdict]) return
# print("creating limits file") mcReader.SetLimitsFileName(isoDir + 'iso.lim') mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(mcReader.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetSize(w, w) renWin.AddRenderer(ren) ren.AddActor(actor) # print("creating obj exporter") writer = vtk.vtkOBJExporter() writer.SetFilePrefix(isoDir + 'iso_' + str(percent) + '_percent') writer.SetInput(renWin) writer.Write() # print("creating append filter") polyDataAccum = vtk.vtkPolyData() connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetInputConnection(mcReader.GetOutputPort()) connectivity.SetExtractionModeToSpecifiedRegions() connectivity.ScalarConnectivityOff() connectivity.Update() numberOfRegions = connectivity.GetNumberOfExtractedRegions()