Exemplo n.º 1
0
def getregionsrange(polydata):
    """Return range of connected regions."""
    # extract surface
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInput(polydata)
    surfer.Update()

    # clean before connectivity filter
    # to avoid artificial regionIds
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(surfer.GetOutput())
    cleaner.Update()

    # extract all connected regions
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(cleaner.GetOutput())
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()

    # extract surface
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInput(connect.GetOutput())
    surfer.Update()

    # get range
    regions = surfer.GetOutput().GetPointData().GetArray('RegionId')
    regionsrange = regions.GetRange()
    return regionsrange
Exemplo n.º 2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkDataSetSurfaceFilter(), 'Processing.',
         ('vtkDataSet',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 3
0
def separate_regions(dataset, regionIdArrayName='RegionId', regionIds=None):
    dataset_dsa = wdo(dataset)

    if regionIds is None:
        regionIds = np.unique(dataset_dsa.PointData[regionIdArrayName])

    regions = []

    for regionId in regionIds:
        threshold = vtk.vtkThreshold()
        threshold.SetInputData(dataset)
        threshold.ThresholdBetween(regionId, regionId)
        threshold.SetInputArrayToProcess(0, 0, 0, 0, regionIdArrayName)
        threshold.AllScalarsOff()
        threshold.Update()
        region = threshold.GetOutput()

        if isinstance(dataset, vtk.vtkPolyData):
            surfFilter = vtk.vtkDataSetSurfaceFilter()
            surfFilter.SetInputData(region)
            surfFilter.Update()
            region = surfFilter.GetOutput()

        regions.append(region)

    return regions
Exemplo n.º 4
0
    def __init__(self, vtk_filename=None, vtk_data=None):
        """
        Initiate Viwer

        Parameters
        ----------
        vtk_filename : str
            Input VTK filename
        """

        QDialog.__init__(self)
        self.initUI()

        ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(ren)
        iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        if vtk_filename is not None:
            # VTK file
            reader = vtk.vtkUnstructuredGridReader()
            reader.SetFileName(vtk_filename)
            reader.Update()
            vtkdata = reader.GetOutput()

        if vtk_data is not None:
            vtkdata = vtk_data

        # VTK surface
        surface = vtk.vtkDataSetSurfaceFilter()
        surface.SetInput(vtkdata)
        surface.Update()

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(surface.GetOutput())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOff()
        # actor.GetProperty().SetEdgeColor(1,1,1)
        # actor.GetProperty().SetLineWidth(0.1)
        ren.AddActor(actor)

        # annot. cube
        axesActor = vtk.vtkAnnotatedCubeActor()
        axesActor.SetXPlusFaceText('R')
        axesActor.SetXMinusFaceText('L')
        axesActor.SetYMinusFaceText('H')
        axesActor.SetYPlusFaceText('F')
        axesActor.SetZMinusFaceText('A')
        axesActor.SetZPlusFaceText('P')
        axesActor.GetTextEdgesProperty().SetColor(1, 1, 0)
        axesActor.GetCubeProperty().SetColor(0, 0, 1)
        self.axes = vtk.vtkOrientationMarkerWidget()
        self.axes.SetOrientationMarker(axesActor)
        self.axes.SetInteractor(iren)
        self.axes.EnabledOn()
        self.axes.InteractiveOn()

        ren.ResetCamera()
        iren.Initialize()
	def __init__(self,volume):
		self.volume=volume
		#Get the outer surface of the volume
		self.surface=vtk.vtkDataSetSurfaceFilter()
		self.surface.SetInputData(volume)
		self.surface.Update()
		self.volume=self.surface
Exemplo n.º 6
0
    def ExtractSurface(self, pass_pointid=True, pass_cellid=True):
        """
        Extract surface mesh of the grid

        Parameters
        ----------
        pass_pointid : bool, optional
            Adds a point scalar "vtkOriginalPointIds" that idenfities which
            original points these surface points correspond to

        pass_cellid : bool, optional
            Adds a cell scalar "vtkOriginalPointIds" that idenfities which
            original cells these surface cells correspond to

        Returns
        -------
        extsurf : vtki.PolyData
            Surface mesh of the grid
        """
        surf_filter = vtk.vtkDataSetSurfaceFilter()
        surf_filter.SetInputData(self)
        if pass_pointid:
            surf_filter.PassThroughCellIdsOn()
        if pass_cellid:
            surf_filter.PassThroughPointIdsOn()
        surf_filter.Update()
        return vtki.PolyData(surf_filter.GetOutput())
Exemplo n.º 7
0
    def vtkReadVTKfile(self, filename='not defined'):
        """ Lecture d'un fichier vtk"""
        # Read the source file.
        print "----------------------------------------------------"
        print "Read geometric surface"
        print "----------------------------------------------------"
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(os.path.join(self.read_path, filename))
        reader.Update()  # Needed because of GetScalarRange

        surface_filter = vtk.vtkDataSetSurfaceFilter()
        surface_filter.SetInputConnection(reader.GetOutputPort())

        self.meshNormals = vtk.vtkPolyDataNormals()
        self.meshNormals.SetInputConnection(surface_filter.GetOutputPort())
        self.meshNormals.Update()

        #~ self.normales = VN.vtk_to_numpy(self.meshNormals.GetOutput().GetPointData().GetNormals())
        self.meshNode = VN.vtk_to_numpy(
            surface_filter.GetOutput().GetPoints().GetData())
        self.meshTable = VN.vtk_to_numpy(
            surface_filter.GetOutput().GetPolys().GetData())
        self.meshTable = self.meshTable.reshape(self.meshTable.shape[0] / 4,
                                                4)[:, 1:]

        self.nbDof = self.meshNode.shape[0]
        self.nbElem = self.meshTable.shape[0]
Exemplo n.º 8
0
def extractconnectedregion(polydata, regionid):
    """Run connectivity filter to assign regionsids and return region with
    given regionid."""
    # extract surface
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInput(polydata)
    surfer.Update()

    # clean before connectivity filter
    # to avoid artificial regionIds
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(surfer.GetOutput())
    cleaner.Update()

    # extract all regions
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(cleaner.GetOutput())
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()

    # threshold especified region
    surface = pointthreshold(connect.GetOutput(), 'RegionId', float(regionid),
                             float(regionid))
    return surface
Exemplo n.º 9
0
 def get_boundaries(self):
     '''
     Extracts the boundaries of the model to a polydata object, if export_STL is selected then ask for where to save it.
     '''
     #can't be activated unless load_model has run
     extract_surface = vtk.vtkDataSetSurfaceFilter()
     extract_surface.SetInputDataObject(self.vtu_output)
     extract_surface.Update()
     self.model_boundary = vtk.vtkPolyData()
     self.model_boundary = extract_surface.GetOutput()
     msg = 'Extracted boundaries.'
     
     if self.ui.export_STL_button.isChecked():
         #get file name
         fileo, _ = get_save_file('*.stl')
         if fileo is None:
             return
         writer = vtk.vtkSTLWriter()
         writer.SetFileName(fileo)
         writer.SetInputData(self.model_boundary)
         msg = 'Extracted boundaries and wrote STL file.' #overwrite msg if stl was written
         writer.Write()
     
     self.display_info(msg)
     self.ui.vtkWidget.update()
def get_number_of_points_and_boundary_faces(pod_mode_dir,calibrate_coefficients):
	filename = pod_mode_dir+"/spatial_meanfield.vtk"
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.ReadAllTensorsOn()
	reader.SetFileName(filename)
	reader.Update()
	num_points = reader.GetOutput().GetNumberOfPoints()

	if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ):
		geom_filter = vtk.vtkDataSetSurfaceFilter()
		geom_filter.SetInput(reader.GetOutput())
		geom_filter.Update()
		boundary_faces = vtk.vtkPolyData()
		boundary_faces = geom_filter.GetOutput()

		point_to_cell_data = vtk.vtkPointDataToCellData()
		point_to_cell_data.SetInput(geom_filter.GetOutput())
		point_to_cell_data.Update()
		num_boundary_faces = point_to_cell_data.GetOutput().GetNumberOfCells()
	else:
		num_boundary_faces = 1

	return num_points, num_boundary_faces
def isolateCap(model, cap, caps_location):
    cap_vtp = intializeVTP(caps_location + '/' + cap + '.vtp')
    cellIds = vtk.vtkIdTypeArray()
    cap_cell_set = set()
    for i_cell in range(0, cap_vtp.GetNumberOfCells()):
        cap_cell_set.add(
            cap_vtp.GetCellData().GetArray('GlobalElementID').GetValue(i_cell))
    for i_cell in range(0, model.GetNumberOfCells()):
        if (model.GetCellData().GetArray('GlobalElementID').GetValue(i_cell)
                in cap_cell_set):
            cellIds.InsertNextValue(i_cell)
    #print(cellIds.GetNumberOfValues())
    #Creates the selection object to extract the subset of cells from the mesh
    region = vtk.vtkExtractSelection()
    region.SetInputData(0, model)
    tempCells = vtk.vtkSelectionNode()
    tempCells.SetFieldType(vtk.vtkSelectionNode.CELL)
    tempCells.SetContentType(vtk.vtkSelectionNode.INDICES)
    tempCells.SetSelectionList(cellIds)
    tempSelection = vtk.vtkSelection()
    tempSelection.AddNode(tempCells)
    region.SetInputData(1, tempSelection)
    region.Update()

    #Outputs the mesh as an polyData object
    dssf = vtk.vtkDataSetSurfaceFilter()
    dssf.SetInputConnection(region.GetOutputPort())
    dssf.Update()
    return dssf.GetOutput(), cellIds
Exemplo n.º 12
0
 def extract_surface(self):
     print('extracting surface')
     # Get surface of the mesh
     surface_filter = vtk.vtkDataSetSurfaceFilter()
     surface_filter.SetInputData(self.mesh.GetOutput())
     surface_filter.Update()
     self.mesh = surface_filter
Exemplo n.º 13
0
def putMaskOnVTKGrid(data,grid,actorColor=None,deep=True):
  #Ok now looking 
  msk = data.mask
  imsk =  VN.numpy_to_vtk(msk.astype(numpy.int).flat,deep=deep)
  mapper = None
  if msk is not numpy.ma.nomask:
      msk =  VN.numpy_to_vtk(numpy.logical_not(msk).astype(numpy.uint8).flat,deep=deep)
      if actorColor is not None:
          grid2 = vtk.vtkStructuredGrid()
          grid2.CopyStructure(grid)
          geoFilter = vtk.vtkDataSetSurfaceFilter()
          if grid.IsA("vtkStructuredGrid"):
              grid2.GetPointData().SetScalars(imsk)
              #grid2.SetCellVisibilityArray(imsk)
              p2c = vtk.vtkPointDataToCellData()
              p2c.SetInputData(grid2)
              geoFilter.SetInputConnection(p2c.GetOutputPort())
          else:
              grid2.GetCellData().SetScalars(imsk)
              geoFilter.SetInputData(grid)
          geoFilter.Update()
          mapper = vtk.vtkPolyDataMapper()
          mapper.SetInputData(geoFilter.GetOutput())
          lut = vtk.vtkLookupTable()
          lut.SetNumberOfTableValues(1)
          r,g,b = actorColor
          lut.SetNumberOfTableValues(2)
          lut.SetTableValue(0,r/100.,g/100.,b/100.)
          lut.SetTableValue(1,r/100.,g/100.,b/100.)
          mapper.SetLookupTable(lut)
          mapper.SetScalarRange(1,1)
      if grid.IsA("vtkStructuredGrid"):
          grid.SetPointVisibilityArray(msk)
          #grid.SetCellVisibilityArray(msk)
  return mapper
    def ReadOBJFile(self, filename):
        '''
        @param filename: str 
        @rtype: None
        '''
        reader = vtk.vtkOBJReader()
        reader.SetFileName(filename)
        
        try:
            reader.Update()
            cleanFilter = vtk.vtkCleanPolyData()
            cleanFilter.SetInput(reader.GetOutput())
            cleanFilter.ConvertLinesToPointsOn()
            cleanFilter.ConvertPolysToLinesOn()
            cleanFilter.ConvertStripsToPolysOn()
            cleanFilter.PointMergingOn()
            cleanFilter.Update()
            surfaceFilter = vtk.vtkDataSetSurfaceFilter()
            surfaceFilter.SetInput(cleanFilter.GetOutput())
            surfaceFilter.Update()
            self.setDataSet(surfaceFilter.GetOutput())
            del cleanFilter
            del surfaceFilter
        except Exception, e:
#            del reader
            print e
            raise IOError, "Could not read the OBJ file! "
Exemplo n.º 15
0
def get_surface_faces(surface):
    '''Get the faces from the surface mesh using the ModelFaceID data array.
    '''
    face_ids = surface.GetCellData().GetArray('ModelFaceID')
    face_ids_range = 2 * [0]
    face_ids.GetRange(face_ids_range, 0)
    min_id = int(face_ids_range[0])
    max_id = int(face_ids_range[1])

    ## Extract face geometry.
    #
    faces = []
    for i in range(min_id, max_id + 1):
        threshold = vtk.vtkThreshold()
        threshold.SetInputData(surface)
        threshold.SetInputArrayToProcess(0, 0, 0, 1, 'ModelFaceID')
        threshold.ThresholdBetween(i, i)
        threshold.Update()

        surfacer = vtk.vtkDataSetSurfaceFilter()
        surfacer.SetInputData(threshold.GetOutput())
        surfacer.Update()
        faces.append(surfacer.GetOutput())

    return faces
    def doNonLinear(self, ghosts, ncells):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(10)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))
        pts.InsertPoint(4, (0.5, 0, 0))
        pts.InsertPoint(5, (1.25, 0.5, 0))
        pts.InsertPoint(6, (0.25, 0.5, 0))
        pts.InsertPoint(7, (0.25, 0.25, 0.5))
        pts.InsertPoint(8, (0.75, 0.25, 0.5))
        pts.InsertPoint(9, (0.5, 0.75, 0.5))

        te = vtk.vtkQuadraticTetra()
        ptIds = te.GetPointIds()
        for i in range(10):
            ptIds.SetId(i, i)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        ugg = vtk.vtkUnstructuredGridGeometryFilter()
        ugg.SetInputData(grid)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetNonlinearSubdivisionLevel(2)
        dss.SetInputConnection(ugg.GetOutputPort())
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), ncells)
Exemplo n.º 17
0
def extract_fiber(bundle, ids):
    print "ids selected: ", ids.GetNumberOfTuples()
    sys.stdout.flush()
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection = vtk.vtkSelection()
    extractSelection = vtk.vtkExtractSelection()
    vtu2vtkFilter = vtk.vtkDataSetSurfaceFilter()

    selectionNode.SetSelectionList(ids)
    selection.AddNode(selectionNode)
    if vtk.VTK_MAJOR_VERSION > 5:
        extractSelection.SetInputData(0, bundle)
        del bundle
        extractSelection.SetInputData(1, selection)
        del selection
        extractSelection.Update()
        vtu2vtkFilter.SetInputData(extractSelection.GetOutput())
        del extractSelection
    else:
        extractSelection.SetInput(0, bundle)
        del bundle
        extractSelection.SetInput(1, selection)
        del selection
        extractSelection.Update()
        vtu2vtkFilter.SetInput(extractSelection.GetOutput())
        del extractSelection
    vtu2vtkFilter.Update()
    extract = vtk.vtkPolyData()
    extract = vtu2vtkFilter.GetOutput()
    del vtu2vtkFilter
    del selectionNode
    return extract
Exemplo n.º 18
0
    def doNonLinear(self, ghosts, ncells):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(10)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))
        pts.InsertPoint(4, (0.5, 0, 0))
        pts.InsertPoint(5, (0.25, 0.5, 0))
        pts.InsertPoint(6, (0.75, 0.5, 0))
        pts.InsertPoint(7, (0.25, 0.25, 0.5))
        pts.InsertPoint(8, (0.75, 0.25, 0.5))
        pts.InsertPoint(9, (0.5, 0.75, 0.5))

        te = vtk.vtkQuadraticTetra()
        ptIds = te.GetPointIds()
        for i in range(10):
            ptIds.SetId(i, i)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        ugg = vtk.vtkUnstructuredGridGeometryFilter()
        ugg.SetInputData(grid)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetNonlinearSubdivisionLevel(2)
        dss.SetInputConnection(ugg.GetOutputPort())
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), ncells)
def save_lesion(output_file, input_file, field, limits):
    reader = v.vtkXMLUnstructuredGridReader()
    reader.SetFileName(input_file)
    reader.Update()

    threshold = v.vtkThreshold()
    threshold.SetInput(reader.GetOutput())

    if limits[0] is None:
        threshold.ThresholdByLower(limits[1])
    elif limits[1] is None:
        threshold.ThresholdByUpper(limits[0])
    else:
        threshold.ThresholdBetween(*limits)

    threshold.SetInputArrayToProcess(0, 0, 0, v.vtkDataObject.FIELD_ASSOCIATION_CELLS, field)
    threshold.Update()

    extract_surface = v.vtkDataSetSurfaceFilter()
    extract_surface.SetInput(threshold.GetOutput())
    extract_surface.Update()

    writer = v.vtkXMLPolyDataWriter()
    writer.SetFileName(output_file)
    writer.SetInput(extract_surface.GetOutput())
    writer.Write()
Exemplo n.º 20
0
	def ConvertDataSetToSurface(algorithmOutputPort):
		dataSetSurfaceFilter = vtk.vtkDataSetSurfaceFilter()
		dataSetSurfaceFilter.SetInputConnection(algorithmOutputPort)
		dataSetSurfaceFilter.Update()
		polyData = vtk.vtkPolyData()
		polyData.ShallowCopy(dataSetSurfaceFilter.GetOutput())
		return polyData
Exemplo n.º 21
0
def Test3(datadir):
    reader = vtk.vtkDataSetReader()
    reader.SetFileName(datadir + "/Data/blow.vtk")
    reader.UpdateInformation();
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()

    dssf = vtk.vtkDataSetSurfaceFilter()
    dssf.SetInputConnection(reader.GetOutputPort())

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(dssf.GetOutputPort())

    f = vtk.vtkIntegrateAttributes()
    f.SetInputConnection(stripper.GetOutputPort())
    f.Update()

    result = f.GetOutputDataObject(0)
    val = result.GetPointData().GetArray("displacement1").GetValue(0)
    assert (val > 463.64 and val < 463.642)

    val = result.GetPointData().GetArray("thickness3").GetValue(0)
    assert (val > 874.61 and val < 874.618)

    val = result.GetCellData().GetArray("Area").GetValue(0)
    assert (val > 1145.405 and val < 1145.415)
Exemplo n.º 22
0
def threshold(polydata,
              arrayname,
              valuerange=[0, 1],
              iscelldata=True,
              allscalars=True):
    """Extract those cells from polydata whose pointdata/celldata values are
    within a specified range.

    For pointdata, cells are included if scalar values of all cell points are
    within the range (allscalars=True) or if the scalar value of at least one of
    the cell points is within the range (allscalar=False).

    """
    thresholdfilter = vtk.vtkThreshold()
    thresholdfilter.SetInput(polydata)
    thresholdfilter.ThresholdBetween(valuerange[0], valuerange[1])
    if iscelldata:
        thresholdfilter.SetInputArrayToProcess(
            0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, arrayname)
    else:
        thresholdfilter.SetInputArrayToProcess(
            0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, arrayname)
    if allscalars:
        thresholdfilter.AllScalarsOn()
    else:
        thresholdfilter.AllScalarsOff()
    thresholdfilter.Update()
    surfacefilter = vtk.vtkDataSetSurfaceFilter()
    surfacefilter.SetInput(thresholdfilter.GetOutput())
    surfacefilter.Update()
    return surfacefilter.GetOutput()
Exemplo n.º 23
0
    def __init__(self, renderer, data, type, index):
        PeacockActor.__init__(self, renderer)
        self.data = data
        self.type = type
        self.index = index

        self.solid_visible = False
        self.edges_visible = False

        self.mesh = data.GetBlock(type).GetBlock(index)

        self.geom = vtk.vtkDataSetSurfaceFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.geom.SetInput(self.mesh)
        else:
            self.geom.SetInputData(self.mesh)
        self.geom.Update()

        self.mapper = vtk.vtkDataSetMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.mesh)
        else:
            self.mapper.SetInputData(self.mesh)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetPointSize(5)
        self.actor.GetProperty().SetEdgeColor(0, 0, 0)
        self.actor.GetProperty().SetAmbient(0.3)
Exemplo n.º 24
0
 def ConvertDataSetToSurface(algorithmOutputPort):
     dataSetSurfaceFilter = vtk.vtkDataSetSurfaceFilter()
     dataSetSurfaceFilter.SetInputConnection(algorithmOutputPort)
     dataSetSurfaceFilter.Update()
     polyData = vtk.vtkPolyData()
     polyData.ShallowCopy(dataSetSurfaceFilter.GetOutput())
     return polyData
Exemplo n.º 25
0
   def vtkReadVTKfile(self, filename):
      """ Lecture d'un fichier vtk"""
      # Read the source file.
      reader = vtk.vtkUnstructuredGridReader()
      reader.SetFileName(filename)
      reader.Update() # Needed because of GetScalarRange
      
      surface_filter = vtk.vtkDataSetSurfaceFilter()
      surface_filter.SetInputConnection(reader.GetOutputPort()) 
      
      self.meshNormals = vtk.vtkPolyDataNormals()
      self.meshNormals.SetInputConnection(surface_filter.GetOutputPort())
      self.meshNormals.SetFeatureAngle(60.0)
      self.meshNormals.ComputeCellNormalsOn()
      self.meshNormals.ComputePointNormalsOn()
      self.meshNormals.ConsistencyOn()
      self.meshNormals.AutoOrientNormalsOn()
      self.meshNormals.Update()
      
      # Sauvegarde des proprietes maillage GMSH pour calcul centerline
      self.gmeshNode  = vtk_to_np(surface_filter.GetOutput().GetPoints().GetData())
      self.gmeshTable = vtk_to_np(surface_filter.GetOutput().GetPolys().GetData())
      
      # The quadric has nasty discontinuities from the way the edges are generated
      # so let's pass it though a CleanPolyDataFilter and merge any points which
      # are coincident, or very close
 
      self.outputMesh = vtk.vtkCleanPolyData()
      self.outputMesh.SetInputConnection(surface_filter.GetOutputPort())
      self.outputMesh.SetTolerance(0.001)
Exemplo n.º 26
0
def get_number_of_points_and_boundary_faces(pod_mode_dir,
                                            calibrate_coefficients):
    filename = pod_mode_dir + "/spatial_meanfield.vtk"
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.ReadAllTensorsOn()
    reader.SetFileName(filename)
    reader.Update()
    num_points = reader.GetOutput().GetNumberOfPoints()

    if ((calibrate_coefficients == "none")
            or (calibrate_coefficients == "constant")):
        geom_filter = vtk.vtkDataSetSurfaceFilter()
        geom_filter.SetInput(reader.GetOutput())
        geom_filter.Update()
        boundary_faces = vtk.vtkPolyData()
        boundary_faces = geom_filter.GetOutput()

        point_to_cell_data = vtk.vtkPointDataToCellData()
        point_to_cell_data.SetInput(geom_filter.GetOutput())
        point_to_cell_data.Update()
        num_boundary_faces = point_to_cell_data.GetOutput().GetNumberOfCells()
    else:
        num_boundary_faces = 1

    return num_points, num_boundary_faces
Exemplo n.º 27
0
    def __init__(self, renderer, data, type, index):
        PeacockActor.__init__(self, renderer)
        self.data = data
        self.type = type
        self.index = index

        self.solid_visible = False
        self.edges_visible = False

        self.mesh = data.GetBlock(type).GetBlock(index)

        self.geom = vtk.vtkDataSetSurfaceFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.geom.SetInput(self.mesh)
        else:
            self.geom.SetInputData(self.mesh)
        self.geom.Update()

        self.mapper = vtk.vtkDataSetMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.mesh)
        else:
            self.mapper.SetInputData(self.mesh)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetPointSize(5)
        self.actor.GetProperty().SetEdgeColor(0,0,0)
        self.actor.GetProperty().SetAmbient(0.3);
def get_surface_faces(surface_mesh, bc_faces):
    '''Get the faces from the surface mesh.
 
       The faces are vtkPolyData objects with cell data arrays.
    '''
    print("\n========== get_surface_faces ==========")
    face_ids = surface_mesh.GetCellData().GetArray(VtkDataNames.ModelFaceID)
    face_ids_range = 2 * [0]
    face_ids.GetRange(face_ids_range, 0)
    min_id = int(face_ids_range[0])
    max_id = int(face_ids_range[1])
    print("[get_surface_faces] Face IDs range: {0:d} {1:d}".format(
        min_id, max_id))

    ## Extract face geometry.
    #
    for i in range(min_id, max_id + 1):
        if i not in bc_faces:
            continue
        print("[get_surface_faces] ----- Face ID {0:d} ----".format(i))
        print("[get_surface_faces] Face name: {0:s} ".format(bc_faces[i].name))
        threshold = vtk.vtkThreshold()
        threshold.SetInputData(surface_mesh)
        threshold.SetInputArrayToProcess(0, 0, 0, 1, VtkDataNames.ModelFaceID)
        threshold.ThresholdBetween(i, i)
        threshold.Update()

        surfacer = vtk.vtkDataSetSurfaceFilter()
        surfacer.SetInputData(threshold.GetOutput())
        surfacer.Update()
        bc_faces[i].set_mesh(surfacer.GetOutput())
        print("[get_surface_faces] Face number of points: %d" %
              bc_faces[i].mesh.GetNumberOfPoints())
        print("[get_surface_faces] Face number of cells: %d" %
              bc_faces[i].mesh.GetNumberOfCells())
Exemplo n.º 29
0
    def testLinear(self):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        ghosts = vtk.vtkUnsignedCharArray()
        ghosts.SetName("vtkGhostLevels")
        ghosts.SetNumberOfTuples(4)
        ghosts.SetValue(0, 1)
        ghosts.SetValue(1, 1)
        ghosts.SetValue(2, 1)
        ghosts.SetValue(3, 0)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
Exemplo n.º 30
0
def threshold(polydata, arrayname, valuerange=[0, 1], iscelldata=True,
              allscalars=True):
    """Extract those cells from polydata whose pointdata/celldata values are
    within a specified range.

    For pointdata, cells are included if scalar values of all cell points are
    within the range (allscalars=True) or if the scalar value of at least one of
    the cell points is within the range (allscalar=False).

    """
    thresholdfilter = vtk.vtkThreshold()
    thresholdfilter.SetInput(polydata)
    thresholdfilter.ThresholdBetween(valuerange[0], valuerange[1])
    if iscelldata:
        thresholdfilter.SetInputArrayToProcess(0, 0, 0,
                                           vtk.vtkDataObject.
                                           FIELD_ASSOCIATION_CELLS, arrayname)
    else:
        thresholdfilter.SetInputArrayToProcess(0, 0, 0,
                                           vtk.vtkDataObject.
                                           FIELD_ASSOCIATION_POINTS, arrayname)
    if allscalars:
        thresholdfilter.AllScalarsOn()
    else:
        thresholdfilter.AllScalarsOff()
    thresholdfilter.Update()
    surfacefilter = vtk.vtkDataSetSurfaceFilter()
    surfacefilter.SetInput(thresholdfilter.GetOutput())
    surfacefilter.Update()
    return surfacefilter.GetOutput()
Exemplo n.º 31
0
    def write_boundary_edge_cells(self, edge_cell_ids):
        '''Write a PolyData surface containing the cells incident to boundary edges.

           This is for debugging.
        '''
        cell_mask = vtk.vtkIntArray()
        cell_mask.SetNumberOfValues(num_cells)
        cell_mask.SetName("CellMask")
        for i in range(num_cells):
            cell_mask.SetValue(i, 0)
        surface.GetCellData().AddArray(cell_mask)

        for cell_id in edge_cell_ids:
            cell_mask.SetValue(cell_id, 1)

        thresh = vtk.vtkThreshold()
        thresh.SetInputData(surface)
        thresh.ThresholdBetween(1, 1)
        thresh.SetInputArrayToProcess(
            0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_CELLS", "CellMask")
        thresh.Update()

        surfacefilter = vtk.vtkDataSetSurfaceFilter()
        surfacefilter.SetInputData(thresh.GetOutput())
        surfacefilter.Update()
        edge_cells = surfacefilter.GetOutput()

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName("boundary_edge_cells.vtp")
        writer.SetInputData(edge_cells)
        writer.Write()
Exemplo n.º 32
0
    def testLinear(self):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        ghosts = vtk.vtkUnsignedCharArray()
        ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName())
        ghosts.SetNumberOfTuples(4)
        ghosts.SetValue(0, 1)
        ghosts.SetValue(1, 1)
        ghosts.SetValue(2, 1)
        ghosts.SetValue(3, 0)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
Exemplo n.º 33
0
def extractSurface(inputMesh):
    """ Extract surface of a mesh. """
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputData(inputMesh)
    surfaceFilter.Update()
    surface = surfaceFilter.GetOutput()

    return surface
Exemplo n.º 34
0
    def _plotInternalCustomBoxfill(self):
        """Implements the logic to render a custom boxfill."""
        self._mappers = []

        self._customBoxfillArgs = self._prepContours()
        tmpLevels = self._customBoxfillArgs["tmpLevels"]
        tmpColors = self._customBoxfillArgs["tmpColors"]
        tmpOpacities = self._customBoxfillArgs["tmpOpacities"]

        style = self._gm.fillareastyle

        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        _colorMap = self.getColorMap()
        for i, l in enumerate(tmpLevels):
            # Ok here we are trying to group together levels can be, a join
            # will happen if: next set of levels continues where one left off
            # AND pattern is identical

            # TODO this should really just be a single polydata/mapper/actor:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                # th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                th.SetInputData(self._vtkDataSetFittedToViewport)
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100.,
                                      tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], False]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    self._mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos
Exemplo n.º 35
0
def putMaskOnVTKGrid(data,grid,actorColor=None,cellData=True,deep=True):
  #Ok now looking
  msk = data.mask
  imsk =  numpy_to_vtk_wrapper(msk.astype(numpy.int).flat,deep=deep)
  mapper = None
  if msk is not numpy.ma.nomask and not numpy.allclose(msk,False):
      if actorColor is not None:
          if grid.IsA("vtkStructuredGrid"):
            grid2 = vtk.vtkStructuredGrid()
          else:
            grid2 = vtk.vtkUnstructuredGrid()
          grid2.CopyStructure(grid)
          geoFilter = vtk.vtkDataSetSurfaceFilter()
          lut = vtk.vtkLookupTable()
          r,g,b = actorColor
          lut.SetNumberOfTableValues(2)
          if not cellData:
              grid2.GetPointData().RemoveArray(
                    vtk.vtkDataSetAttributes.GhostArrayName())
              grid2.GetPointData().SetScalars(imsk)
              #grid2.SetCellVisibilityArray(imsk)
              #p2c = vtk.vtkPointDataToCellData()
              #p2c.SetInputData(grid2)
              #geoFilter.SetInputConnection(p2c.GetOutputPort())
              geoFilter.SetInputData(grid2)
              lut.SetTableValue(0,r/100.,g/100.,b/100.,1.)
              lut.SetTableValue(1,r/100.,g/100.,b/100.,1.)
          else:
              grid2.GetCellData().RemoveArray(
                    vtk.vtkDataSetAttributes.GhostArrayName())
              grid2.GetCellData().SetScalars(imsk)
              geoFilter.SetInputData(grid2)
              lut.SetTableValue(0,r/100.,g/100.,b/100.,0.)
              lut.SetTableValue(1,r/100.,g/100.,b/100.,1.)
          geoFilter.Update()
          mapper = vtk.vtkPolyDataMapper()
          mapper.SetInputData(geoFilter.GetOutput())
          mapper.SetLookupTable(lut)
          mapper.SetScalarRange(0,1)

      # The ghost array now stores information about hidden (blanked)
      # points/cells. Setting an array entry to the bitwise value
      # `vtkDataSetAttributes.HIDDEN(CELL|POINT)` will blank the cell/point.
      flatMask = msk.flat
      ghost = numpy.zeros(len(flatMask), dtype=numpy.uint8)
      invalidMaskValue = vtk.vtkDataSetAttributes.HIDDENCELL if cellData else \
                         vtk.vtkDataSetAttributes.HIDDENPOINT
      for i, isInvalid in enumerate(flatMask):
          if isInvalid:
              ghost[i] = invalidMaskValue

      ghost = numpy_to_vtk_wrapper(ghost, deep=deep)
      ghost.SetName(vtk.vtkDataSetAttributes.GhostArrayName())
      if cellData:
          grid.GetCellData().AddArray(ghost)
      else:
          grid.GetPointData().AddArray(ghost)
  return mapper
Exemplo n.º 36
0
 def _createPolyDataFilter(self):
     """Overrides baseclass implementation."""
     self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter()
     if self._useCellScalars:
         p2c = vtk.vtkPointDataToCellData()
         p2c.SetInputData(self._vtkDataSet)
         self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort())
     else:
         self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
Exemplo n.º 37
0
    def get_surface_faces(self):
        '''Get the faces from the surface mesh using the ModelFaceID data array.
     
           The faces are vtkPolyData objects with cell data arrays.
        '''
        self.logger.info("========== get_surface_faces ==========")
        face_ids = self.surface.GetCellData().GetArray(
            VtkDataNames.ModelFaceID)
        if face_ids == None:
            self.logger.error("No ModelFaceID data.")
            return
        face_ids_range = 2 * [0]
        face_ids.GetRange(face_ids_range, 0)
        min_id = int(face_ids_range[0])
        max_id = int(face_ids_range[1])
        self.logger.info("Face IDs range: {0:d} {1:d}".format(min_id, max_id))

        ## Extract face geometry.
        #
        mesh_faces = {}

        for i in range(min_id, max_id + 1):
            #print("[Mesh.get_surface_faces] ---------- ID {0:d} ---------".format(i))
            threshold = vtk.vtkThreshold()
            threshold.SetInputData(self.surface)
            threshold.SetInputArrayToProcess(0, 0, 0, 1,
                                             VtkDataNames.ModelFaceID)
            threshold.ThresholdBetween(i, i)
            threshold.Update()

            surfacer = vtk.vtkDataSetSurfaceFilter()
            surfacer.SetInputData(threshold.GetOutput())
            surfacer.Update()
            mesh_faces[i] = Face(i, surfacer.GetOutput())
            #print("Mesh.[get_surface_faces] Face number of points: %d" % mesh_faces[i].GetNumberOfPoints())
            #print("Mesh.[get_surface_faces] Face number of cells: %d" % mesh_faces[i].GetNumberOfCells())
            #write_surface_mesh("surface", mesh_faces[i], str(i))
        #_for i in range(min_id, max_id+1)

        self.boundary_faces = mesh_faces
        center = [0.0, 0.0, 0.0]
        total_num_pts = 0
        for fid, face in self.boundary_faces.items():
            npts = face.surface.GetNumberOfPoints()
            ncells = face.surface.GetNumberOfCells()
            self.logger.info("  id:{0:d} num cells: {1:d}".format(
                face.model_face_id, ncells))
            for i in range(0, npts):
                point = face.surface.GetPoint(i)
                center[0] += point[0]
                center[1] += point[1]
                center[2] += point[2]
            total_num_pts += npts
        center[0] /= total_num_pts
        center[1] /= total_num_pts
        center[2] /= total_num_pts
        self.center = center
Exemplo n.º 38
0
def delaunay3d(points):
    """Construct a 3D Delaunay triangulation from a set of points."""
    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInput(points)
    delaunay.Update()
    surface = vtk.vtkDataSetSurfaceFilter()
    surface.SetInput(delaunay.GetOutput())
    surface.Update()
    return surface.GetOutput()
Exemplo n.º 39
0
    def setUp(self):
        # corner-points (9)
        c0=[[0,0,0],[1,0,0],[2,0,0]]
        c1=[[0,1,0],[1,1,0],[2,1,0]]
        c2=[[0,2,0],[1,2,0],[2,2,0]]
        # mid nodes on horizontal edges (6)
        mx0=[[.5,0,0],[1.5,0,0]]
        mx1=[[.5,1,0],[1.5,1,0]]
        mx2=[[.5,2,0],[1.5,2,0]]
        # mid nodes on vertical edges (6)
        my0=[[0,.5,0],[1,.5,0],[2,.5,0]]
        my1=[[0,1.5,0],[1,1.5,0],[2,1.5,0]]
        #
        # create points and point data
        pts=vtk.vtkPoints()
        pts.Allocate(21)
        self.point_ids=vtk.vtkIdTypeArray()
        self.point_ids.SetName('point-ids')
        self.point_values=vtk.vtkFloatArray()
        self.point_values.SetName('point-values')
        i=1
        for coords in (c0,c1,c2,mx0,mx1,mx2,my0,my1):
            for xyz in coords:
                pts.InsertNextPoint(xyz[0],xyz[1],xyz[2])
                self.point_ids.InsertNextValue(i+100)
                i+=1
                self.point_values.InsertNextValue( float(i) / 10 )
        #
        # create cells and cell data
        corners=[(0,1,4,3),
                 (1,2,5,4),
                 (3,4,7,6),
                 (4,5,8,7)]
        midnodes=[(9+0,15+1,9+2,15+0),
                  (9+1,15+2,9+3,15+1),
                  (9+2,15+4,9+4,15+3),
                  (9+3,15+5,9+5,15+4)]
        self.ug=vtk.vtkUnstructuredGrid()
        self.ug.SetPoints(pts)
        self.ug.Allocate(4)
        self.cell_ids=vtk.vtkIdTypeArray()
        self.cell_ids.SetName('cell-ids')
        i=1
        for (c,m) in zip(corners,midnodes):
            self.ug.InsertNextCell(vtk.VTK_QUADRATIC_QUAD,8,(c+m))
            self.cell_ids.InsertNextValue(i+1000)
            i+=1
        self.ug.GetPointData().AddArray(self.point_ids)
        self.ug.GetPointData().AddArray(self.point_values)
        self.ug.GetCellData().AddArray(self.cell_ids)
        #
        # create the surface-filter
        surface=vtk.vtkDataSetSurfaceFilter()
        surface.SetInputData(self.ug)
        surface.Update()

        self.output=surface.GetOutput()
Exemplo n.º 40
0
def delaunay3d(points):
    """Construct a 3D Delaunay triangulation from a set of points."""
    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInput(points)
    delaunay.Update()
    surface = vtk.vtkDataSetSurfaceFilter()
    surface.SetInput(delaunay.GetOutput())
    surface.Update()
    return surface.GetOutput()
Exemplo n.º 41
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkDataSetSurfaceFilter(),
                                       'Processing.', ('vtkDataSet', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 42
0
    def _plotInternalCustomBoxfill(self):
        """Implements the logic to render a custom boxfill."""
        self._mappers = []

        self._customBoxfillArgs = self._prepContours()
        tmpLevels = self._customBoxfillArgs["tmpLevels"]
        tmpColors = self._customBoxfillArgs["tmpColors"]
        tmpOpacities = self._customBoxfillArgs["tmpOpacities"]

        style = self._gm.fillareastyle

        luts = []
        geos = []
        wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1)
        _colorMap = self.getColorMap()
        assert(style != 'solid' or len(tmpLevels) == 1)
        for i, l in enumerate(tmpLevels):
            # Ok here we are trying to group together levels can be, a join
            # will happen if: next set of levels continues where one left off
            # AND pattern is identical

            # TODO this should really just be a single polydata/mapper/actor:
            for j, color in enumerate(tmpColors[i]):
                mapper = vtk.vtkPolyDataMapper()
                lut = vtk.vtkLookupTable()
                th = vtk.vtkThreshold()
                th.ThresholdBetween(l[j], l[j + 1])
                th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
                geoFilter2 = vtk.vtkDataSetSurfaceFilter()
                geoFilter2.SetInputConnection(th.GetOutputPort())
                # Make the polydata output available here for patterning later
                geoFilter2.Update()
                geos.append(geoFilter2)
                mapper.SetInputConnection(geoFilter2.GetOutputPort())
                lut.SetNumberOfTableValues(1)
                r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color)
                if style == 'solid':
                    tmpOpacity = tmpOpacities[j]
                    if tmpOpacity is None:
                        tmpOpacity = a / 100.
                    else:
                        tmpOpacity = tmpOpacities[j] / 100.
                    lut.SetTableValue(0, r / 100., g / 100., b / 100., tmpOpacity)
                else:
                    lut.SetTableValue(0, 1., 1., 1., 0.)
                mapper.SetLookupTable(lut)
                mapper.SetScalarRange(l[j], l[j + 1])
                luts.append([lut, [l[j], l[j + 1], False]])
                # Store the mapper only if it's worth it?
                # Need to do it with the whole slab min/max for animation
                # purposes
                if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax):
                    self._mappers.append(mapper)

        self._resultDict["vtk_backend_luts"] = luts
        if len(geos) > 0:
            self._resultDict["vtk_backend_geofilters"] = geos
Exemplo n.º 43
0
 def _createPolyDataFilter(self):
     """Overrides baseclass implementation."""
     self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter()
     if self._useCellScalars:
         p2c = vtk.vtkPointDataToCellData()
         p2c.SetInputData(self._vtkDataSet)
         self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort())
     else:
         self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
Exemplo n.º 44
0
def __surface_filter__(Obj):
    print "[surface_filter] <-\'%s\' ->" % Obj.GetClassName(),
    GetOutputPort = Obj.GetOutputPort()
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(GetOutputPort)
    surfaceFilter.Update()

    __save_vtp__(Obj.GetClassName(), surfaceFilter.GetOutput())

    return surfaceFilter
Exemplo n.º 45
0
def write_stl(ugrid, filename):
    surface_filter = vtk.vtkDataSetSurfaceFilter()
    surface_filter.SetInputData(ugrid)

    triangle_filter = vtk.vtkTriangleFilter()
    triangle_filter.SetInputConnection(surface_filter.GetOutputPort())

    writer = vtk.vtkSTLWriter()
    writer.SetFileName(filename)
    writer.SetInputConnection(triangle_filter.GetOutputPort())
    writer.Write()
Exemplo n.º 46
0
def cellthreshold(polydata, arrayname, start=0, end=1):
    threshold = vtk.vtkThreshold()
    threshold.SetInputData(polydata)
    threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,arrayname)
    threshold.ThresholdBetween(start,end)
    threshold.Update()

    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputConnection(threshold.GetOutputPort())
    surfer.Update()
    return surfer.GetOutput()
Exemplo n.º 47
0
 def _createPolyDataFilter(self):
     """Overrides baseclass implementation."""
     self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter()
     if self._useCellScalars:
         # Sets data to point instead of just cells
         c2p = vtk.vtkCellDataToPointData()
         c2p.SetInputData(self._vtkDataSet)
         c2p.Update()
         # For contouring duplicate points seem to confuse it
         self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort())
     else:
         self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
     self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter
Exemplo n.º 48
0
def pointthreshold(polydata, arrayname, start=0, end=1,alloff=0):
    threshold = vtk.vtkThreshold()
    threshold.SetInputData(polydata)
    threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,arrayname)
    threshold.ThresholdBetween(start,end)
    if (alloff):
        threshold.AllScalarsOff()
    threshold.Update()

    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputConnection(threshold.GetOutputPort())
    surfer.Update()
    return surfer.GetOutput()
def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(20)
    pointSource.Update()

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInputConnection(pointSource.GetOutputPort())
    idFilter.SetIdsArrayName("OriginalIds")
    idFilter.Update()

    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(idFilter.GetOutputPort())
    surfaceFilter.Update()

    poly_input = surfaceFilter.GetOutput()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()

    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    areaPicker = vtk.vtkAreaPicker()
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetPicker(areaPicker)
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    #renderer.SetBackground(1,1,1) # Background color white

    renderWindow.Render()

    style = vtk.vtkRenderWindowInteractor()
    #style = myInteractorStyle()
    #style = InteractorStyle()
    #style = QVTKRenderWindowInteractor()
    #style.SetPoints(poly_input)
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindowInteractor.Start()
Exemplo n.º 50
0
    def _plotInternalBoxfill(self):
        """Implements the logic to render a non-custom boxfill."""
        # Prep mapper
        mapper = vtk.vtkPolyDataMapper()
        self._mappers = [mapper]

        if self._gm.ext_1 and self._gm.ext_2:
            mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
            self._resultDict["vtk_backend_geofilters"] = \
                [self._vtkPolyDataFilter]
        else:
            thr = vtk.vtkThreshold()
            thr.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
            if not self._gm.ext_1 and not self._gm.ext_2:
                thr.ThresholdBetween(self._contourLevels[0],
                                     self._contourLevels[-1])
            elif self._gm.ext_1 and not self._gm.ext_2:
                thr.ThresholdByLower(self._contourLevels[-1])
            elif not self._gm.ext_1 and self._gm.ext_2:
                thr.ThresholdByUpper(self._contourLevels[0])

            geoFilter2 = vtk.vtkDataSetSurfaceFilter()
            geoFilter2.SetInputConnection(thr.GetOutputPort())
            mapper.SetInputConnection(geoFilter2.GetOutputPort())
            self._resultDict["vtk_backend_geofilters"] = [geoFilter2]

        # Colortable bit
        # make sure length match
        numLevels = len(self._contourLevels)
        while len(self._contourColors) < numLevels:
            self._contourColors.append(self._contourColors[-1])

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(numLevels)
        _colorMap = self.getColorMap()
        for i in range(numLevels):
            r, g, b, a = self.getColorIndexOrRGBA(_colorMap, self._contourColors[i])
            lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.)

        mapper.SetLookupTable(lut)
        if numpy.allclose(self._contourLevels[0], -1.e20):
            lmn = self._min - 1.
        else:
            lmn = self._contourLevels[0]
        if numpy.allclose(self._contourLevels[-1], 1.e20):
            lmx = self._mx + 1.
        else:
            lmx = self._contourLevels[-1]
        mapper.SetScalarRange(lmn, lmx)
        self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]
Exemplo n.º 51
0
  def __init__(self, renderer, mesh):
    PeacockActor.__init__(self, renderer)
    self.mesh = mesh

    self.geom = vtk.vtkDataSetSurfaceFilter()
    self.geom.SetInput(self.mesh)
    self.geom.Update()

    self.mapper = vtk.vtkPolyDataMapper()
    self.mapper.SetInput(self.geom.GetOutput())

    self.actor = vtk.vtkActor();
    self.actor.SetMapper(self.mapper);
    self.actor.GetProperty().SetPointSize(5)
    self.actor.GetProperty().SetEdgeColor(0,0,0)
    self.actor.GetProperty().SetAmbient(0.3);
Exemplo n.º 52
0
def countregions(polydata):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(surfer.GetOutputPort())
    cleaner.Update()

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.Update()
    return connect.GetNumberOfExtractedRegions()
    def AddDataSet(self, dataset, property=None):
        '''
        Add a dataset to the view (has to be subclass of vtkPointSet).
        The dataset will be cut through the implicit slice plane
        (GetImplicitSlicePlane()).
    
        This results in a loss of dimensionality, i.e. tetrahedron will be displayed
        as triangles, triangles as lines, lines as points.
        A vtkProperty of the dataset can be specified.
        @param dataset: vtkDataSet
        @param property: vtkProperty  
        @return: vtkActor
        '''
        if not dataset or self.getDataSetCollection().IsItemPresent(dataset):
            return None
        
        if vtk.vtkImageData.SafeDownCast(dataset):
            self.SetInput(vtk.vtkImageData.SafeDownCast(dataset))
            return None
        
        geometryextractor = vtk.vtkDataSetSurfaceFilter()
        normalextractor = vtk.vtkPolyDataNormals()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()
        
        normalextractor.SetFeatureAngle(90)
#        try to skip the normal extraction filter in order to enhance the visualization speed when the data is time sequence.
        
        geometryextractor.SetInput(dataset)
        normalextractor.SetInput(geometryextractor.GetOutput())
        mapper.SetInput(normalextractor.GetOutput())
        actor.SetMapper(mapper)
        if property:
            actor.SetProperty(property)
        
        self.GetRenderer().AddViewProp(actor)
        self.getDataSetCollection().AddItem(dataset)
        self.getProp3DCollection().AddItem(actor)
        
        self.GetRenderer().AddViewProp(actor)
        
        del mapper
        del normalextractor
        del geometryextractor
        del actor
Exemplo n.º 54
0
def extractclosestpointregion(polydata, point=[0, 0, 0]):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(surfer.GetOutputPort())
    cleaner.Update()

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.SetExtractionModeToClosestPointRegion()
    connect.SetClosestPoint(point)
    connect.Update()
    return connect.GetOutput()
Exemplo n.º 55
0
def extractconnectedregion(polydata, regionid):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(surfer.GetOutputPort())
    cleaner.Update()

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()
    surface = pointthreshold(connect.GetOutput(),'RegionId',float(regionid),float(regionid))
    return surface
Exemplo n.º 56
0
def convexHull(thePoints, color):
    points = vtk.vtkPoints()
    for pt in thePoints:
        points.InsertNextPoint(*pt)
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInput(polydata)
    delaunay.Update()
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) 
    surfaceFilter.Update()
    
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(surfaceFilter.GetOutput())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetOpacity(0.5)
    ren.AddActor(actor)
Exemplo n.º 57
0
 def _createPolyDataFilter(self):
     """This is only used when we use the grid stored in the file for all plots."""
     self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter()
     if self._hasCellData == self._needsCellData:
         self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
     elif self._hasCellData:
         # use cells but needs points
         c2p = vtk.vtkCellDataToPointData()
         c2p.PassCellDataOn()
         c2p.SetInputData(self._vtkDataSet)
         self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort())
     else:
         # use points but needs cells
         p2c = vtk.vtkPointDataToCellData()
         p2c.SetInputData(self._vtkDataSet)
         # For contouring duplicate points seem to confuse it
         self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort())
     self._vtkPolyDataFilter.Update()
     self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter
     # create an actor and a renderer for the surface mesh.
     # this is used for displaying point information using the hardware selection
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
     act = vtk.vtkActor()
     act.SetMapper(mapper)
     vp = self._resultDict.get(
         'ratio_autot_viewport',
         [self._template.data.x1, self._template.data.x2,
          self._template.data.y1, self._template.data.y2])
     plotting_dataset_bounds = self.getPlottingBounds()
     surface_renderer, xScale, yScale = self._context().fitToViewport(
         act, vp,
         wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(),
         geo=self._vtkGeoTransform,
         priority=self._template.data.priority,
         create_renderer=True)
     self._resultDict['surface_renderer'] = surface_renderer
     self._resultDict['surface_scale'] = (xScale, yScale)
     if (surface_renderer):
         surface_renderer.SetDraw(False)
Exemplo n.º 58
0
def extractlargestregion(polydata):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(surfer.GetOutputPort())
    cleaner.Update()

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.SetExtractionModeToLargestRegion()
    connect.Update()

    # leaves phantom points ....
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(connect.GetOutputPort())
    cleaner.Update()
    return cleaner.GetOutput()