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 __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkRectilinearGridGeometryFilter(), 'Processing.', ('vtkRectilinearGrid',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, startX, startY, endX, endY, zValue=0, nPoints=20): self.xCoords = vtk.vtkFloatArray() self.yCoords = vtk.vtkFloatArray() self.zCoords = vtk.vtkFloatArray() for x in np.linspace(startX, endX, nPoints): self.xCoords.InsertNextValue(x) for y in np.linspace(startY, endY, nPoints): self.yCoords.InsertNextValue(y) for z in [zValue]: self.zCoords.InsertNextValue(z) self.rgrid = vtk.vtkRectilinearGrid() self.rgrid.SetDimensions(nPoints, nPoints, 1) self.rgrid.SetXCoordinates(self.xCoords) self.rgrid.SetYCoordinates(self.yCoords) self.rgrid.SetZCoordinates(self.zCoords) self.plane = vtk.vtkRectilinearGridGeometryFilter() self.plane.SetInputData(self.rgrid) self.plane.SetExtent(0, nPoints - 1, 0, nPoints - 1, 0, 0) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.plane.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetRepresentationToWireframe() self.actor.GetProperty().SetColor((0, 0, 0)) self.actor.GetProperty().EdgeVisibilityOn() return
def _set_input (self): """ This function tries its best to generate an appropriate input for the Normals. If one has an input StructuredGrid or StructuredPoints or even a RectilinearGrid the PolyDataNormals will not work. In order for it to work an appropriate intermediate filter is used to create the correct output.""" debug ("In PolyDataNormals::_set_input ()") out = self.prev_fil.GetOutput () f = None if out.IsA ('vtkStructuredGrid'): f = vtk.vtkStructuredGridGeometryFilter () elif out.IsA ('vtkRectilinearGrid'): f = vtk.vtkRectilinearGridGeometryFilter () elif out.IsA ('vtkStructuredPoints') or out.IsA('vtkImageData'): if hasattr (vtk, 'vtkImageDataGeometryFilter'): f = vtk.vtkImageDataGeometryFilter () else: f = vtk.vtkStructuredPointsGeometryFilter () elif out.IsA('vtkUnstructuredGrid'): f = vtk.vtkGeometryFilter() elif out.IsA('vtkPolyData'): f = None else: msg = "This module does not support the given "\ "output - %s "%(out.GetClassName ()) raise Base.Objects.ModuleException, msg if f: f.SetInput (out) self.fil.SetInput (f.GetOutput ()) else: self.fil.SetInput(out)
def loadRectilinearGrid(filename): # not tested '''Load a vtkRectilinearGrid object from file and return a vtkActor.''' reader = vtk.vtkRectilinearGridReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtkRectilinearGridGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() return Actor(gf.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkRectilinearGridGeometryFilter(), "Processing.", ("vtkRectilinearGrid",), ("vtkPolyData",), replaceDoc=True, inputFunctions=None, outputFunctions=None, )
def set_vtk_data(self): """ :return: """ div1 = np.linspace(self.x_min, self.x_max, self.N) div2 = np.linspace(self.y_min, self.y_max, self.N) self.n3 = np.zeros_like(div1) self.n1, self.n2 = np.meshgrid(div1, div2) self.grid_nodes = np.array([ self.n1, self.n2, ]) # predefine vtk array x = vtk.vtkFloatArray() y = vtk.vtkFloatArray() z = vtk.vtkFloatArray() N = len(self.n1.flatten()) for n1_i in self.n1.flatten(): x.InsertNextValue(n1_i) for n2_i in self.n2.flatten(): y.InsertNextValue(n2_i) for n3_i in self.n3.flatten(): z.InsertNextValue(n3_i) self.vtk_grid = vtk.vtkRectilinearGrid() self.vtk_grid.SetDimensions(N, N, N) self.vtk_grid.SetXCoordinates(x) self.vtk_grid.SetYCoordinates(y) self.vtk_grid.SetZCoordinates(z) # extract a plane from the grid to see what we've got self.vtk_plane = vtk.vtkRectilinearGridGeometryFilter() self.vtk_plane.SetInputData(self.vtk_grid) self.vtk_plane.SetExtent(0, N - 1, 0, N - 1, 0, 0) self.vtk_mapper = vtk.vtkPolyDataMapper() self.vtk_mapper.SetInputConnection(self.vtk_plane.GetOutputPort()) self.vtk_actor = vtk.vtkActor() self.vtk_actor.SetMapper(self.vtk_mapper) self.vtk_actor.GetProperty().SetRepresentationToWireframe() # self.vtk_actor.GetProperty().SetColor(self.color) self.vtk_actor.GetProperty().SetColor(.5, .5, .5)
def build_plane(position, params, colour): """ Generates floor plane using individual layered rectilinear grids """ x = np.arange(params[0], params[1], params[2]) y = np.arange(params[0], params[1], params[2]) z = np.arange(params[0], params[1], params[2]) # Create a rectilinear grid by defining three arrays specifying the # coordinates in the x-y-z directions. x_coords = vtk.vtkFloatArray() for i in x: x_coords.InsertNextValue(i) y_coords = vtk.vtkFloatArray() for i in y: y_coords.InsertNextValue(i) z_coords = vtk.vtkFloatArray() for i in z: z_coords.InsertNextValue(i) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(len(x), len(y), len(z)) rgrid.SetXCoordinates(x_coords) rgrid.SetYCoordinates(y_coords) rgrid.SetZCoordinates(z_coords) # Extract a plane from the grid plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) plane.SetExtent(0, 46, 0, 46, 0, 0) rgrid_mapper = vtk.vtkPolyDataMapper() rgrid_mapper.SetInputConnection(plane.GetOutputPort()) wire_actor = vtk.vtkActor() wire_actor.SetMapper(rgrid_mapper) wire_actor.GetProperty().SetRepresentationToWireframe() wire_actor.GetProperty().SetColor(colour) wire_actor.SetOrientation(0, 0, 90) wire_actor.GetProperty().LightingOff() wire_actor.SetPosition(3000, -2000, position) return wire_actor
def do_contour (self, event=None): debug ("In BandedSurfaceMap::do_contour ()") Common.state.busy () if self.contour_on.get (): if not self.mod_m.get_scalar_data_name (): self.contour_on.set (0) msg = "Warning: No scalar data present to contour!" Common.print_err (msg) Common.state.idle () return out = self.mod_m.GetOutput () if out.IsA('vtkPolyData'): f = None elif out.IsA ('vtkStructuredGrid'): f = vtk.vtkStructuredGridGeometryFilter () elif out.IsA ('vtkRectilinearGrid'): f = vtk.vtkRectilinearGridGeometryFilter () elif out.IsA ('vtkStructuredPoints') or \ out.IsA('vtkImageData'): if hasattr (vtk, 'vtkImageDataGeometryFilter'): f = vtk.vtkImageDataGeometryFilter () else: f = vtk.vtkStructuredPointsGeometryFilter () elif out.IsA('vtkUnstructuredGrid'): f = vtk.vtkGeometryFilter() else: msg = "This module does not support the given "\ "output - %s "%(out.GetClassName ()) raise Base.Objects.ModuleException, msg if f: f.SetInput (out) self.cont_fil.SetInput (f.GetOutput()) else: self.cont_fil.SetInput (out) self.map.SetInput (self.cont_fil.GetOutput ()) self.map.SetScalarModeToUseCellData() else: self.map.SetInput (self.mod_m.GetOutput ()) self.map.SetScalarModeToDefault() self.change_contour () Common.state.idle ()
#help(vtk.vtkRectilinearGridReader()) rectGridReader = vtk.vtkRectilinearGridReader() rectGridReader.SetFileName("data/jet4_0.500.vtk") # do not forget to call "Update()" at the end of the reader rectGridReader.Update() rectGridOutline = vtk.vtkRectilinearGridOutlineFilter() rectGridOutline.SetInputData(rectGridReader.GetOutput()) # New vtkRectilinearGridGeometryFilter() goes here: # # # # plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rectGridReader.GetOutput()) rectGridOutlineMapper = vtk.vtkPolyDataMapper() rectGridOutlineMapper.SetInputConnection(rectGridOutline.GetOutputPort()) rectGridGeomMapper = vtk.vtkPolyDataMapper() rectGridGeomMapper.SetInputConnection(plane.GetOutputPort()) # outlineActor = vtk.vtkActor() outlineActor.SetMapper(rectGridOutlineMapper) outlineActor.GetProperty().SetColor(0, 0, 0) gridGeomActor = vtk.vtkActor() gridGeomActor.SetMapper(rectGridGeomMapper)
This is a temporary script file. """ #============================================================================== # Challenge 1: Adding a new Filter+Mapper+Actor to visualize the grid #============================================================================== import vtk rectGridReader = vtk.vtkRectilinearGridReader() rectGridReader.SetFileName("data/jet4_0.500.vtk") rectGridReader.Update() rectGridOutline = vtk.vtkRectilinearGridOutlineFilter() rectGridOutline.SetInputData(rectGridReader.GetOutput()) rectGridGeom = vtk.vtkRectilinearGridGeometryFilter() rectGridGeom.SetInputData(rectGridReader.GetOutput()) rectGridOutlineMapper = vtk.vtkPolyDataMapper() rectGridOutlineMapper.SetInputConnection(rectGridOutline.GetOutputPort()) rectGridGeomMapper = vtk.vtkPolyDataMapper() rectGridGeomMapper.SetInputConnection(rectGridGeom.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(rectGridOutlineMapper) outlineActor.GetProperty().SetColor(1, 1, 1) wireActor = vtk.vtkActor() wireActor.SetMapper(rectGridGeomMapper) wireActor.GetProperty().SetRepresentationToWireframe()
def main(): colors = vtk.vtkNamedColors() # Create polydata to slice the grid with. In this case, use a cone. This could # be any polydata including a stl file. cone = vtk.vtkConeSource() cone.SetResolution(20) cone.Update() # implicit function that will be used to slice the mesh implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance() implicitPolyDataDistance.SetInput(cone.GetOutput()) # create a grid xCoords = vtk.vtkFloatArray() for x, i in enumerate(np.linspace(-1.0, 1.0, 15)): xCoords.InsertNextValue(i) yCoords = vtk.vtkFloatArray() for y, i in enumerate(np.linspace(-1.0, 1.0, 15)): yCoords.InsertNextValue(i) zCoords = vtk.vtkFloatArray() for z, i in enumerate(np.linspace(-1.0, 1.0, 15)): zCoords.InsertNextValue(i) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(x + 1, y + 1, z + 1) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # Evaluate the signed distance function at all of the grid points for pointId in range(rgrid.GetNumberOfPoints()): p = rgrid.GetPoint(pointId) signedDistance = implicitPolyDataDistance.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # add the SignedDistances to the grid rgrid.GetPointData().SetScalars(signedDistances) # use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipDataSet() clipper.SetInputData(rgrid) clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() # --- mappers, actors, render, etc. --- # mapper and actor to view the cone coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) # geometry filter to view the background grid geometryFilter = vtk.vtkRectilinearGridGeometryFilter() geometryFilter.SetInputData(rgrid) geometryFilter.SetExtent(0, x + 1, 0, y + 1, (z + 1) // 2, (z + 1) // 2) geometryFilter.Update() rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(geometryFilter.GetOutputPort()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() wireActor.GetProperty().SetColor(colors.GetColor3d('Black')) # mapper and actor to view the clipped mesh clipperMapper = vtk.vtkDataSetMapper() clipperMapper.SetInputConnection(clipper.GetOutputPort()) clipperActor = vtk.vtkActor() clipperActor.SetMapper(clipperMapper) clipperActor.GetProperty().SetRepresentationToWireframe() clipperActor.GetProperty().SetColor(colors.GetColor3d('Black')) # A renderer and render window renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d('White')) # add the actors # renderer.AddActor(coneActor) renderer.AddActor(wireActor) renderer.AddActor(clipperActor) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(renderer) # An interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) # Start interactor.Initialize() renwin.Render() renderer.GetActiveCamera().SetPosition(0, -1, 0) renderer.GetActiveCamera().SetFocalPoint(0, 0, 0) renderer.GetActiveCamera().SetViewUp(0, 0, 1) renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCamera() renwin.Render() interactor.Start()
def main(): colors = vtk.vtkNamedColors() x = [-1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042, -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042, 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458, 0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, 0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458, 0.963542, 1.01562, 1.06771, 1.11979, 1.17188] y = [-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625, -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, 0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875, 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, 1.09375, 1.17188, 1.25] z = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.75, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9] print(len(x), len(y), len(z)) # Create a rectilinear grid by defining three arrays specifying the # coordinates in the x-y-z directions. xCoords = vtk.vtkDoubleArray() for i in range(0, len(x)): xCoords.InsertNextValue(x[i]) yCoords = vtk.vtkDoubleArray() for i in range(0, len(y)): yCoords.InsertNextValue(y[i]) zCoords = vtk.vtkDoubleArray() for i in range(0, len(z)): zCoords.InsertNextValue(z[i]) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). # rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(len(x), len(y), len(z)) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Extract a plane from the grid to see what we've got. plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) plane.SetExtent(0, len(x) - 1, 16, 16, 0, len(z) - 1) rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(plane.GetOutputPort()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetColor(colors.GetColor3d("Banana")) wireActor.GetProperty().EdgeVisibilityOn() # Create the usual rendering stuff. renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor(wireActor) renderer.SetBackground(colors.GetColor3d("Beige")) renderer.ResetCamera() renderer.GetActiveCamera().Elevation(60.0) renderer.GetActiveCamera().Azimuth(30.0) renderer.GetActiveCamera().Zoom(1.0) renWin.SetSize(640, 480) # Interact with the data. renWin.Render() iren.Start()
do2ds.SetPointComponent(2, "ZCoordinates", 0) do2ds.Update() fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputData(do2ds.GetRectilinearGridOutput()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.SetVectorComponent(0, "vectors", 0) fd2ad.SetVectorComponent(1, "vectors", 1) fd2ad.SetVectorComponent(2, "vectors", 2) fd2ad.SetScalarComponent(0, "scalars", 0) fd2ad.Update() # create pipeline # plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(fd2ad.GetRectilinearGridOutput()) plane.SetExtent(0, 100, 0, 100, 15, 15) warper = vtk.vtkWarpVector() warper.SetInputConnection(plane.GetOutputPort()) warper.SetScaleFactor(0.05) planeMapper = vtk.vtkDataSetMapper() planeMapper.SetInputConnection(warper.GetOutputPort()) planeMapper.SetScalarRange(0.197813, 0.710419) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) cutPlane = vtk.vtkPlane()
def main(args): # Load config file config_module = imp.load_source('config', args.config_path) # Get cfg dict cfg = config_module.cfg # Get model model = config_module.get_model(interp=True) # Compile functions print('Compiling theano functions...') tfuncs, tvars = make_test_functions(cfg, model) # Load model weights print('Loading weights from {}'.format(args.weights_fname)) checkpoints.load_weights(args.weights_fname, model['l_latents']) checkpoints.load_weights(args.weights_fname, model['l_out']) # prepare data loader loader = (data_loader(cfg, args.testing_fname)) # Load test set into local memory and get inferred latent values for each # element of the test set. Consider not doing this if you have limited RAM. print('Evaluating on test set') ygnd = np.empty([1,1,32,32,32],dtype=np.uint8) cc = np.empty([1,10],dtype=np.float32) counter = 0 for x_shared, y_shared in loader: ygnd = np.append(ygnd,x_shared,axis=0) cc = np.append(cc,y_shared,axis=0) # Get rid of first entries. Yeah, you could do this better by starting with a regular ole' python list, # appending inside the for loop and then just calling np.asarray, but I didn't really know any python # when I wrote this. Sue me.* # # *Please don't sue me ygnd = np.delete(ygnd,0,axis=0) cc = np.delete(cc,0,axis=0) print('Test set evaluation complete, render time!') # Total number of models loaded and encoded num_instances = len(ygnd)-1; # Seed the rng for repeatable operation np.random.seed(1) # Index of shuffled data display_ix = np.random.choice(len(ygnd), num_instances,replace=False) # Resolution: Number of blocks per side on each voxel. Setting this to less than 3 # results in some ugly renderings, though it will be faster. Setting it higher makes it # prettier but can slow it down. With this setting, I can run interpolation in real-time on # a laptop with 16GB RAM and a GT730M. A setup with a real graphics card should be able to do # much, much more. v_res = 3 # Dimensionality of the voxel grid dim = 32 # Function to produce the data matrix for rendering. def make_data_matrix(x,intensity): return intensity*np.repeat(np.repeat(np.repeat(x[0][0],v_res,axis=0),v_res,axis=1),v_res,axis=2) # VTK Image Importer dataImporter = vtk.vtkImageImport() # Make the initial data matrix # initial random latent vector z_1 = np.random.randn(1,cfg['num_latents']).astype(np.float32) if cfg['cc']: # If augmenting with class-conditional vector cc_1 = np.zeros((1,10),dtype=np.float32) cc_1[0,np.random.randint(10)] = 1 data_matrix = make_data_matrix(np.asarray(tfuncs['pred'](z_1,cc_1),dtype=np.uint8),128) else: data_matrix = make_data_matrix(np.asarray(tfuncs['pred'](z_1),dtype=np.uint8),128) # VTK bookkeeping stuff to prepare the central model data_string = data_matrix.tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1) dataImporter.SetWholeExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1) # Prepare the interpolant endpoints # endpoint data importer edi = [0,0,0,0] # Endpoint data matrices dm = [0,0,0,0] # Endpoint Latent values eZ = [0,0,0,0] # Endpoint sigmas eS = [0,0,0,0] # Endpoint class-conditional values eCC = [0,0,0,0] # Endpoint intensity values for colormapping eIs = [64,128,192,255] # VTK Bookkeeping stuff for interpolant endpoints for i in xrange(4): eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[i]])[0] eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[i]])[0] eCC[i] = cc[None,display_ix[i]] # This may need changing to preserve shape? to be a 1x10 matrix instead of a 10x1? dm[i] = make_data_matrix(ygnd[None,display_ix[i]],eIs[i]).tostring() edi[i] = vtk.vtkImageImport() edi[i].CopyImportVoidPointer(dm[i], len(dm[i])) edi[i].SetDataScalarTypeToUnsignedChar() edi[i].SetNumberOfScalarComponents(1) edi[i].SetDataExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1) edi[i].SetWholeExtent(0, int(dim*v_res)-1, 0, int(dim*v_res)-1, 0, int(dim*v_res)-1) # Prepare color and transparency values colorFunc = vtk.vtkColorTransferFunction() alphaChannelFunc = vtk.vtkPiecewiseFunction() alphaChannelFunc.AddPoint(0, 0.0) alphaChannelFunc.AddPoint(64,1) alphaChannelFunc.AddPoint(128,1.0) alphaChannelFunc.AddPoint(192,1.0) alphaChannelFunc.AddPoint(255,1.0) colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0) colorFunc.AddRGBPoint(64, 0.0, 0.4, 0.8) colorFunc.AddRGBPoint(128,0.8,0.0,0.0) colorFunc.AddRGBPoint(192,0.8,0.0,0.7) colorFunc.AddRGBPoint(255,0.0,0.8,0.0) # Prepare volume properties. volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorFunc) volumeProperty.SetScalarOpacity(alphaChannelFunc) volumeProperty.ShadeOn() # Keep this on unless you want everything to look terrible volumeProperty.SetInterpolationTypeToNearest() # Optional settings # volumeProperty.SetSpecular(0.2) # volumeProperty.SetAmbient(0.4) # volumeProperty.SetDiffuse(0.6) # More VTK Bookkeeping stuff. compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() # Specify the data and raycast methods for the rendered volumes. volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetVolumeRayCastFunction(compositeFunction) volumeMapper.SetInputConnection(dataImporter.GetOutputPort()) # Endpoint volumeMappers evm = [0,0,0,0] for i in xrange(4): evm[i] = vtk.vtkVolumeRayCastMapper() evm[i].SetVolumeRayCastFunction(compositeFunction) evm[i].SetInputConnection(edi[i].GetOutputPort()) # Prepare the volume for the draggable model. volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) volume.SetPosition([0, 0, 0]) # Endpoint volumes ev = [0,0,0,0] vps = [[0,-150.0,-150.0],[0,150.0,-150.0],[0,-150.0,150.0],[0,150.0,150.0]] for i in xrange(4): ev[i] = vtk.vtkVolume() ev[i].SetMapper(evm[i]) ev[i].SetProperty(volumeProperty) ev[i].SetPosition(vps[i]) ev[i].DragableOff() ev[i].PickableOff() # Simple linear 2D Interpolation function for interpolation between latent values. # Feel free to extend this to use more advanced interpolation methods. def interp2d(x,y,z_): x1 = vps[0][1]+97.5 x2 = vps[1][1] y1 = vps[0][2]+97.5 y2 = vps[2][2] return ( ( (z_[0] * (x2-x) * (y2-y)) + (z_[1] * (x-x1) * (y2-y)) + (z_[2] * (x2-x) * (y-y1)) + (z_[3] * (x-x1) * (y-y1)) ) / ( (x2-x1) * (y2-y1) ) ) ### Interactor Style # This class defines the user interface, and how the system reacts to different user inputs. class MyInteractorStyle(vtk.vtkInteractorStyleSwitch): def __init__(self,parent=None): # Index indicating which models are currently selected for endpoints self.ix = 0 # Togglable flag indicating if the center model is being dragged or not self.drag = 0; # Picker self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.001) # Set up observers. These functions watch for specific user actions. self.SetCurrentStyleToTrackballActor() self.GetCurrentStyle().AddObserver("MiddleButtonReleaseEvent",self.middleButtonReleaseEvent) self.GetCurrentStyle().AddObserver("MouseMoveEvent",self.mouseMoveEvent) self.SetCurrentStyleToTrackballCamera() self.GetCurrentStyle().AddObserver("MiddleButtonPressEvent",self.middleButtonPressEvent) self.GetCurrentStyle().AddObserver("KeyPressEvent",self.keyPress) # def mouseMoveEvent(self,obj,event): # Re-render every time the user moves the mouse while clicking. # If you have a slow computer, consider changing this to be thresholded so as to only have a certain resolution # (i.e. to only change if the mouse moves a certain distance, rather than any move) if self.drag and self.picker.GetProp3D(): # Move object. This is a rewrite of the raw move object code; # Normally you would do this with the built-in version of this function and extend # it pythonically in the normal way, but the python bindings for VTK don't expose # this function in that way (it's all hard-coded in C++) so this is a simple # re-implementation that gives more control over how the object is moved. # Specifically, this constrains the draggable object to only move in-plane # and prevents it going out of bounds. center = self.picker.GetProp3D().GetCenter() display_center = [0,0,0] new_point = [0,0,0,0] old_point = [0,0,0,0] motion_vector = [0,0] event_pos = self.GetCurrentStyle().GetInteractor().GetEventPosition() last_event_pos = self.GetCurrentStyle().GetInteractor().GetLastEventPosition() self.ComputeWorldToDisplay(self.GetDefaultRenderer(), center[0], center[1], center[2], display_center) self.ComputeDisplayToWorld(self.GetDefaultRenderer(), event_pos[0], event_pos[1], display_center[2], new_point) self.ComputeDisplayToWorld(self.GetDefaultRenderer(), last_event_pos[0], last_event_pos[1], display_center[2], old_point) # Calculate the position change, making sure to confine the object to within the boundaries. # Consider finding a way to do this so that it depends on position of center instead of mouse new_point[1] = max(min(vps[1][1], new_point[1]), vps[0][1]+97.5) new_point[2] = max(min(vps[2][2], new_point[2]), vps[0][2]+97.5) old_point[1] = max(min(vps[1][1], self.picker.GetProp3D().GetCenter()[1]), vps[0][1]+97.5) old_point[2] = max(min(vps[2][2], self.picker.GetProp3D().GetCenter()[2]), vps[0][2]+97.5) # Increment the position self.picker.GetProp3D().AddPosition(0,new_point[1]-old_point[1],new_point[2]-old_point[2]) # Update Data if cfg['cc']: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)], interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eCC)), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() else: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)]), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() # Update the renderer's pointer to the data so that the GUI has the updated data. dataImporter.CopyImportVoidPointer(data_string, len(data_string)) # Update the window. self.GetCurrentStyle().GetInteractor().Render() return # If the middle button is used to select the center object, change to # dragging mode. Else, use it to pan the view. def middleButtonPressEvent(self,obj,event): clickPos = self.GetCurrentStyle().GetInteractor().GetEventPosition() self.picker.Pick(clickPos[0],clickPos[1],0,self.GetDefaultRenderer()) if self.picker.GetProp3D(): self.SetCurrentStyleToTrackballActor() self.drag=1 # Optional: Add the ability to modify interpolant endpoints. # else: # If we click an interpolant endpoint, change that endpoint somehow. # self.drag = 0 self.GetCurrentStyle().OnMiddleButtonDown() # self.GetCurrentStyle().HighlightProp3D(volume) return # When we release, change style from TrackballActor to TrackballCamera. def middleButtonReleaseEvent(self,obj,event): self.SetCurrentStyleToTrackballCamera() self.drag=0 self.GetCurrentStyle().OnMiddleButtonUp() return # If the user presses an arrow key, swap out interpolant endpoints and re-render. # If the user hits space, sample randomly in the latent space and re-render. # If class-conditional vectors are enabled and the user hits 1-9, render a random # class-conditional object. def keyPress(self,obj,event): key=self.GetCurrentStyle().GetInteractor().GetKeySym() if key == 'Right': # Increment index of which models we're using, re-render all endpoints self.ix+=1 for i in xrange(4): eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[self.ix+i]])[0] eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[self.ix+i]])[0] eCC[i] = cc[None,display_ix[self.ix+i]] dm[i] = make_data_matrix(ygnd[None,display_ix[self.ix+i]],eIs[i]).tostring() edi[i].CopyImportVoidPointer(dm[i], len(dm[i])) if cfg['cc']: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)], interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eCC)), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() else: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)]), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) elif key == 'Left' and (self.ix > 0): self.ix-=1 for i in xrange(4): eZ[i] = tfuncs['Zfn'](ygnd[None,display_ix[self.ix+i]])[0] eS[i] = tfuncs['sigma_fn'](ygnd[None,display_ix[self.ix+i]])[0] eCC[i] = cc[None,display_ix[self.ix+i]] dm[i] = make_data_matrix(ygnd[None,display_ix[self.ix+i]],eIs[i]).tostring() edi[i].CopyImportVoidPointer(dm[i], len(dm[i])) if cfg['cc']: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)], interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eCC)), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() else: data_string = make_data_matrix(np.asarray(tfuncs['pred']([interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)]), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) elif key == 'space': # Random Z, with optional weighting. Z_rand = 0.5*np.random.randn(1,cfg['num_latents']).astype(np.float32) # Optionally, sample using the interpolated sigmas as well. # Z_rand = np.square(np.exp(interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eS))*np.random.randn(1,cfg['num_latents']).astype(np.float32)) if cfg['cc']: # if class-conditional, take the class vector into account cc_rand = np.zeros((1,10),dtype=np.float32) cc_rand[0,np.random.randint(10)] = 1 data_string = make_data_matrix(np.asarray(tfuncs['pred'](interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eZ)+Z_rand,cc_rand), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() else: data_string = make_data_matrix(np.asarray(tfuncs['pred'](Z_rand), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) # Generate random Class-conditional Z elif 0<= int(float(key))<=9 and cfg['cc']: cc_rand = np.zeros((1,10),dtype=np.float32) cc_rand[0,int(float(key))] = 5 Z_rand = np.square(np.exp(interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eS)))*np.random.randn(1,cfg['num_latents']).astype(np.float32)+interp2d(volume.GetCenter()[1],volume.GetCenter()[2],eZ) data_string = make_data_matrix(np.asarray(tfuncs['pred'](Z_rand,cc_rand), dtype=np.uint8), int(interp2d(volume.GetCenter()[1], volume.GetCenter()[2],eIs))).tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) # print(key) # Render and pass event on self.GetCurrentStyle().GetInteractor().Render() self.GetCurrentStyle().OnKeyPress() return # Initialize the render window renderer = vtk.vtkRenderer() renderWin = vtk.vtkRenderWindow() renderWin.AddRenderer(renderer) # Initialize the render interactor renderInteractor = vtk.vtkRenderWindowInteractor() style = MyInteractorStyle() style.SetDefaultRenderer(renderer) renderInteractor.SetInteractorStyle(style)#volume_set=volume,Lvolume_set = Lvolume, Rvolume_set = Rvolume)) renderInteractor.SetRenderWindow(renderWin) # Make boundary plane rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(1,2,2) xCoords = vtk.vtkFloatArray() xCoords.InsertNextValue(30) yCoords = vtk.vtkFloatArray() yCoords.InsertNextValue(vps[0][1]+97.5) yCoords.InsertNextValue(vps[1][1]) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(yCoords) plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(plane.GetOutputPort()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() wireActor.GetProperty().SetColor(0, 0, 0) wireActor.PickableOff() wireActor.DragableOff() # Add model, endpoints, and boundary plane to renderer renderer.AddActor(wireActor) for i in xrange(4): renderer.AddVolume(ev[i]) renderer.AddVolume(volume) # set background to white. Optionally change it to a fun color, like "Lifeblood of the Untenderized." renderer.SetBackground(1.0,1.0,1.0) # Set initial window size. You can drag the window to change size, but keep in mind that # the larger the window, the slower this thing runs. On my laptop, I get little spikes # of lag when I run this on full screen, though a more graphics-cardy setup should do fine. renderWin.SetSize(400, 400) # Exit function def exitCheck(obj, event): if obj.GetEventPending() != 0: obj.SetAbortRender(1) # Add exit function renderWin.AddObserver("AbortCheckEvent", exitCheck) # initialize interactor renderInteractor.Initialize() # Start application! renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(20) renderer.GetActiveCamera().Dolly(2.8) renderer.ResetCameraClippingRange() renderWin.Render() renderInteractor.Start()
def render(self, **args): """ main function to render all required objects """ gridData = args.get('gridData', True) drawSurface = args.get('drawSurface', True) drawAxes = args.get('drawAxes', True) drawColorBar = args.get('drawColorBar', True) drawLegend = args.get('drawLegend', True) wireSurface = args.get('wireSurface', False) drawBox = args.get('drawBox', True) scaleFactor = args.get('scaleFactor', (1, 1, 1)) autoscale = args.get('autoScale', True) colorMap = args.get('colorMap', 'rainbow') reverseMap = args.get('reverseMap', False) drawGrid = args.get('drawGrid', False) resolution = args.get('gridResolution', 10) xtics = args.get('xtics', 0) ytics = args.get('ytics', 0) ztics = args.get('ztics', 0) planeGrid = args.get('planeGrid', True) xCutterOn = args.get('XCutterOn', True) yCutterOn = args.get('YCutterOn', True) zCutterOn = args.get('ZCutterOn', True) xCutterPos = args.get('XCutterPos', None) yCutterPos = args.get('YCutterPos', None) zCutterPos = args.get('ZCutterPos', None) self.parseRenderArgs(**args) if gridData: geometry = vtk.vtkStructuredGridGeometryFilter() else: geometry = vtk.vtkRectilinearGridGeometryFilter() geometry.SetInputData(self.gridfunc) geometry.SetExtent(self.gridfunc.GetExtent()) if gridData: wzscale = self.computeScale(self.gridfunc) self.out = geometry.GetOutput() else: geometry.SetExtent(self.gridfunc.GetExtent()) geometry.GetOutput().SetPoints(self.Points) geometry.GetOutput().GetPointData().SetScalars(self.Colors) geometry.GetOutput().Update() self.out = geometry.GetOutput() self.out.SetPoints(self.Points) self.out.GetPointData().SetScalars(self.Colors) self.out.Update() wzscale = self.computeScale(self.out) x = self.XScale if autoscale else self.XScale * scaleFactor[0] y = self.YScale if autoscale else self.YScale * scaleFactor[1] z = 0.5 * self.ZScale if autoscale else self.ZScale * scaleFactor[2] transform = vtk.vtkTransform() transform.Scale(x, y, z) trans = vtk.vtkTransformPolyDataFilter() trans.SetInputConnection(geometry.GetOutputPort()) trans.SetTransform(transform) localScale = wzscale if wzscale < 1 else 1 / wzscale self.warp = vtk.vtkWarpScalar() self.warp.XYPlaneOn() self.warp.SetInputConnection(trans.GetOutputPort()) self.warp.SetNormal(0, 0, 1) self.warp.UseNormalOn() self.warp.SetScaleFactor(localScale) tmp = self.gridfunc.GetScalarRange() # map gridfunction self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.warp.GetOutputPort()) # calculate ranges if self.customZRange: self.mapper.SetScalarRange(*self.customZRange) elif self.autoZRange: mx = max(abs(tmp[0]), abs(tmp[1])) self.mapper.SetScalarRange(-mx, mx) else: self.mapper.SetScalarRange(tmp[0], tmp[1]) wireActor = None bounds = self.mapper.GetBounds() # wire mapper if planeGrid: if not gridData: self.plane = vtk.vtkRectilinearGridGeometryFilter() self.plane.SetInput(self.gridfunc) self.plane.SetExtent(self.gridfunc.GetExtent()) x_, y_ = x, y else: self.plane = vtk.vtkPlaneSource() self.plane.SetXResolution(resolution) self.plane.SetYResolution(resolution) x_, y_ = bounds[1] - bounds[0], bounds[3] - bounds[2] pltr = vtk.vtkTransform() pltr.Translate((bounds[1] - bounds[0]) / 2. - (0 - bounds[0]), (bounds[3] - bounds[2]) / 2. - (0 - bounds[2]), bounds[4]) pltr.Scale(x_, y_, 1) pltran = vtk.vtkTransformPolyDataFilter() pltran.SetInputConnection(self.plane.GetOutputPort()) pltran.SetTransform(pltr) cmap = self.buildColormap('black-white', True) rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(pltran.GetOutputPort()) rgridMapper.SetLookupTable(cmap) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() wireActor.GetProperty().SetColor(self.fgColor) # xcutter actor xactor = None if xCutterOn: xactor = self.makeXCutter(bounds, scaleFactor, xCutterPos) # ycutter actor yactor = None if yCutterOn: yactor = self.makeYCutter(bounds, scaleFactor, yCutterPos) # zcutter actor zactor = None if zCutterOn: zactor = self.makeZCutter(bounds, scaleFactor, zCutterPos) # create plot surface actor surfplot = vtk.vtkActor() surfplot.SetMapper(self.mapper) if wireSurface: surfplot.GetProperty().SetRepresentationToWireframe() # color map clut = self.buildColormap(colorMap, reverseMap) self.mapper.SetLookupTable(clut) # create outline outlinefilter = vtk.vtkOutlineFilter() outlinefilter.SetInputConnection(self.warp.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outlinefilter.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(outlineMapper) outline.GetProperty().SetColor(self.fgColor) # make axes zax, axes = self.makeAxes(outline, outlinefilter) # setup axes xaxis = axes.GetXAxisActor2D() yaxis = axes.GetYAxisActor2D() zaxis = axes.GetZAxisActor2D() xaxis.SetLabelFormat(self.config.XLabelsFormat()) xaxis.SetAdjustLabels(1) xaxis.SetNumberOfMinorTicks(xtics) yaxis.SetLabelFormat(self.config.YLabelsFormat()) yaxis.SetNumberOfMinorTicks(ytics) yaxis.SetAdjustLabels(1) zaxis.SetLabelFormat(self.config.ZLabelsFormat()) zaxis.SetNumberOfMinorTicks(ztics) zaxis.SetAdjustLabels(1) # create colorbar colorbar = self.makeColorbar() # renderer if drawSurface: self.renderer.AddActor(surfplot) self.actors.append(surfplot) if drawGrid: self.renderer.AddViewProp(zax) self.actors.append(zax) if planeGrid: self.renderer.AddActor(wireActor) self.actors.append(wireActor) if drawBox: self.renderer.AddActor(outline) self.actors.append(outline) if drawAxes: self.renderer.AddViewProp(axes) self.actors.append(axes) if drawColorBar or drawLegend: self.renderer.AddActor(colorbar) self.actors.append(colorbar) self.colorbar = colorbar self._addPlaneCutters(xactor, yactor, zactor, xCutterOn, yCutterOn, zCutterOn)
def __init__(self): x = [ -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042, -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042, 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458, 0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, 0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458, 0.963542, 1.01562, 1.06771, 1.11979, 1.17188] y = [ -1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625, -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, 0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875, 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, 1.09375, 1.17188, 1.25] z = [ 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.75, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9] # Create a rectilinear grid by defining three arrays specifying the # coordinates in the x-y-z directions. xCoords = vtk.vtkFloatArray() for i in x: xCoords.InsertNextValue(i) yCoords = vtk.vtkFloatArray() for i in y: yCoords.InsertNextValue(i) zCoords = vtk.vtkFloatArray() for i in z: zCoords.InsertNextValue(i) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). # rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(len(x), len(y), len(z)) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Extract a plane from the grid to see what we've got. plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) plane.SetExtent(0, 46, 16, 16, 0, 43) rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(plane.GetOutputPort()) self.wire_actor = vtk.vtkActor() self.wire_actor.SetMapper(rgridMapper) self.wire_actor.GetProperty().SetRepresentationToWireframe() self.wire_actor.GetProperty().SetColor(0, 0, 0)
def main(): colors = vtk.vtkNamedColors() # Create polydata to slice the grid with. In this case, use a cone. This # could # be any polydata including a stl file. cone = vtk.vtkConeSource() cone.SetResolution(50) cone.SetDirection(0, 0, -1) cone.SetHeight(3.0) cone.CappingOn() cone.Update() # Implicit function that will be used to slice the mesh implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance() implicitPolyDataDistance.SetInput(cone.GetOutput()) # create a grid dimension = 51 xCoords = vtk.vtkFloatArray() for x, i in enumerate(np.linspace(-1.0, 1.0, dimension)): xCoords.InsertNextValue(i) yCoords = vtk.vtkFloatArray() for y, i in enumerate(np.linspace(-1.0, 1.0, dimension)): yCoords.InsertNextValue(i) zCoords = vtk.vtkFloatArray() for z, i in enumerate(np.linspace(-1.0, 1.0, dimension)): zCoords.InsertNextValue(i) # # create a grid - if not using numpy # dimension = 51 # xCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # xCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # # yCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # yCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # # zCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # zCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(xCoords.GetNumberOfTuples(), yCoords.GetNumberOfTuples(), zCoords.GetNumberOfTuples()) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName('SignedDistances') # Evaluate the signed distance function at all of the grid points for pointId in range(0, rgrid.GetNumberOfPoints()): p = rgrid.GetPoint(pointId) signedDistance = implicitPolyDataDistance.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # Add the SignedDistances to the grid rgrid.GetPointData().SetScalars(signedDistances) # Use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipDataSet() clipper.SetInputData(rgrid) clipper.InsideOutOn() clipper.SetValue(0.0) clipper.GenerateClippedOutputOn() clipper.Update() # --- mappers, actors, render, etc. --- # mapper and actor to view the cone coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) # geometry filter to view the background grid geometryFilter = vtk.vtkRectilinearGridGeometryFilter() geometryFilter.SetInputData(rgrid) geometryFilter.SetExtent(0, dimension, 0, dimension, int(dimension / 2), int(dimension / 2)) geometryFilter.Update() rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(geometryFilter.GetOutputPort()) rgridMapper.SetScalarRange( rgrid.GetPointData().GetArray('SignedDistances').GetRange()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() # mapper and actor to view the clipped mesh clipperMapper = vtk.vtkDataSetMapper() clipperMapper.SetInputConnection(clipper.GetOutputPort()) clipperMapper.ScalarVisibilityOff() clipperOutsideMapper = vtk.vtkDataSetMapper() clipperOutsideMapper.SetInputConnection(clipper.GetOutputPort(1)) clipperOutsideMapper.ScalarVisibilityOff() clipperActor = vtk.vtkActor() clipperActor.SetMapper(clipperMapper) clipperActor.GetProperty().SetColor(colors.GetColor3d('Banana')) clipperOutsideActor = vtk.vtkActor() clipperOutsideActor.SetMapper(clipperOutsideMapper) clipperOutsideActor.GetProperty().SetColor( colors.GetColor3d('Banana')) # A renderer and render window # Create a renderer, render window, and interactor leftViewport = [0.0, 0.0, 0.5, 1.0] leftRenderer = vtk.vtkRenderer() leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(colors.GetColor3d('SteelBlue')) rightViewport = [0.5, 0.0, 1.0, 1.0] rightRenderer = vtk.vtkRenderer() rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(colors.GetColor3d('CadetBlue')) # add the actors leftRenderer.AddActor(wireActor) leftRenderer.AddActor(clipperActor) rightRenderer.AddActor(clipperOutsideActor) renwin = vtk.vtkRenderWindow() renwin.SetSize(640, 480) renwin.AddRenderer(leftRenderer) renwin.AddRenderer(rightRenderer) renwin.SetWindowName('ClipDataSetWithPolyData') # An interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) # Share the camera leftRenderer.GetActiveCamera().SetPosition(0, -1, 0) leftRenderer.GetActiveCamera().SetFocalPoint(0, 0, 0) leftRenderer.GetActiveCamera().SetViewUp(0, 0, 1) leftRenderer.GetActiveCamera().Azimuth(30) leftRenderer.GetActiveCamera().Elevation(30) leftRenderer.ResetCamera() rightRenderer.SetActiveCamera(leftRenderer.GetActiveCamera()) renwin.Render() interactor.Start() # Generate a report ct = vtk.vtkCellTypes() numberOfCells = clipper.GetOutput().GetNumberOfCells() print('------------------------') print('The clipped dataset(inside) contains a\n', clipper.GetOutput().GetClassName(), 'that has', numberOfCells, 'cells') cellMap = dict() for i in range(0, numberOfCells): cellMap[clipper.GetOutput().GetCellType(i)] = cellMap.get(clipper.GetOutput().GetCellType(i), 0) + 1 for k, v in cellMap.items(): print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.') numberOfCells = clipper.GetClippedOutput().GetNumberOfCells() print('------------------------') print('The clipped dataset(outside) contains a\n', clipper.GetClippedOutput().GetClassName(), 'that has', numberOfCells, 'cells') outsideCellMap = dict() for i in range(0, numberOfCells): outsideCellMap[clipper.GetClippedOutput().GetCellType(i)] = outsideCellMap.get( clipper.GetClippedOutput().GetCellType(i), 0) + 1 for k, v in outsideCellMap.items(): print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.')
def scan(wannabeacts): scannedacts = [] if not utils.isSequence(wannabeacts): wannabeacts = [wannabeacts] for a in wannabeacts: # scan content of list if isinstance(a, vtk.vtkActor): scannedacts.append(a) if hasattr(a, 'trail' ) and a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkAssembly): scannedacts.append(a) if a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkActor2D): if isinstance(a, vtk.vtkCornerAnnotation): for a2 in settings.collectable_actors: if isinstance(a2, vtk.vtkCornerAnnotation): if at in a2.renderedAt: # remove old message self.removeActor(a2) scannedacts.append(a) elif isinstance(a, vtk.vtkImageActor): scannedacts.append(a) elif isinstance(a, vtk.vtkVolume): scannedacts.append(a) elif isinstance(a, vtk.vtkImageData): scannedacts.append(Volume(a)) elif isinstance(a, vtk.vtkPolyData): scannedacts.append(Actor(a, c, alpha, wire, bc)) elif isinstance(a, str): # assume a filepath was given out = vtkio.load(a, c, alpha, wire, bc) if isinstance(out, str): colors.printc("~times File not found:", out, c=1) scannedacts.append(None) else: scannedacts.append(out) elif "dolfin" in str(type(a)): # assume a dolfin.Mesh object from vtkplotter.dolfin import MeshActor out = MeshActor(a, c=c, alpha=alpha, wire=True, bc=bc) scannedacts.append(out) elif a is None: pass elif isinstance(a, vtk.vtkUnstructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkStructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkRectilinearGrid): gf = vtk.vtkRectilinearGridGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkMultiBlockDataSet): for i in range(a.GetNumberOfBlocks()): b = a.GetBlock(i) if isinstance(b, vtk.vtkPolyData): scannedacts.append(Actor(b, c, alpha, wire, bc)) elif isinstance(b, vtk.vtkImageData): scannedacts.append(Volume(b)) else: colors.printc("~!? Cannot understand input in show():", type(a), c=1) scannedacts.append(None) return scannedacts
def testVTK(): print(vtk.VTK_VERSION, sys.version) line = vtk.vtkLineSource() line.SetPoint1(0, 0, 0) line.SetPoint2(5, 0, 0) # tubeFilter = vtk.vtkTubeFilter() # tubeFilter.SetInputConnection(line.GetOutputPort()) # tubeFilter.SetRadius(0.1) # tubeFilter.SetNumberOfSides(8) # tubeFilter.CappingOn() cone_a = vtk.vtkConeSource() cone_a.SetHeight(10) cone_a.SetRadius(5) cone_a.SetResolution(30) coneMapper1 = vtk.vtkPolyDataMapper() coneMapper1.SetInputConnection(cone_a.GetOutputPort()) coneMapper2 = vtk.vtkPolyDataMapper() # coneMapper2.SetInputConnection(tubeFilter.GetOutputPort()) coneMapper2.SetInputConnection(line.GetOutputPort()) coneActor1 = vtk.vtkActor() coneActor2 = vtk.vtkActor() coneActor2.SetPosition(0, 0, -2.5) # coneActor1.RotateY(90) # coneActor2.RotateY(45) # coneActor.RotateWXYZ(90, 0, 0, 1) # coneActor.SetScale(0.4) coneActor1.SetMapper(coneMapper1) coneActor2.SetMapper(coneMapper2) coneActor1.GetProperty().SetColor(1, 0, 0) coneActor1.GetProperty().SetOpacity(0.5) # coneActor2.GetProperty().SetOpacity(0.8) xc, yc, zc = 3, 6, 12 xCoords = vtk.vtkFloatArray() yCoords = vtk.vtkFloatArray() zCoords = vtk.vtkFloatArray() for i in range(xc): xCoords.InsertNextValue(i * i) for i in range(yc): yCoords.InsertNextValue(i * i) for i in range(zc): zCoords.InsertNextValue(i * i) rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(xc, yc, zc) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) plane.SetExtent(0, xc - 1, 0, yc - 1, 0, zc - 1) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(plane.GetOutputPort()) # mapper.SetInputData(rgrid) actor = vtk.vtkActor() actor.SetMapper(mapper) ren1 = vtk.vtkRenderer() ren1.AddActor(coneActor1) ren1.AddActor(coneActor2) # ren1.AddActor(actor) ren1.SetBackground(0, .4, .4) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(400, 400) renWin.Render() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() iren.Start()