Пример #1
0
   def vtkPlotMesh(self, courbure = "MEAN"):
      """ Creation du maillage surfacique """
      self.meshActor = None
      self.vtkMeshCurvature = None
      # Creation de l'information des courbures
      self.vtkMeshCurvature = vtk.vtkCurvatures()
      if courbure == "GAUSS" : self.vtkMeshCurvature.SetCurvatureTypeToGaussian()
      if courbure == "MEAN"  : self.vtkMeshCurvature.SetCurvatureTypeToMean()
      self.vtkMeshCurvature.SetInputConnection(self.outputMesh.GetOutputPort())
      self.vtkMeshCurvature.Update()
      range_curvature = self.vtkMeshCurvature.GetOutput().GetScalarRange()

      # Create color of curvature
      Lut = vtk.vtkLookupTable()
      Lut.SetNumberOfColors(256)
      Lut.SetRange(range_curvature[0], range_curvature[1])
      Lut.Build()
      # Create the mapper that corresponds the objects of the vtk file
      # into graphics elements
      self.meshMapper = vtk.vtkPolyDataMapper()
      self.meshMapper.SetInputConnection(self.meshNormals.GetOutputPort())
      self.meshMapper.SetLookupTable(Lut)
      self.meshMapper.SetUseLookupTableScalarRange(1)
      # Create the Actor
      self.vtkDeleteMesh()
      self.meshActor = vtk.vtkActor()
      self.meshActor.SetMapper(self.meshMapper)
      self.meshActor.GetProperty().SetDiffuseColor(1, 0.2, 0.2)
      self.ren.AddActor(self.meshActor)
      self.vtkRedraw()
Пример #2
0
def curvature(actor, method=1, r=1, alpha=1, lut=None, legend=None):
    '''
    Build a copy of vtkActor that contains the color coded surface
    curvature following four different ways to calculate it:
        method =  0-gaussian, 1-mean, 2-max, 3-min

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py)
    '''
    poly = actor.polydata()
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputData(poly)
    curve = vtk.vtkCurvatures()
    curve.SetInputConnection(cleaner.GetOutputPort())
    curve.SetCurvatureType(method)
    curve.InvertMeanCurvatureOn()
    curve.Update()
    print('CurvatureType set to:', method)
    if not lut:
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0.15, 1)
        lut.SetSaturationRange(1, 1)
        lut.SetValueRange(1, 1)
        lut.SetAlphaRange(alpha, 1)
        b = poly.GetBounds()
        sc = max([b[1]-b[0], b[3]-b[2], b[5]-b[4]])
        lut.SetRange(-0.01/sc*r, 0.01/sc*r)
    cmapper = vtk.vtkPolyDataMapper()
    cmapper.SetInputConnection(curve.GetOutputPort())
    cmapper.SetLookupTable(lut)
    cmapper.SetUseLookupTableScalarRange(1)
    cactor = vtk.vtkActor()
    cactor.SetMapper(cmapper)
    return cactor
Пример #3
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)


        # we'll be playing around with some vtk objects, this could
        # be anything
        self._triangleFilter = vtk.vtkTriangleFilter()
        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMaximum()
        self._curvatures.SetInput(self._triangleFilter.GetOutput())

        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self,
                {'Module (self)' : self,
                    'vtkTriangleFilter' : self._triangleFilter,
                    'vtkCurvatures' : self._curvatures})

        module_utils.setup_vtk_object_progress(self, self._triangleFilter,
                                           'Triangle filtering...')
        module_utils.setup_vtk_object_progress(self, self._curvatures,
                                           'Calculating curvatures...')
        
        
        self.sync_module_logic_with_config()
Пример #4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkCurvatures(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Пример #5
0
def GetCurvature(vtkdata):
    curve = vtk.vtkCurvatures()
    curve.SetCurvatureTypeToMinimum()
    curve.SetInputData(vtkdata)
    curve.Update()
    vtkdata = curve.GetOutput()
    return vtkdata
Пример #6
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)

        # we'll be playing around with some vtk objects, this could
        # be anything
        self._triangleFilter = vtk.vtkTriangleFilter()
        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMaximum()
        self._curvatures.SetInput(self._triangleFilter.GetOutput())

        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(
            self, {
                'Module (self)': self,
                'vtkTriangleFilter': self._triangleFilter,
                'vtkCurvatures': self._curvatures
            })

        module_utils.setup_vtk_object_progress(self, self._triangleFilter,
                                               'Triangle filtering...')
        module_utils.setup_vtk_object_progress(self, self._curvatures,
                                               'Calculating curvatures...')

        self.sync_module_logic_with_config()
Пример #7
0
def get_curvature_mean(poly_data):
    curvatures = vtk.vtkCurvatures()
    curvatures.SetInputConnection(poly_data.GetOutputPort())
    curvatures.SetCurvatureTypeToMean()
    curvatures.Update()
    pd = curvatures.GetOutput()
    pd.GetPointData().SetActiveScalars('Mean_Curvature')
    Mean = vtk_to_numpy(pd.GetPointData().GetArray(1))
    return Mean
Пример #8
0
def get_node_curvatures(vtk_mesh, curvature_type='min'):
    curvature = vtk.vtkCurvatures()
    if curvature_type == 'min':
        curvature.SetCurvatureTypeToMinimum()
    elif curvature_type == 'max':
        curvature.SetCurvatureTypeToMaximum()
    curvature.SetInputData(vtk_mesh)
    curvature.Update()
    return curvature.GetOutput()
Пример #9
0
def get_curvature_gaussian(poly_data):
    curv = vtk.vtkCurvatures()
    curv.SetInputConnection(poly_data.GetOutputPort())
    curv.SetCurvatureTypeToGaussian()
    curv.Update()
    pd = curv.GetOutput()
    pd.GetPointData().SetActiveScalars('Gauss_Curvature')
    gaussian = vtk_to_numpy(pd.GetPointData().GetArray(1))
    return gaussian
Пример #10
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkCurvatures(),
                                       'Processing.', ('vtkPolyData', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
def compute_curvature(polydata):
    curvaturesFilter = vtk.vtkCurvatures()
    curvaturesFilter.SetInputData(polydata)
    curvaturesFilter.SetCurvatureTypeToMinimum()
    curvaturesFilter.SetCurvatureTypeToMaximum()
    curvaturesFilter.SetCurvatureTypeToGaussian()
    curvaturesFilter.SetCurvatureTypeToMean()
    curvaturesFilter.Update()
    return curvaturesFilter.GetOutput()
Пример #12
0
def mean_curvature(s):
    curve1 = vtkCurvatures()
    s = createPolyData(s.vertices, s.faces)
    curve1.SetInput(s)
    curve1.SetCurvatureTypeToMean()
    curve1.Update()
    m = curve1.GetOutput()
    m = vtk_to_numpy(m.GetPointData().GetScalars())
    return m
Пример #13
0
    def compute_curvatures(self, vertices, faces):
 
        pts, tris = self.arrayToPolydata(vertices, faces)
        polys = vtk.vtkPolyData()    
        polys.SetPoints(pts)
        polys.SetPolys(tris)
        polys.Update()
        
        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(polys)
        sources.append(polys)
 
        curvatures = list()        
        curvatures.append(vtk.vtkCurvatures())
        curvatures.append(vtk.vtkCurvatures())
        
        curvatures[0].SetCurvatureTypeToMaximum()
        curvatures[1].SetCurvatureTypeToMinimum()
        
        # Link the pipeline together. 
        for idx, item in enumerate(sources):
            sources[idx].Update()
            curvatures[idx].SetInput(sources[idx])
            curvatures[idx].Update()
            
        c_min = curvatures[1]
        curvMin = c_min.GetOutput().GetPointData().GetScalars()
        
        c_max = curvatures[0]
        curvMax = c_max.GetOutput().GetPointData().GetScalars()
        
        min_hist_4 = createHistogram(4, curvMin)
        min_hist_8 = createHistogram(8, curvMin)
        min_hist_16 = createHistogram(16, curvMin)
        
        max_hist_4 = createHistogram(4, curvMax)
        max_hist_8 = createHistogram(8, curvMax)
        max_hist_16 = createHistogram(16, curvMax)
        
        #[[MIN_4, MIN_8, MIN_16], [MAX_4, MAX_8, MAX_16]]
        return [[min_hist_4, min_hist_8, min_hist_16], [max_hist_4, max_hist_8, max_hist_16]]
def CalculateCurvatures(src):
    '''
    The source must be triangulated.
    :param: src - the source.
    :return: vtkPolyData with normal and scalar data representing curvatures.
    '''
    curvature = vtk.vtkCurvatures()
    curvature.SetCurvatureTypeToGaussian()
    curvature.SetInputData(src)
    curvature.Update()
    return curvature.GetOutput()
Пример #15
0
def CalculateCurvatures(src):
    """
    The source must be triangulated.
    :param: src - the source.
    :return: vtkPolyData with normal and scalar data representing curvatures.
    """
    curvature = vtk.vtkCurvatures()
    curvature.SetCurvatureTypeToGaussian()
    curvature.SetInputData(src)
    curvature.Update()
    return curvature.GetOutput()
Пример #16
0
def PlotCurvature(mesh, curvtype):
    """ Plots curvature of a mesh """

    # Curvatures Filter
    curvefilter = vtk.vtkCurvatures()

    curvefilter.SetInput(mesh)

    if curvtype == 'Mean':
        curvefilter.SetCurvatureTypeToMean()
    elif curvtype == 'Gaussian':
        curvefilter.SetCurvatureTypeToGaussian()
    elif curvtype == 'Maximum':
        curvefilter.SetCurvatureTypeToMaximum()
    else:
        curvefilter.SetCurvatureTypeToMinimum()

    # Get curves
    curvefilter.Update()

    # Mapper
    mapper = vtk.vtkDataSetMapper()
    if vtk.vtkVersion().GetVTKMajorVersion() > 5:
        mapper.SetInputData(curvefilter.GetOutput())
    else:
        mapper.SetInput(curvefilter.GetOutput())

    # Actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().LightingOff()

    ###############################
    # Display
    ###############################

    # Render
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Allow user to interact
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)

    ren.AddActor(actor)

    iren.Initialize()
    renWin.Render()
    iren.Start()
Пример #17
0
def PlotCurvature(mesh, curvtype):
    """ Plots curvature of a mesh """
    
    # Curvatures Filter
    curvefilter = vtk.vtkCurvatures()
    
    curvefilter.SetInput(mesh)
    
    if curvtype == 'Mean':
        curvefilter.SetCurvatureTypeToMean()
    elif curvtype == 'Gaussian': 
        curvefilter.SetCurvatureTypeToGaussian()
    elif curvtype == 'Maximum':
        curvefilter.SetCurvatureTypeToMaximum()
    else:
        curvefilter.SetCurvatureTypeToMinimum()

    # Get curves
    curvefilter.Update()
    
    # Mapper
    mapper = vtk.vtkDataSetMapper()
    if vtk.vtkVersion().GetVTKMajorVersion() >5:
        mapper.SetInputData(curvefilter.GetOutput())
    else:
        mapper.SetInput(curvefilter.GetOutput())
    
    # Actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().LightingOff()    
        
    ###############################
    # Display
    ###############################
    
    # Render
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    # Allow user to interact
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    
    ren.AddActor(actor)
        
    iren.Initialize()
    renWin.Render()
    iren.Start()
Пример #18
0
    def compute_Curvature(self):

        self.curvaturesFilter = vtk.vtkCurvatures()
        self.curvaturesFilter.SetInputConnection(self.dmc.GetOutputPort())
        self.curvaturesFilter.SetCurvatureTypeToMean()

        self.curvaturesFilter.Update()

        np.savetxt(
            "./result.txt",
            np.trim_zeros(
                vtk_to_numpy(self.curvaturesFilter.GetOutput().GetPointData().
                             GetScalars())))
Пример #19
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        mm = self._module_manager

        self._cleaner = vtk.vtkCleanPolyData()

        self._tf = vtk.vtkTriangleFilter()
        self._tf.SetInput(self._cleaner.GetOutput())

        self._wspdf = vtk.vtkWindowedSincPolyDataFilter()
        #self._wspdf.SetNumberOfIterations(50)
        self._wspdf.SetInput(self._tf.GetOutput())
        self._wspdf.SetProgressText('smoothing')
        self._wspdf.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf))

        self._cleaner2 = vtk.vtkCleanPolyData()
        self._cleaner2.SetInput(self._wspdf.GetOutput())

        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMean()
        self._curvatures.SetInput(self._cleaner2.GetOutput())

        self._tf.SetProgressText('triangulating')
        self._tf.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf))

        self._curvatures.SetProgressText('calculating curvatures')
        self._curvatures.SetProgressMethod(
            lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures))

        self._inputFilter = self._tf

        self._inputPoints = None
        self._inputPointsOID = None
        self._giaGlenoid = None
        self._outsidePoints = None
        self._outputPolyDataARB = vtk.vtkPolyData()
        self._outputPolyDataHM = vtk.vtkPolyData()

        self._createViewFrame('Test Module View', {
            'vtkTriangleFilter': self._tf,
            'vtkCurvatures': self._curvatures
        })

        self._viewFrame.Show(True)
Пример #20
0
    def Curvature(self, curvature='mean'):
        """
        Returns the pointwise curvature of a mesh


        Parameters
        ----------
        mesh : vtk.polydata
            vtk polydata mesh

        curvature string, optional
            One of the following strings
            Mean
            Gaussian
            Maximum
            Minimum


        Returns
        -------
        curvature : np.ndarray
            Curvature values

        """
        curvature = curvature.lower()

        # Create curve filter and compute curvature
        curvefilter = vtk.vtkCurvatures()
        curvefilter.SetInputData(self)
        if curvature == 'mean':
            curvefilter.SetCurvatureTypeToMean()
        elif curvature == 'gaussian':
            curvefilter.SetCurvatureTypeToGaussian()
        elif curvature == 'maximum':
            curvefilter.SetCurvatureTypeToMaximum()
        elif curvature == 'minimum':
            curvefilter.SetCurvatureTypeToMinimum()
        else:
            raise Exception('Curvature must be either "Mean", ' +
                            '"Gaussian", "Maximum", or "Minimum"')
        curvefilter.Update()

        # Compute and return curvature
        curves = curvefilter.GetOutput()
        return vtk_to_numpy(curves.GetPointData().GetScalars())
Пример #21
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        mm = self._module_manager

        self._cleaner = vtk.vtkCleanPolyData()

        self._tf = vtk.vtkTriangleFilter()
        self._tf.SetInput(self._cleaner.GetOutput())

        self._wspdf = vtk.vtkWindowedSincPolyDataFilter()
        # self._wspdf.SetNumberOfIterations(50)
        self._wspdf.SetInput(self._tf.GetOutput())
        self._wspdf.SetProgressText("smoothing")
        self._wspdf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf))

        self._cleaner2 = vtk.vtkCleanPolyData()
        self._cleaner2.SetInput(self._wspdf.GetOutput())

        self._curvatures = vtk.vtkCurvatures()
        self._curvatures.SetCurvatureTypeToMean()
        self._curvatures.SetInput(self._cleaner2.GetOutput())

        self._tf.SetProgressText("triangulating")
        self._tf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf))

        self._curvatures.SetProgressText("calculating curvatures")
        self._curvatures.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures))

        self._inputFilter = self._tf

        self._inputPoints = None
        self._inputPointsOID = None
        self._giaGlenoid = None
        self._outsidePoints = None
        self._outputPolyDataARB = vtk.vtkPolyData()
        self._outputPolyDataHM = vtk.vtkPolyData()

        self._createViewFrame("Test Module View", {"vtkTriangleFilter": self._tf, "vtkCurvatures": self._curvatures})

        self._viewFrame.Show(True)
Пример #22
0
def add_curvature_to_vtk_surface(surface, curvature_type, invert=True):
    """
    Adds curvatures (Gaussian, mean, maximum or minimum) calculated by VTK to
    each triangle vertex of a vtkPolyData surface.

    Args:
        surface (vtk.vtkPolyData): a surface of triangles
        curvature_type (str): type of curvature to add: 'Gaussian', 'Mean',
            'Maximum' or 'Minimum'
        invert (boolean, optional): if True (default), VTK will calculate
            curvatures as for meshes with opposite pointing normals (their
            convention is outwards pointing normals, opposite from ours)

    Returns:
        the vtkPolyData surface with '<type>_Curvature' property added to each
        triangle vertex
    """
    if isinstance(surface, vtk.vtkPolyData):
        curvature_filter = vtk.vtkCurvatures()
        curvature_filter.SetInputData(surface)
        if curvature_type == "Gaussian":
            curvature_filter.SetCurvatureTypeToGaussian()
        elif curvature_type == "Mean":
            curvature_filter.SetCurvatureTypeToMean()
        elif curvature_type == "Maximum":
            curvature_filter.SetCurvatureTypeToMaximum()
        elif curvature_type == "Minimum":
            curvature_filter.SetCurvatureTypeToMinimum()
        else:
            raise pexceptions.PySegInputError(
                expr='add_curvature_to_vtk_surface',
                msg=("One of the following strings required as the second "
                     "input: 'Gaussian', 'Mean', 'Maximum' or 'Minimum'."))
        if invert:
            curvature_filter.InvertMeanCurvatureOn()  # default Off
        curvature_filter.Update()
        surface_curvature = curvature_filter.GetOutput()
        return surface_curvature
    else:
        raise pexceptions.PySegInputError(
            expr='add_curvature_to_vtk_surface',
            msg="A vtkPolyData object required as the first input.")
Пример #23
0
    def get_point_curvatures(self, method='mean'):
        curv = vtk.vtkCurvatures()
        curv.SetInputData(self.vtkPolyData)
        if method == 'mean':
            curv.SetCurvatureTypeToMean()
        elif method == 'max':
            curv.SetCurvatureTypeToMaximum()
        elif method == 'min':
            curv.SetCurvatureTypeToMinimum()
        elif method == 'Gaussian':
            curv.SetCurvatureTypeToGaussian()
        else:
            curv.SetCurvatureTypeToMean()
        curv.Update()

        n_points = self.vtkPolyData.GetNumberOfPoints()
        self.point_attributes['Curvature'] = np.zeros([n_points, 1])
        for i in range(n_points):
            self.point_attributes['Curvature'][i] = curv.GetOutput(
            ).GetPointData().GetArray(0).GetValue(i)
Пример #24
0
def filter_curvature(vtkObject, mode='gaussian'):
    """
    Create vtkCurvatures filter on vtkObject.

    :param vtkObject: input
    :param mode: gaussian or mean

    :type vtkObject: :py:class:`vtk.vtkObject`
    :type mode: str

    >>> image_data = create_image_data_from_array(surf)
    >>> cubes = filter_marching_cubes(image_data)
    >>> curve = filter_curvature(cubes)
    >>> show(curve)
    """
    curvature = vtk.vtkCurvatures()
    pipe(vtkObject, curvature)
    curvature.SetCurvatureTypeToMean()
    if mode == 'gaussian':
        curvature.SetCurvatureTypeToGaussian()
    return curvature
Пример #25
0
def filter_curvature(vtkObject, mode='gaussian'):
    """
    Create vtkCurvatures filter on vtkObject.

    :param vtkObject: input
    :param mode: gaussian or mean

    :type vtkObject: :py:class:`vtk.vtkObject`
    :type mode: str

    >>> image_data = create_image_data_from_array(surf)
    >>> cubes = filter_marching_cubes(image_data)
    >>> curve = filter_curvature(cubes)
    >>> show(curve)
    """
    curvature = vtk.vtkCurvatures()
    pipe(vtkObject, curvature)
    curvature.SetCurvatureTypeToMean()
    if mode == 'gaussian':
        curvature.SetCurvatureTypeToGaussian()
    return curvature
Пример #26
0
    def compute_curvatures_backup(self, vertices, faces):
 
        pts, tris = self.arrayToPolydata(vertices, faces)
        polys = vtk.vtkPolyData()    
        polys.SetPoints(pts)
        polys.SetPolys(tris)
        polys.Update()
        
        print "Vertices: " + str(len(vertices))
        print "Faces: " + str(tris.GetNumberOfCells())
        
        tri_2 = vtk.vtkTriangleFilter()
        tri_2.SetInput(polys)
 
        # 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
        cleaner_2 = vtk.vtkCleanPolyData()
        cleaner_2.SetInputConnection(tri_2.GetOutputPort())
        cleaner_2.SetTolerance(0.005)
        
        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner_2)
        sources.append(cleaner_2)
#        sources.append(cleaner_2)
#        sources.append(cleaner_2)
 
        curvatures = list()        
        curvatures.append(vtk.vtkCurvatures())
        curvatures.append(vtk.vtkCurvatures())
#        curvatures.append(vtk.vtkCurvatures())
#        curvatures.append(vtk.vtkCurvatures())
        
        curvatures[0].SetCurvatureTypeToMaximum()
        curvatures[1].SetCurvatureTypeToMinimum()
#        curvatures[2].SetCurvatureTypeToGaussian()
#        curvatures[3].SetCurvatureTypeToMean()
        
        # Link the pipeline together. 
        for idx, item in enumerate(sources):
            sources[idx].Update()
            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())
            curvatures[idx].Update()
            
        c_min = curvatures[1]
        curvMin = c_min.GetOutput().GetPointData().GetScalars()
        
        c_max = curvatures[0]
        curvMax = c_max.GetOutput().GetPointData().GetScalars()
        
        min_hist_4 = createHistogram(4, curvMin)
        min_hist_8 = createHistogram(8, curvMin)
        min_hist_16 = createHistogram(16, curvMin)
        
        max_hist_4 = createHistogram(4, curvMax)
        max_hist_8 = createHistogram(8, curvMax)
        max_hist_16 = createHistogram(16, curvMax)
        
        #[[MIN_4, MIN_8, MIN_16], [MAX_4, MAX_8, MAX_16]]
        return [[min_hist_4, min_hist_8, min_hist_16], [max_hist_4, max_hist_8, max_hist_16]]
Пример #27
0
    def CurvaturesDemo(self):

        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource()
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution(64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness(1)
        torus.SetThickness(0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1)

        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)

        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)

        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())

        # 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

        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)

        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)

        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)

        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0))

        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()

        curvatures = list()
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()

        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        names = [
            'Torus - Gaussian Curvature', 'Torus - Mean Curvature',
            'Random Hills - Gaussian Curvature',
            'Random Hills - Mean Curvature'
        ]

        # Link the pipeline together.
        for idx, item in enumerate(sources):
            sources[idx].Update()

            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 2

        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)

        rendererSize = 300

        # Create the RenderWindow
        #
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(rendererSize * gridDimensions,
                             rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - (row + 1)) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - row) * rendererSize /
                    (gridDimensions * rendererSize))

                if idx > (len(sources) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                renderWindow.AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4, 0.3, 0.2)

        interactor = vtk.vtkRenderWindowInteractor()
        interactor.SetRenderWindow(renderWindow)

        renderWindow.Render()

        interactor.Start()
Пример #28
0
import vtk_functions

import vtk
import numpy as np
from vtk.util import numpy_support

if __name__ == "__main__":
    r = 100

    polydata = vtk_functions.read_ply(
        "/home/steven/scriptie/inputs/meshes/sphere_r_100_p_20_MLX.ply")
    polydata = vtk_functions.normals(polydata)

    # Use VTK to get H
    mcFilter = vtk.vtkCurvatures()
    mcFilter.SetCurvatureTypeToMean()
    mcFilter.SetInputData(polydata)
    mcFilter.Update()

    points = mcFilter.GetOutput().GetPoints()
    vals = mcFilter.GetOutput().GetPointData().GetScalars()
    mc_errors = []

    for i in range(points.GetNumberOfPoints()):
        p = points.GetPoint(i)
        val = vals.GetComponent(i, 0)

        # Compare VTK H with analytic H to derive error
        mc_error = abs(val - 1 / r) / (1 / r) * 100
        mc_errors.append(mc_error)
Пример #29
0
	def CurvaturesDemo(self, filePath, nominalRadius):
		sphere = Sphere(filePath, nominalRadius, False)
		errors = np.abs(sphere.fittingError())
		print sphere.curvature.max()
		print sphere.curvature.argmax()

		reader = vtk.vtkOBJReader()
		reader.SetFileName(sys.argv[1])
		reader.Update()

		# Colour transfer function.
		ctf = vtk.vtkColorTransferFunction()
		ctf.SetColorSpaceToDiverging()
		ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
		ctf.AddRGBPoint(0.5, 1.0, 1.0, 1.0)
		ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
		cc = list()
		for i in range(256):
			cc.append(ctf.GetColor(float(i) / 255.0)) 

		scalars = vtk.vtkFloatArray()
		scalars.SetNumberOfComponents(1)

		for errorVal in errors:
			scalars.InsertNextTuple([errorVal])

		mean = np.mean(errors)
		std = np.std(errors)
		min3 = mean - std
		max3 = mean + std

		# Now we have the sources, lets put them into a list.
		sources = list()
		sources.append(reader)
		sources.append(reader)
		sources.append(sphere.polyData)
		sources.append(sphere.polyData)

		curvatures = list()        
		for idx in range(2):
			curvatures.append(vtk.vtkCurvatures())
			curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())
			if idx % 2 == 0:
				curvatures[idx].SetCurvatureTypeToGaussian()
				curvatures[idx].Update()
				npcurv1 =  numpy_support.vtk_to_numpy(curvatures[idx].GetOutput().GetPointData().GetScalars())
		
				mean = np.mean(npcurv1)
				std = np.std(npcurv1)

				min1 = 0.01*(mean - std)
				max1 = 0.01*(mean + std)
			else:
				curvatures[idx].SetCurvatureTypeToMean()
				curvatures[idx].Update()
				npcurv2 =  np.abs(numpy_support.vtk_to_numpy(curvatures[idx].GetOutput().GetPointData().GetScalars()))

				mean = np.mean(npcurv2)
				std = np.std(npcurv2)
				#print 'Curvature (min / max / mean / total): ' + str(np.min(npcurv2)) + ' / ' + str(np.max(npcurv2)) + ' / ' + str(np.mean(npcurv2)) + ' / ' + str(np.sum(npcurv2))

				min2 = mean - std
				max2 = mean + std
		fig = plt.figure()
		xa = np.arange(-0.1, 0.1,0.001)
		#plt.hist(npcurv1, bins=xa)
		plt.hist(npcurv2/npcurv2.max(), bins=xa)
		print 'By vtk:'
		print npcurv2.max()
		print npcurv2.argmax()
		plt.gca().set_yscale('log')
		plt.show()

		# Lookup table.
		lut = list()
		for idx in range(len(sources)):
			lut.append(vtk.vtkLookupTable())
			lut[idx].SetNumberOfColors(256)
			for i, item in enumerate(cc):
				lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
			if idx == 0:
				lut[idx].SetRange(min1, max1)
			if idx == 1:
				lut[idx].SetRange(min2, max2)
			if idx == 2:
				lut[idx].SetRange(min3, max3)
			lut[idx].Build()


		renderers = list()
		mappers = list()
		actors = list()
		textmappers = list()
		textactors = list()
		scalarbars = list()

		# Create a common text property.
		textProperty = vtk.vtkTextProperty()
		textProperty.SetFontSize(16)
		textProperty.SetJustificationToCentered()

		names = ['Sphere - Gaussian Curvature', 'Sphere - Mean Curvature', 'Sphere - Residuals to fitted sphere', 'Sphere - Residuals to fitted sphere']

		# Link the pipeline together. 
		for idx, item in enumerate(sources):
			#sources[idx].Update()


			mappers.append(vtk.vtkPolyDataMapper())
			mappers[idx].SetUseLookupTableScalarRange(1)
			if idx < 2:
				#print npcurv.min(), npcurv.max()
				#print npcurv

				mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
				mappers[idx].SetLookupTable(lut[idx])
			else:
				#mappers[idx].SetInputConnection(sources[idx].GetOutputPort())
				mappers[idx].SetInputData(sources[idx])
				mappers[idx].SetColorModeToMapScalars()
				#mappers[idx].GetPointData().SetScalars(scalars)
				mappers[idx].SetLookupTable(lut[idx])

			actors.append(vtk.vtkActor())
			actors[idx].SetMapper(mappers[idx])
			if idx == 3:
				actors[idx].GetProperty().SetEdgeVisibility(1)
				actors[idx].GetProperty().SetEdgeColor(0.5, 0.5, 0.5);
				actors[idx].GetProperty().SetLineWidth(0.5)

			textmappers.append(vtk.vtkTextMapper())
			textmappers[idx].SetInput(names[idx])
			textmappers[idx].SetTextProperty(textProperty)

			textactors.append(vtk.vtkActor2D())
			textactors[idx].SetMapper(textmappers[idx])
			textactors[idx].SetPosition(150, 16)

			scalarbars.append(vtk.vtkScalarBarActor())
			scalarbars[idx].SetLookupTable(lut[idx])

			renderers.append(vtk.vtkRenderer())

		gridDimensions = 2

		for idx in range(len(sources)):
			if idx < gridDimensions * gridDimensions:
				renderers.append(vtk.vtkRenderer)

		rendererSize = 300

		# Create the RenderWindow
		#
		renderWindow = vtk.vtkRenderWindow()
		renderWindow.SetSize(rendererSize * gridDimensions, 0)

		# Add and position the renders to the render window.
		viewport = list()
		for row in range(gridDimensions):
			for col in range(gridDimensions):
				idx = row * gridDimensions + col

				viewport[:] = []
				viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
				viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
				viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
				viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))

				if idx > (len(sources) - 1):
					continue

				renderers[idx].SetViewport(viewport)
				renderWindow.AddRenderer(renderers[idx])

				renderers[idx].AddActor(actors[idx])
				renderers[idx].AddActor(textactors[idx])
				renderers[idx].AddActor(scalarbars[idx])
				renderers[idx].SetBackground(0.5,0.5,0.5)

		interactor = vtk.vtkRenderWindowInteractor()
		interactor.SetRenderWindow(renderWindow)

		renderWindow.Render()

		interactor.Start()
Пример #30
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        curvatureFilter = vtk.vtkCurvatures()
        curvatureFilter.SetInput(self.Surface)
        if self.CurvatureType == 'mean':
            curvatureFilter.SetCurvatureTypeToMean()
        elif self.CurvatureType == 'gaussian':
            curvatureFilter.SetCurvatureTypeToGaussian()
        elif self.CurvatureType == 'maximum':
            curvatureFilter.SetCurvatureTypeToMaximum()
        elif self.CurvatureType == 'minimum':
            curvatureFilter.SetCurvatureTypeToMinimum()
        curvatureFilter.Update()

        activeScalars = curvatureFilter.GetOutput().GetPointData().GetScalars()
        activeScalars.SetName('Curvature')

        if self.AbsoluteCurvature:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                activeScalars.SetTuple1(i, abs(value))

        neighborhoods = None
        if not self.CurvatureOnBoundaries or self.MedianFiltering:
            neighborhoods = vtkvmtk.vtkvmtkNeighborhoods()
            neighborhoods.SetNeighborhoodTypeToPolyDataManifoldNeighborhood()
            neighborhoods.SetDataSet(self.Surface)
            neighborhoods.Build()

        if not self.CurvatureOnBoundaries:
            boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor()
            boundaryExtractor.SetInput(self.Surface)
            boundaryExtractor.Update()
            boundaryIdsArray = vtk.vtkIdTypeArray.SafeDownCast(
                boundaryExtractor.GetOutput().GetPointData().GetScalars())
            boundaryIds = vtk.vtkIdList()
            boundaryIds.SetNumberOfIds(boundaryIdsArray.GetNumberOfTuples())
            for i in range(boundaryIdsArray.GetNumberOfTuples()):
                boundaryIds.SetId(i, boundaryIdsArray.GetValue(i))
            self.Surface.BuildLinks()
            for i in range(boundaryIds.GetNumberOfIds()):
                pointId = boundaryIds.GetId(i)
                neighborhood = neighborhoods.GetNeighborhood(pointId)
                values = []
                for j in range(neighborhood.GetNumberOfPoints()):
                    neighborId = neighborhood.GetPointId(j)
                    if boundaryIds.IsId(neighborId) != -1:
                        continue
                    value = activeScalars.GetTuple1(neighborId)
                    values.append(value)
                values.sort()
                if not values:
                    continue
                medianValue = values[(len(values) - 1) / 2]
                activeScalars.SetTuple1(pointId, medianValue)

        if self.MedianFiltering:
            for i in range(neighborhoods.GetNumberOfNeighborhoods()):
                neighborhood = neighborhoods.GetNeighborhood(i)
                values = []
                for j in range(neighborhood.GetNumberOfPoints()):
                    neighborId = neighborhood.GetPointId(j)
                    value = activeScalars.GetTuple1(neighborId)
                    values.append(value)
                values.sort()
                if not values:
                    continue
                medianValue = values[(len(values) - 1) / 2]
                activeScalars.SetTuple1(i, medianValue)

        if self.BoundedReciprocal:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                reciprocalValue = 1.0 / (self.Epsilon + value)
                activeScalars.SetTuple1(i, reciprocalValue)

        if self.Offset:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                activeScalars.SetTuple1(i, value + self.Offset)

        if self.ReferenceSurface == None:
            self.Surface.GetPointData().AddArray(activeScalars)
        else:
            self.ReferenceSurface.GetPointData().AddArray(activeScalars)
            self.Surface = self.ReferenceSurface
Пример #31
0
smooth.SetFeatureAngle(45)
smooth.SetEdgeAngle(15)
smooth.SetBoundarySmoothing(1)
smooth.SetFeatureEdgeSmoothing(0)
smooth.Update()
'''

# ---- Vertices - smoothed ---------------------
smooth_verts = smooth.GetOutput().GetPoints().GetData()
output_smooth_verts = array(
    numpy_support.vtk_to_numpy(smooth_verts).transpose(), 'd')

if debug: print output_smooth_verts

# ---- Curvature ---------------------
curvature = vtk.vtkCurvatures()
curvature.SetInputConnection(smooth.GetOutputPort())
curvature.SetCurvatureTypeToMean()
curvature.Update()

curv = curvature.GetOutput().GetPointData().GetScalars()
output_curvature = array(numpy_support.vtk_to_numpy(curv).transpose(), 'd')

if debug: print min(output_curvature)
if debug: print max(output_curvature)
if debug: print output_curvature

# -------- colours based on curvature ------------

# turn curvature into color
tmp_colors = output_curvature.copy()
Пример #32
0
def flow(mesh_file, iter_num, show_flow=False):
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(mesh_file)
    reader.Update()

    mesh = reader.GetOutput()
    tol = 0.05
    q = 1.0
    dt = 0.001
    orig_mesh = mesh
    prev_mesh = mesh
    thin_plate_spline_list = []
    for i in range(iter_num + 1):
        deformed_surface_writer = vtk.vtkPolyDataWriter()
        deformed_surface_writer.SetFileName('data/flow/' + str(i) + '.vtk')
        deformed_surface_writer.SetInputData(mesh)
        deformed_surface_writer.Update()

        taubin_smooth = vtk.vtkWindowedSincPolyDataFilter()
        taubin_smooth.SetInputData(mesh)
        taubin_smooth.SetNumberOfIterations(20)
        taubin_smooth.BoundarySmoothingOff()
        taubin_smooth.FeatureEdgeSmoothingOff()
        taubin_smooth.SetPassBand(0.01)
        taubin_smooth.NonManifoldSmoothingOn()
        taubin_smooth.NormalizeCoordinatesOn()

        taubin_smooth.Update()
        mesh = taubin_smooth.GetOutput()

        normal_generator = vtk.vtkPolyDataNormals()
        normal_generator.SetInputData(mesh)
        normal_generator.SplittingOff()
        normal_generator.ComputePointNormalsOn()
        normal_generator.ComputeCellNormalsOff()
        normal_generator.Update()
        mesh = normal_generator.GetOutput()

        curvatures = vtk.vtkCurvatures()
        curvatures.SetCurvatureTypeToMean()
        curvatures.SetInputData(mesh)
        curvatures.Update()

        mean_curvatures = curvatures.GetOutput().GetPointData().GetArray("Mean_Curvature")
        normals = normal_generator.GetOutput().GetPointData().GetNormals()

        mesh_pts = mesh.GetPoints()
        for j in range(mesh.GetNumberOfPoints()):
            current_point = mesh.GetPoint(j)
            current_normal = np.array(normals.GetTuple3(j))
            current_mean_curvature = mean_curvatures.GetValue(j)

            pt = np.array(mesh_pts.GetPoint(j))
            pt -= dt * current_mean_curvature * current_normal
            mesh_pts.SetPoint(j, pt)
        mesh_pts.Modified()
        mesh.SetPoints(mesh_pts)
        mesh.Modified()
#        if i % 100 == 0 and show_flow:
            # plotter = pyvista.Plotter()
            # plotter.add_mesh(mesh)
            # plotter.show()

        tps_deform = get_thin_plate_spline_deform(prev_mesh, mesh)

        prev_mesh = mesh
        thin_plate_spline_list.append(tps_deform)
    # new_mesh = apply_tps_on_spokes_poly(mesh, thin_plate_spline_list)
    # plotter = pyvista.Plotter()
    # plotter.add_mesh(new_mesh, color='red', opacity=0.3)
    # plotter.add_mesh(orig_mesh, color='blue', opacity=0.3)
    # plotter.show()
    return mesh, thin_plate_spline_list
Пример #33
0
        # test binary writing and reading for polygons
        binaryWriter = vtk.vtkMNIObjectWriter()
        binaryWriter.SetInputConnection(stripper.GetOutputPort())
        binaryWriter.SetFileName("mni-surface-mesh-binary.obj")
        binaryWriter.SetProperty(property0)
        binaryWriter.SetFileTypeToBinary()
        binaryWriter.Write()

        binaryReader = vtk.vtkMNIObjectReader()
        binaryReader.SetFileName("mni-surface-mesh-binary.obj")

        property2 = binaryReader.GetProperty()

        # make a polyline object with color scalars
        scalars = vtk.vtkCurvatures()
        scalars.SetInputConnection(asciiReader.GetOutputPort())

        colors = vtk.vtkLookupTable()
        colors.SetRange(-14.5104, 29.0208)
        colors.SetAlphaRange(1.0, 1.0)
        colors.SetSaturationRange(1.0, 1.0)
        colors.SetValueRange(1.0, 1.0)
        colors.SetHueRange(0.0, 1.0)
        colors.Build()

        # this is just to test using the SetMapper option of vtkMNIObjectWriter
        mapper = vtk.vtkDataSetMapper()
        mapper.SetLookupTable(colors)
        mapper.UseLookupTableScalarRangeOn()
        edges = vtk.vtkExtractEdges()
Пример #34
0
        # test binary writing and reading for polygons
        binaryWriter = vtk.vtkMNIObjectWriter()
        binaryWriter.SetInputConnection(stripper.GetOutputPort())
        binaryWriter.SetFileName("mni-surface-mesh-binary.obj")
        binaryWriter.SetProperty(property0)
        binaryWriter.SetFileTypeToBinary()
        binaryWriter.Write()

        binaryReader = vtk.vtkMNIObjectReader()
        binaryReader.SetFileName("mni-surface-mesh-binary.obj")

        property2 = binaryReader.GetProperty()

        # make a polyline object with color scalars
        scalars = vtk.vtkCurvatures()
        scalars.SetInputConnection(asciiReader.GetOutputPort())

        colors = vtk.vtkLookupTable()
        colors.SetRange(-14.5104, 29.0208)
        colors.SetAlphaRange(1.0, 1.0)
        colors.SetSaturationRange(1.0, 1.0)
        colors.SetValueRange(1.0, 1.0)
        colors.SetHueRange(0.0, 1.0)
        colors.Build()

        # this is just to test using the SetMapper option of vtkMNIObjectWriter
        mapper = vtk.vtkDataSetMapper()
        mapper.SetLookupTable(colors)
        mapper.UseLookupTableScalarRangeOn()
        edges = vtk.vtkExtractEdges()
    def MeanCurvature(self, verbose=False):
        self.gauss_mean = False
        value_list = []
        self.curvaturesFilter_mean = vtk.vtkCurvatures()
        self.curvaturesFilter_mean.SetInputConnection(
            self.normal_generator_smooth.GetOutputPort())
        self.curvaturesFilter_mean.SetCurvatureTypeToMean()
        self.curvaturesFilter_mean.Update()
        # Use a color series to create a transfer function
        scalar_range = [-0.002, 0.001]
        #self.curvaturesFilter_gauss.GetOutput().GetScalarRange(scalar_range)
        if verbose:
            print "scalar_range:  ", scalar_range
            lut = vtk.vtkColorTransferFunction()
            lut.SetColorSpaceToHSV()
            num_colors = self.color_series.GetNumberOfColors()
            d_color = [0.0, 0.0, 0.0]
            for i in range(num_colors):
                color = self.color_series.GetColor(i)
                d_color[0] = color[0] / 255.0
                d_color[1] = color[1] / 255.0
                d_color[2] = color[2] / 255.0
                t = scalar_range[0] + (scalar_range[1] -
                                       scalar_range[0]) * i / (num_colors - 1)
                lut.AddRGBPoint(t, d_color[0], d_color[1], d_color[2])
                # print t, "  :  ",d_color[0], d_color[1], d_color[2]
        ## make the value list:
        poly_data = self.curvaturesFilter_mean.GetOutput()
        self.curvature_polydata = poly_data
        cell_number = poly_data.GetNumberOfCells()
        #poly_data.GetPointData.SetActiveScalars("Mean_Curvature")
        point_data = poly_data.GetPointData()
        data_array = point_data.GetScalars()
        self.total_MC = 0  # total Gaussian curvature
        triangle = np.zeros([3, 3], dtype="f")  # variable to store triangles
        if verbose:
            print "first value: ", data_array.GetTuple1(0)
        t = float(cell_number)

        for i in range(cell_number):
            value = data_array.GetTuple1(i)
            if verbose:
                pdb.update_progress(float(i) / t)
            cell = poly_data.GetCell(i)
            for j in range(3):
                point_id = cell.GetPointId(j)
                poly_data.GetPoints().GetPoint(point_id, triangle[j])
            if abs(value) < 1.0:  # integrate only if ...
                self.total_MC = self.total_MC + (CalcArea(triangle) * value)
                value_list.append(float(value))

        if verbose:
            print "\nmax value: ", max(value_list)
            print "min value    : ", min(value_list)
            print "total Gaussian curvature: ", self.total_MC
            plt.hist(value_list, bins=100)
            plt.suptitle('Mean curvature distribution')
            plt.show()

            ##Create a mapper and actor
            mapper = vtk.vtkPolyDataMapper()
            mapper.UseLookupTableScalarRangeOn()
            mapper.SetInputConnection(
                self.curvaturesFilter_mean.GetOutputPort())
            mapper.SetLookupTable(lut)
            mapper.SetScalarRange(scalar_range)
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)

            ##Create a scalar bar actor
            scalarBar = vtk.vtkScalarBarActor()
            scalarBar.SetLookupTable(mapper.GetLookupTable())
            scalarBar.SetNumberOfLabels(5)
            ##Create text actor
            text_actor = vtk.vtkTextActor()
            text_actor.SetInput("Mean Curvature")
            text_actor.GetTextProperty().SetFontSize(20)
            text_actor.GetTextProperty().SetColor(0.5, 0.5, 0.5)
            text_actor.SetPosition(100, 16)

            self.meancurve_renderer = vtk.vtkRenderer()
            self.meancurve_renderer.SetBackground([1., 1., 1.])
            self.meancurve_renderer.AddActor(actor)
            self.meancurve_renderer.AddActor2D(scalarBar)
            self.meancurve_renderer.AddActor2D(text_actor)

        return self.total_MC
Пример #36
0
torus.SetPhiRoundness(1.0)
torus.SetThetaRoundness(1.0)
torus.SetThickness(0.5)
torus.SetSize(0.5)
torus.SetToroidal(1)
# The quadric is made of strips, so pass it through a triangle filter as
# the curvature filter only operates on polys
tri = vtk.vtkTriangleFilter()
tri.SetInputConnection(torus.GetOutputPort())
# 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
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(tri.GetOutputPort())
cleaner.SetTolerance(0.005)
curve1 = vtk.vtkCurvatures()
curve1.SetInputConnection(cleaner.GetOutputPort())
curve1.SetCurvatureTypeToGaussian()
curve2 = vtk.vtkCurvatures()
curve2.SetInputConnection(cleaner.GetOutputPort())
curve2.SetCurvatureTypeToMean()
lut1 = vtk.vtkLookupTable()
lut1.SetNumberOfColors(256)
lut1.SetHueRange(0.15,1.0)
lut1.SetSaturationRange(1.0,1.0)
lut1.SetValueRange(1.0,1.0)
lut1.SetAlphaRange(1.0,1.0)
lut1.SetRange(-20,20)
lut2 = vtk.vtkLookupTable()
lut2.SetNumberOfColors(256)
lut2.SetHueRange(0.15,1.0)
Пример #37
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        curvatureFilter = vtk.vtkCurvatures()
        curvatureFilter.SetInputData(self.Surface)
        if self.CurvatureType == 'mean':
            curvatureFilter.SetCurvatureTypeToMean()
        elif self.CurvatureType == 'gaussian':
            curvatureFilter.SetCurvatureTypeToGaussian()
        elif self.CurvatureType == 'maximum':
            curvatureFilter.SetCurvatureTypeToMaximum()
        elif self.CurvatureType == 'minimum':
            curvatureFilter.SetCurvatureTypeToMinimum()
        curvatureFilter.Update()

        activeScalars = curvatureFilter.GetOutput().GetPointData().GetScalars()
        activeScalars.SetName('Curvature')

        if self.AbsoluteCurvature:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                activeScalars.SetTuple1(i,abs(value))

        neighborhoods = None
        if not self.CurvatureOnBoundaries or self.MedianFiltering:
            neighborhoods = vtkvmtk.vtkvmtkNeighborhoods()
            neighborhoods.SetNeighborhoodTypeToPolyDataManifoldNeighborhood()
            neighborhoods.SetDataSet(self.Surface)
            neighborhoods.Build()

        if not self.CurvatureOnBoundaries:
            boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor()
            boundaryExtractor.SetInputData(self.Surface)
            boundaryExtractor.Update()
            boundaryIdsArray = vtk.vtkIdTypeArray.SafeDownCast(boundaryExtractor.GetOutput().GetPointData().GetScalars())
            boundaryIds = vtk.vtkIdList()
            boundaryIds.SetNumberOfIds(boundaryIdsArray.GetNumberOfTuples())
            for i in range(boundaryIdsArray.GetNumberOfTuples()):
                boundaryIds.SetId(i,boundaryIdsArray.GetValue(i))
            self.Surface.BuildLinks()
            for i in range(boundaryIds.GetNumberOfIds()):
                pointId = boundaryIds.GetId(i)
                neighborhood = neighborhoods.GetNeighborhood(pointId)
                values = []
                for j in range(neighborhood.GetNumberOfPoints()):
                    neighborId = neighborhood.GetPointId(j)
                    if boundaryIds.IsId(neighborId) != -1:
                        continue
                    value = activeScalars.GetTuple1(neighborId)
                    values.append(value)
                values.sort()
                if not values:
                    continue
                medianValue = values[(len(values) - 1)/2]
                activeScalars.SetTuple1(pointId,medianValue)

        if self.MedianFiltering:
            for i in range(neighborhoods.GetNumberOfNeighborhoods()):
                neighborhood = neighborhoods.GetNeighborhood(i)
                values = []
                for j in range(neighborhood.GetNumberOfPoints()):
                    neighborId = neighborhood.GetPointId(j)
                    value = activeScalars.GetTuple1(neighborId)
                    values.append(value)
                values.sort()
                if not values:
                    continue
                medianValue = values[(len(values) - 1)/2]
                activeScalars.SetTuple1(i,medianValue)

        if self.BoundedReciprocal:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                reciprocalValue = 1.0 / (self.Epsilon + value)
                activeScalars.SetTuple1(i,reciprocalValue)

        if self.Offset:
            for i in range(activeScalars.GetNumberOfTuples()):
                value = activeScalars.GetTuple1(i)
                activeScalars.SetTuple1(i,value + self.Offset)

        if self.ReferenceSurface == None:
            self.Surface.GetPointData().AddArray(activeScalars)
        else:
            self.ReferenceSurface.GetPointData().AddArray(activeScalars)
            self.Surface = self.ReferenceSurface
Пример #38
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        # Create source
        # We are going to handle two different sources.
        # The first source is a superquadric source.
        torus = vtk.vtkSuperquadricSource();
        torus.SetCenter(0.0, 0.0, 0.0)
        torus.SetScale(1.0, 1.0, 1.0)
        torus.SetPhiResolution (64)
        torus.SetThetaResolution(64)
        torus.SetThetaRoundness (1)
        torus.SetThickness (0.5)
        torus.SetSize(0.5)
        torus.SetToroidal(1) 
 
        # Rotate the torus towards the observer (around the x-axis)
        torusT = vtk.vtkTransform()
        torusT.RotateX(55)
 
        torusTF = vtk.vtkTransformFilter()
        torusTF.SetInputConnection(torus.GetOutputPort())
        torusTF.SetTransform(torusT)
 
        # The quadric is made of strips, so pass it through a triangle filter as
        # the curvature filter only operates on polys
        tri = vtk.vtkTriangleFilter()
        tri.SetInputConnection(torusTF.GetOutputPort())
 
        # 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
 
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputConnection(tri.GetOutputPort())
        cleaner.SetTolerance(0.005)
 
        # The next source will be a parametric function
        rh = vtk.vtkParametricRandomHills()
        rhFnSrc = vtk.vtkParametricFunctionSource()
        rhFnSrc.SetParametricFunction(rh)
 
        # Now we have the sources, lets put them into a list.
        sources = list()
        sources.append(cleaner)
        sources.append(cleaner)
        sources.append(rhFnSrc)
        sources.append(rhFnSrc)
 
        # Colour transfer function.
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754)
        ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150)
        cc = list()
        for i in range(256):
            cc.append(ctf.GetColor(float(i) / 255.0)) 
 
        # Lookup table.
        lut = list()
        for idx in range(len(sources)):
            lut.append(vtk.vtkLookupTable())
            lut[idx].SetNumberOfColors(256)
            for i, item in enumerate(cc):
                lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0)
            if idx == 0:
                lut[idx].SetRange(-10, 10)
            if idx == 1:
                lut[idx].SetRange(0, 4)
            if idx == 2:
                lut[idx].SetRange(-1, 1)
            if idx == 3:
                lut[idx].SetRange(-1, 1)
            lut[idx].Build()
 
        curvatures = list()        
        for idx in range(len(sources)):
            curvatures.append(vtk.vtkCurvatures())
            if idx % 2 == 0:
                curvatures[idx].SetCurvatureTypeToGaussian()
            else:
                curvatures[idx].SetCurvatureTypeToMean()
 
        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()
 
        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()
 
        names = ['Torus - Gaussian Curvature', 'Torus - Mean Curvature', 'Random Hills - Gaussian Curvature', 'Random Hills - Mean Curvature']
 
        # Link the pipeline together. 
        for idx, item in enumerate(sources):
            sources[idx].Update()
 
            curvatures[idx].SetInputConnection(sources[idx].GetOutputPort())
 
            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort())
            mappers[idx].SetLookupTable(lut[idx])
            mappers[idx].SetUseLookupTableScalarRange(1)
 
            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])
 
            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(names[idx])
            textmappers[idx].SetTextProperty(textProperty)
 
            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)
 
            renderers.append(vtk.vtkRenderer())
 
        gridDimensions = 2
 
        for idx in range(len(sources)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer)
 
        rendererSize = 300
 
        # Create the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)
 
        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col
 
                viewport[:] = []
                viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize))
                viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize))
 
                if idx > (len(sources) - 1):
                    continue
 
                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])
 
                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4,0.3,0.2)
        
        self._initialized = False
Пример #39
0
torus.SetPhiRoundness(1.0)
torus.SetThetaRoundness(1.0)
torus.SetThickness(0.5)
torus.SetSize(0.5)
torus.SetToroidal(1)
# The quadric is made of strips, so pass it through a triangle filter as
# the curvature filter only operates on polys
tri = vtk.vtkTriangleFilter()
tri.SetInputConnection(torus.GetOutputPort())
# 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
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(tri.GetOutputPort())
cleaner.SetTolerance(0.005)
curve1 = vtk.vtkCurvatures()
curve1.SetInputConnection(cleaner.GetOutputPort())
curve1.SetCurvatureTypeToGaussian()
curve2 = vtk.vtkCurvatures()
curve2.SetInputConnection(cleaner.GetOutputPort())
curve2.SetCurvatureTypeToMean()
lut1 = vtk.vtkLookupTable()
lut1.SetNumberOfColors(256)
lut1.SetHueRange(0.15, 1.0)
lut1.SetSaturationRange(1.0, 1.0)
lut1.SetValueRange(1.0, 1.0)
lut1.SetAlphaRange(1.0, 1.0)
lut1.SetRange(-20, 20)
lut2 = vtk.vtkLookupTable()
lut2.SetNumberOfColors(256)
lut2.SetHueRange(0.15, 1.0)
Пример #40
0
    model_avg_cur_m = np.zeros(1)
    model_avg_cur_m_std = np.zeros(1)
    for bound in range(1, lith, 1):
        #contacts = vtk.vtkDiscreteMarchingCubes()
        #contacts.SetInputData(input)
        contacts = vtk.vtkMarchingCubes()
        contacts.SetInputData(input)
        true_bound = bound+0.5
        contacts.SetValue(0,true_bound)
        contacts.Update()

        surface_area = vtk.vtkMassProperties()
        surface_area.SetInputConnection(contacts.GetOutputPort())
        surface_area.Update()

        curvature = vtk.vtkCurvatures()
        curvature.SetInputConnection(contacts.GetOutputPort())
        curvature.SetCurvatureTypeToMinimum()
        #curvature.SetCurvatureTypeToMaximum()
        #curvature.SetCurvatureTypeToGaussian()
        #curvature.SetCurvatureTypeToMean()
        curvature.Update()
        gauss = np.frombuffer(curvature.GetOutput().GetPointData().GetArray("Gauss_Curvature"), dtype = float)
        mean = np.frombuffer(curvature.GetOutput().GetPointData().GetArray("Mean_Curvature"), dtype = float)
        if (true_bound ==1.5):
            model_area[0] = surface_area.GetSurfaceArea()
            model_sum_cur_g[0] = np.sum(gauss)
            model_sum_cur_m[0] = np.sum(mean)
            model_sum_cur_g_std[0] = np.std(gauss)
            model_sum_cur_m_std[0] = np.std(mean)
            model_avg_cur_g[0] = np.mean(gauss)
Пример #41
0
def main(filename, curvature=0, scalarRange=None, scheme=None):
    print("Loading", filename)
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(filename)

    curvaturesFilter = vtk.vtkCurvatures()
    curvaturesFilter.SetInputConnection(reader.GetOutputPort())
    if curvature == 0:
        curvaturesFilter.SetCurvatureTypeToMinimum()
    elif curvature == 1:
        curvaturesFilter.SetCurvatureTypeToMaximum()
    elif curvature == 2:
        curvaturesFilter.SetCurvatureTypeToGaussian()
    else:
        curvaturesFilter.SetCurvatureTypeToMean()
    curvaturesFilter.Update()

    # Get scalar range from command line if present, otherwise use
    # range of computed curvature
    if scalarRange is None:
        scalarRange = curvaturesFilter.GetOutput().GetScalarRange()

    # Build a lookup table
    if scheme is None:
        scheme = 16
    colorSeries = vtk.vtkColorSeries()
    colorSeries.SetColorScheme(scheme)
    print("Using color scheme #:", colorSeries.GetColorScheme(), \
        "is", colorSeries.GetColorSchemeName())

    lut = vtk.vtkColorTransferFunction()
    lut.SetColorSpaceToHSV()

    # Use a color series to create a transfer function
    numColors = colorSeries.GetNumberOfColors()
    for i in range(numColors):
        color = colorSeries.GetColor(i)
        dColor = [color[0] / 255.0, color[1] / 255.0, color[2] / 255.0]
        t = scalarRange[0] + (scalarRange[1] - scalarRange[0]) / (numColors -
                                                                  1) * i
        lut.AddRGBPoint(t, dColor[0], dColor[1], dColor[2])

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(curvaturesFilter.GetOutputPort())
    mapper.SetLookupTable(lut)
    mapper.SetScalarRange(scalarRange)

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

    # Create a scalar bar
    print("Displaying",
          curvaturesFilter.GetOutput().GetPointData().GetScalars().GetName())
    scalarBarActor = vtk.vtkScalarBarActor()
    scalarBarActor.SetLookupTable(mapper.GetLookupTable())
    scalarBarActor.SetTitle(
        curvaturesFilter.GetOutput().GetPointData().GetScalars().GetName())

    scalarBarActor.SetNumberOfLabels(5)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actors to the scene
    renderer.AddActor(actor)
    renderer.AddActor2D(scalarBarActor)

    renderer.SetBackground(.1, .2, .3)  # Background color blue

    # Render and interact
    renderWindow.Render()
    renderWindowInteractor.Start()