Esempio n. 1
2
def Create_Topo(Slope,Plane):
	ugrid = vtk.vtkUnstructuredGrid()
	gridreader=vtk.vtkUnstructuredGridReader()
	gridreader.SetFileName(Slope)
	gridreader.Update()
	ugrid = gridreader.GetOutput()
	GeomFilt1 = vtk.vtkGeometryFilter()
	GeomFilt1.SetInput(ugrid)
	GeomFilt1.Update()
	x = GeomFilt1.GetOutput()

	u = vtk.vtkUnstructuredGrid()
	bgridreader=vtk.vtkXMLUnstructuredGridReader()
	bgridreader.SetFileName(Plane)
	bgridreader.Update()
	u = bgridreader.GetOutput() 
	GeomFilt2 = vtk.vtkGeometryFilter()
	GeomFilt2.SetInput(u)
	GeomFilt2.Update()
	y = GeomFilt2.GetOutput()

	append = vtk.vtkAppendPolyData()
	append.AddInput(x)
	append.AddInput(y)
	data = append.GetOutput()

	d = vtk.vtkDelaunay3D()
	d.SetInput(data)
	d.Update
	d.BoundingTriangulationOff()  
	d.SetTolerance(0.00001)
	d.SetAlpha(0)
	d.Update()
	z = d.GetOutput()
	return z
Esempio n. 2
0
def main():
    colors = vtk.vtkNamedColors()

    sphereSource1 = vtk.vtkSphereSource()
    sphereSource1.Update()

    delaunay1 = vtk.vtkDelaunay3D()
    delaunay1.SetInputConnection(sphereSource1.GetOutputPort())
    delaunay1.Update()

    sphereSource2 = vtk.vtkSphereSource()
    sphereSource2.SetCenter(5, 0, 0)
    sphereSource2.Update()

    delaunay2 = vtk.vtkDelaunay3D()
    delaunay2.SetInputConnection(sphereSource2.GetOutputPort())
    delaunay2.Update()

    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputConnection(delaunay1.GetOutputPort())
    appendFilter.AddInputConnection(delaunay2.GetOutputPort())
    appendFilter.Update()

    connectivityFilter = vtk.vtkConnectivityFilter()
    connectivityFilter.SetInputConnection(appendFilter.GetOutputPort())
    connectivityFilter.SetExtractionModeToAllRegions()
    connectivityFilter.ColorRegionsOn()
    connectivityFilter.Update()

    # Visualize
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(connectivityFilter.GetOutputPort())
    mapper.Update()

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

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)

    # renWindow = vtk.vtkRenderWindow()
    # renWindow.AddRenderer(renderer)
    # iren = vtk.vtkRenderWindowInteractor()
    # iren.SetRenderWindow(renWindow)
    # iren.Initialize()
    # iren.Start()
    renWindow = vtk.vtkRenderWindow()
    renWindow.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWindow)

    iren.Initialize()
    renWindow.Render()
    renWindow.SetWindowName('ConnectivityFilter')
    renderer.SetBackground(colors.GetColor3d('deep_ochre'))
    renderer.GetActiveCamera().Zoom(0.9)
    renWindow.Render()
    iren.Start()
    def GridSurface(self):
        #----------------------------------------------------------------------
        # ELECTRODE CONTACT DELAUNAY TRIANGULATION ----------------------------
        deln = vtk.vtkDelaunay3D()
        deln.SetInput(self.electrodePolyData)
        deln.SetTolerance(0.01)
        tmapper = vtk.vtkTextureMapToSphere()
        tmapper.SetInputConnection(deln.GetOutputPort())
        #tmapper.PreventSeamOn()
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(tmapper.GetOutputPort())

        # TEST TEXTURE PART
        atext = vtk.vtkOpenGLTexture()

        self.contactScalarData = vtk.vtkDoubleArray()
        self.contactScalarData.SetNumberOfComponents(1)
        for tupleID in range(self.electrodePolyData.GetNumberOfPoints()):
            self.contactScalarData.InsertNextValue(random.uniform(0, 1))

        self.UpdateGridSurface()
        atext.SetInput(self.electrodePolyData)
        self.triangulation = vtk.vtkOpenGLActor()
        self.triangulation.SetMapper(mapper)
        self.triangulation.SetTexture(atext)
        self.triangulation.GetProperty().SetOpacity(1)
Esempio n. 4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkDelaunay3D(), 'Processing.',
         ('vtkPointSet',), ('vtkUnstructuredGrid',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Esempio n. 5
0
def sphere(resolution=3, size=1):
    grid = vtk.vtkAppendPolyData()

    # add the center to the mesh
    center = vtk.vtkPolyData()
    center.SetPoints(vtk.vtkPoints())
    center.GetPoints().InsertNextPoint(0, 0, 0)

    grid.AddInput(center)

    # add spheres of increasing complexity
    subdivisions = 0
    radius = 0
    for i in range(resolution - 1):
        radius += float(size) / float(resolution - 1)

        sphere = nice_sphere(radius / 2.0, subdivisions)
        grid.AddInput(sphere)

        subdivisions += 1

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(grid.GetOutput())

    mesh = vtk.vtkDelaunay3D()
    mesh.SetInput(cleaner.GetOutput())

    return mesh
Esempio n. 6
0
    def delaunay_3d(dataset, alpha=0, tol=0.001, offset=2.5):
        """Constructs a 3D Delaunay triangulation of the mesh.
        This helps smooth out a rugged mesh.

        Parameters
        ----------
        alpha : float, optional
            Distance value to control output of this filter. For a non-zero
            alpha value, only verts, edges, faces, or tetra contained within
            the circumsphere (of radius alpha) will be output. Otherwise, only
            tetrahedra will be output.

        tol : float, optional
            tolerance to control discarding of closely spaced points.
            This tolerance is specified as a fraction of the diagonal length
            of the bounding box of the points.

        offset : float, optional
            multiplier to control the size of the initial, bounding Delaunay
            triangulation.
        """
        alg = vtk.vtkDelaunay3D()
        alg.SetInputData(dataset)
        alg.SetAlpha(alpha)
        alg.SetTolerance(tol)
        alg.SetOffset(offset)
        alg.Update()
        return _get_output(alg)
Esempio n. 7
0
    def GridSurface(self):
        #----------------------------------------------------------------------
        # ELECTRODE CONTACT DELAUNAY TRIANGULATION ----------------------------
        deln = vtk.vtkDelaunay3D()
        deln.SetInput(self.electrodePolyData)
        deln.SetTolerance(0.01)
        tmapper = vtk.vtkTextureMapToSphere()
        tmapper.SetInputConnection(deln.GetOutputPort())
        #tmapper.PreventSeamOn()
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(tmapper.GetOutputPort())

        # TEST TEXTURE PART
        atext = vtk.vtkOpenGLTexture()

        self.contactScalarData = vtk.vtkDoubleArray()
        self.contactScalarData.SetNumberOfComponents(1)
        for tupleID in range(self.electrodePolyData.GetNumberOfPoints()):
            self.contactScalarData.InsertNextValue(random.uniform(0, 1))

        self.UpdateGridSurface()
        atext.SetInput(self.electrodePolyData)
        self.triangulation = vtk.vtkOpenGLActor()
        self.triangulation.SetMapper(mapper)
        self.triangulation.SetTexture(atext)
        self.triangulation.GetProperty().SetOpacity(1)
Esempio n. 8
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()
Esempio n. 9
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()
Esempio n. 10
0
def main():
    sphereSource1 = vtk.vtkSphereSource()
    sphereSource1.Update()

    delaunay1 = vtk.vtkDelaunay3D()
    delaunay1.SetInputConnection(sphereSource1.GetOutputPort())
    delaunay1.Update()

    sphereSource2 = vtk.vtkSphereSource()
    sphereSource2.SetCenter(5, 0, 0)
    sphereSource2.Update()

    delaunay2 = vtk.vtkDelaunay3D()
    delaunay2.SetInputConnection(sphereSource2.GetOutputPort())
    delaunay2.Update()

    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputConnection(delaunay1.GetOutputPort())
    appendFilter.AddInputConnection(delaunay2.GetOutputPort())
    appendFilter.Update()

    connectivityFilter = vtk.vtkConnectivityFilter()
    connectivityFilter.SetInputConnection(appendFilter.GetOutputPort())
    connectivityFilter.SetExtractionModeToAllRegions()
    connectivityFilter.ColorRegionsOn()
    connectivityFilter.Update()

    # Visualize
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(connectivityFilter.GetOutputPort())
    mapper.Update()

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

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)

    renWindow = vtk.vtkRenderWindow()
    renWindow.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWindow)
    iren.Initialize()
    iren.Start()
Esempio n. 11
0
    def test_vtk_shananigans(self):
        sphere = vtk.vtkPointSource()
        sphere.SetNumberOfPoints(25)
        mesh = Mesh("data/wing_off_files/synth_wing_v3.off")
        # Triangulate the points with vtkDelaunay3D. This generates a convex hull
        # of tetrahedron.
        delny = vtk.vtkDelaunay3D()
        delny.SetInputConnection(sphere.GetOutputPort())
        delny.SetTolerance(0.01)
        print(dir(mesh.pv_mesh))
        # The triangulation has texture coordinates generated so we can map
        # a texture onto it.
        tmapper = vtk.vtkTextureMapToCylinder()
        tmapper.SetInputDataObject(mesh.pv_mesh.GetPointData().GetOutputPort())
        tmapper.PreventSeamOn()

        # We scale the texture coordinate to get some repeat patterns.
        xform = vtk.vtkTransformTextureCoords()
        xform.SetInputConnection(tmapper.GetOutputPort())
        xform.SetScale(4, 4, 1)

        # vtkDataSetMapper internally uses a vtkGeometryFilter to extract the
        # surface from the triangulation. The output (which is vtkPolyData) is
        # then passed to an internal vtkPolyDataMapper which does the
        # rendering.
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(xform.GetOutputPort())

        # A texture is loaded using an image reader. Textures are simply images.
        # The texture is eventually associated with an actor.
        bmpReader = vtk.vtkPNGReader()
        bmpReader.SetFileName("data/textures/checkers.png")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(bmpReader.GetOutputPort())
        atext.InterpolateOn()
        triangulation = vtk.vtkActor()
        triangulation.SetMapper(mapper)
        triangulation.SetTexture(atext)

        # Create the standard rendering stuff.
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Add the actors to the renderer, set the background and size
        ren.AddActor(triangulation)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)

        iren.Initialize()
        renWin.Render()
        iren.Start()
    def _readstls(self):
        for fname in sorted(os.listdir(self._ref_dir)):
            if '.stl' in fname.lower():
                reader = vtk.vtkSTLReader()
                reader.SetFileName(self._ref_dir + '/' + fname)
                reader.Update()
                triangles = vtk.vtkTriangleFilter()
                triangles.SetInputConnection(reader.GetOutputPort())
                triangles.Update()
                self.rsurfs.append(triangles.GetOutput())

                dl = vtk.vtkDelaunay3D()
                dl.SetInputConnection(triangles.GetOutputPort())
                dl.Update()
                self.rmeshes.append(dl)

                vol, cent, axes = self._getMassProps(self.rmeshes[-1])
                self.rvols.append(vol)
                self.rcentroids.append(cent)
                self.raxes.append(axes)

        for fname in sorted(os.listdir(self._def_dir)):
            if '.stl' in fname.lower():
                reader = vtk.vtkSTLReader()
                reader.SetFileName(self._def_dir + '/' + fname)
                reader.Update()
                triangles = vtk.vtkTriangleFilter()
                triangles.SetInputConnection(reader.GetOutputPort())
                triangles.Update()
                self.dsurfs.append(triangles.GetOutput())

                dl = vtk.vtkDelaunay3D()
                dl.SetInputConnection(triangles.GetOutputPort())
                dl.Update()
                self.dmeshes.append(dl)

                vol, cent, axes = self._getMassProps(self.dmeshes[-1])
                self.dvols.append(vol)
                self.dcentroids.append(cent)
                self.daxes.append(axes)
Esempio n. 13
0
    def _readstls(self):
        for fname in sorted(os.listdir(self._ref_dir)):
            if '.stl' in fname.lower():
                reader = vtk.vtkSTLReader()
                reader.SetFileName(self._ref_dir+'/'+fname)
                reader.Update()
                triangles = vtk.vtkTriangleFilter()
                triangles.SetInputConnection(reader.GetOutputPort())
                triangles.Update()
                self.rsurfs.append(triangles.GetOutput())

                dl = vtk.vtkDelaunay3D()
                dl.SetInputConnection(triangles.GetOutputPort())
                dl.Update()
                self.rmeshes.append(dl)

                vol, cent, axes = self._getMassProps(self.rmeshes[-1])
                self.rvols.append(vol)
                self.rcentroids.append(cent)
                self.raxes.append(axes)

        for fname in sorted(os.listdir(self._def_dir)):
            if '.stl' in fname.lower():
                reader = vtk.vtkSTLReader()
                reader.SetFileName(self._def_dir+'/'+fname)
                reader.Update()
                triangles = vtk.vtkTriangleFilter()
                triangles.SetInputConnection(reader.GetOutputPort())
                triangles.Update()
                self.dsurfs.append(triangles.GetOutput())

                dl = vtk.vtkDelaunay3D()
                dl.SetInputConnection(triangles.GetOutputPort())
                dl.Update()
                self.dmeshes.append(dl)

                vol, cent, axes = self._getMassProps(self.dmeshes[-1])
                self.dvols.append(vol)
                self.dcentroids.append(cent)
                self.daxes.append(axes)
Esempio n. 14
0
    def __init__(self):
        """
        Constructor
        """
        self.points = vtk.vtkPoints()
        self.polydata = vtk.vtkPolyData()
        self.delny = vtk.vtkDelaunay3D()

        self.polydata.SetPoints(self.points)
        if vtk.VTK_MAJOR_VERSION >= 6:
            self.delny.SetInputData(self.polydata)
        else:
            self.delny.SetInput(self.polydata)
Esempio n. 15
0
 def __init__(self, scene, V, opacity=1, color='gray'):
     self.scene = scene
     self.frame = scene.frame
     delaunay = vtk.vtkDelaunay3D()
     delaunay.SetInput(self.scene.get_active_point_cloud().polydata)
     delaunay.SetAlpha(V.bin_size)
     mapper = vtk.vtkDataSetMapper()
     mapper.SetInput(delaunay.GetOutput())
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(mapper)
     self.actor.GetProperty().SetColor(*name_to_rgb_float(color))
     self.actor.GetProperty().SetOpacity(opacity)
     self.frame.ren.AddActor(self.actor)
Esempio n. 16
0
    def update(self):
        delaunay = vtkDelaunay3D()
        delaunay.SetInputData(self.input_)
        delaunay.SetTolerance(self.tolerance)
        delaunay.SetAlpha(self.alpha)
        delaunay.Update()

        geom = vtkGeometryFilter()
        geom.SetInputConnection(delaunay.GetOutputPort())

        triangle = vtkTriangleFilter()
        triangle.SetInputConnection(geom.GetOutputPort())
        triangle.Update()
        self.output_ = triangle.GetOutput()
Esempio n. 17
0
    def update(self):
        delaunay = vtkDelaunay3D()
        delaunay.SetInput(self.input_)
        delaunay.SetTolerance(self.tolerance)
        delaunay.SetAlpha(self.alpha)
        delaunay.Update()

        geom = vtkGeometryFilter()
        geom.SetInputConnection(delaunay.GetOutputPort() )

        triangle = vtkTriangleFilter()
        triangle.SetInputConnection(geom.GetOutputPort())
        triangle.Update()
        self.output_ = triangle.GetOutput()
Esempio n. 18
0
    def delaunay_triangulate_polydata(self, polydata, tol=1, alpha=50):
        '''
		class method to triangulate points
		polydata=vtk polydata object loaded with point cloud
		tol=integer indicating mesh quality tolerance
		alpha=integer/float indicating the maximum connection distance in the triangulation
		returns:vtk 3d tetrahedralization
		'''
        delny = vtk.vtkDelaunay3D()
        delny.SetInputData(polydata)
        delny.SetTolerance(tol)
        delny.SetAlpha(alpha)
        delny.BoundingTriangulationOff()
        return (delny)
Esempio n. 19
0
 def delaunay3D(self):
     delny = vtk.vtkDelaunay3D()
     delny.SetInputData(self.vtkPolyData)
     delny.SetTolerance(0.01)
     delny.SetAlpha(0.2)
     delny.BoundingTriangulationOff()
     #shrink = vtk.vtkShrinkFilter()
     #shrink.SetInputConnection(delny.GetOutputPort())
     #shrink.SetShrinkFactor(0.9)
     mapper = vtk.vtkDataSetMapper()
     mapper.SetInputConnection(delny.GetOutputPort())
     triangulation = vtk.vtkActor()
     triangulation.SetMapper(mapper)
     triangulation.GetProperty().SetColor(1, 0, 0)
     return triangulation
Esempio n. 20
0
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a boolean polydata filter to calculate the intersection,
    a general implementation but slow.

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    baseVol = vtkTools.polydata.calculateVolume(baseC)
    # print iV, baseVol
    # Extract cells from the first mesh that intersect the base cell
    extractCells = vtkTools.extraction.extractDataSetWithPolygon(vtkDataSet1,baseC,extInside=True,extBoundaryCells=True,extractBounds=True)
    extInd = npsup.vtk_to_numpy(extractCells.GetCellData().GetArray('id'))
    # print extInd
    # Assert if there are no cells cutv
    assert extractCells.GetNumberOfCells() > 0, 'No cells in the clip, cell id {:d}'.format(iV)
    # Calculate the volumes of the clipped cells and insert to the matrix
    volL = []
    for nrCC,iR in enumerate(extInd):
        tempCell = vtkTools.dataset.thresholdCellId2vtp(extractCells,iR)
        # Find the intersection of the 2 cells
        boolFilt = vtk.vtkBooleanOperationPolyDataFilter()
        boolFilt.SetInputData(0,tempCell)
        boolFilt.SetInputData(1,baseC)
        boolFilt.SetOperationToIntersection()
        # If they intersect, calculate the volumes
        if boolFilt.GetOutput().GetNumberOfPoints() > 0:
            cleanInt = vtkTools.polydata.cleanPolyData(boolFilt.GetOutputPort())
            del3dFilt = vtk.vtkDelaunay3D()
            del3dFilt.SetInputData(cleanInt)
            del3dFilt.Update()
            # Get the output
            intC = vtkTools.extraction.vtu2vtp(del3dFilt.GetOutput())
            intVol = vtkTools.polydata.calculateVolume(tempCell)
            # Calculate the volume
            volVal = intVol/baseVol
            # print iR, intVol, volVal
            # Insert the value
            if volVal > 0.0:
                volL.append(volVal)
    return extInd,np.array(volL)
    def SurfaceExtractDelaunay3D(self):
        """[under construction] The same functionality as self.InitMarchingCubes() which is extraction of the surface given the points representing
        atoms. this uses vtkDelaunay3D to form set of tetrahedrons (vtkUnstructuredGrid) and then using vtkGeometryFilter 
        to find the surface mesh as vtkPolyData. TODO
        """

        points_vtkPolyData = vtk.vtkPolyData()
        points_vtkPolyData.SetPoints(self.points)

        delaunay3D = vtk.vtkDelaunay3D()
        delaunay3D.SetInputData(points_vtkPolyData)
        delaunay3D.SetAlpha(5)

        geometry_filter = vtk.vtkGeometryFilter()
        geometry_filter.SetInputConnection(delaunay3D.GetOutputPort())
        ShowVtkAlgorithm(geometry_filter)
Esempio n. 22
0
def applyDelaunay3D(mat, alpha):
	points = vtk.vtkPoints()
	i = 0
	for x, y ,z in mat:
		points.InsertPoint(i, x, y ,z)
		i+=1
	profile = vtk.vtkPolyData()
	profile.SetPoints(points)
	delny = vtk.vtkDelaunay3D()
	delny.SetInputData(profile)
	delny.SetAlpha(alpha)
	delny.Update()
	geom = vtk.vtkGeometryFilter()
	geom.SetInputData(delny.GetOutput())
	geom.Update()
	return geom
Esempio n. 23
0
def create_actor_delaunay(pts, color, **kwargs):
    """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation.

    Keyword Arguments:
        * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False*

    :param pts: points
    :type pts: vtkFloatArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    use_delaunay3d = kwargs.get("d3d", False)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Create a PolyData object and add points
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Apply Delaunay triangulation on the poly data object
    triangulation = vtk.vtkDelaunay3D(
    ) if use_delaunay3d else vtk.vtkDelaunay2D()
    triangulation.SetInputData(polydata)

    # Map triangulated surface to the graphics primitives
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(triangulation.GetOutputPort())
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)

    # Return the actor
    return actor
Esempio n. 24
0
def cylinder(resolution=4, size=1, ratio=0.3):
    if resolution < 2:
        resolution = 2

    resolution *= 2

    grid = vtk.vtkAppendPolyData()

    # how to make facy cake:
    # add layers of pies... :-)
    height = float(size) / (resolution * 2 - 1)
    for l in range(resolution):
        # insert centers
        pts = vtk.vtkPoints()
        pts.InsertNextPoint(
            0, height * float((l - (resolution * 2 - 1) / 2) * 2 + 1.5), 0)
        pts.InsertNextPoint(
            0, height * float((l - (resolution * 2 - 1) / 2) * 2 + .5), 0)

        pol = vtk.vtkPolyData()
        pol.SetPoints(pts)

        grid.AddInput(pol)

        sides = 6
        for r in range(resolution / 2 - 1):
            pie = vtk.vtkCylinderSource()
            pie.SetHeight(height)
            pie.SetRadius(
                float(r + 1) * float(size) / 2.0 * float(ratio) /
                float(resolution / 2 - 1))
            pie.SetCenter(
                0, height * float((l - (resolution * 2 - 1) / 2) * 2 + 1), 0)
            pie.SetResolution(sides)

            grid.AddInput(pie.GetOutput())

            sides *= 2

    mesh = vtk.vtkDelaunay3D()
    mesh.SetInput(grid.GetOutput())

    return mesh
Esempio n. 25
0
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a boolean polydata filter to calculate the intersection,
    a general implementation but slow.

    """
    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    baseVol = vtkTools.polydata.calculateVolume(baseC)
    # print iV, baseVol
    # Extract cells from the first mesh that intersect the base cell
    extractCells = vtkTools.extraction.extractDataSetWithPolygon(vtkDataSet1,baseC,extInside=True,extBoundaryCells=True,extractBounds=True)
    extInd = npsup.vtk_to_numpy(extractCells.GetCellData().GetArray('id'))
    # print extInd
    # Assert if there are no cells cutv
    assert extractCells.GetNumberOfCells() > 0, 'No cells in the clip, cell id {:d}'.format(iV)
    # Calculate the volumes of the clipped cells and insert to the matrix
    volL = []
    for nrCC,iR in enumerate(extInd):
        tempCell = vtkTools.dataset.thresholdCellId2vtp(extractCells,iR)
        # Find the intersection of the 2 cells
        boolFilt = vtk.vtkBooleanOperationPolyDataFilter()
        boolFilt.SetInputData(0,tempCell)
        boolFilt.SetInputData(1,baseC)
        boolFilt.SetOperationToIntersection()
        # If they intersect, calculate the volumes
        if boolFilt.GetOutput().GetNumberOfPoints() > 0:
            cleanInt = vtkTools.polydata.cleanPolyData(boolFilt.GetOutputPort())
            del3dFilt = vtk.vtkDelaunay3D()
            del3dFilt.SetInputData(cleanInt)
            del3dFilt.Update()
            # Get the output
            intC = vtkTools.extraction.vtu2vtp(del3dFilt.GetOutput())
            intVol = vtkTools.polydata.calculateVolume(tempCell)
            # Calculate the volume
            volVal = intVol/baseVol
            # print iR, intVol, volVal
            # Insert the value
            if volVal > 0.0:
                volL.append(volVal)
    return extInd,np.array(volL)
Esempio n. 26
0
def create_actor_delaunay(pts, color, **kwargs):
    """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation.

    Keyword Arguments:
        * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False*

    :param pts: points
    :type pts: vtkFloatArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    use_delaunay3d = kwargs.get("d3d", False)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Create a PolyData object and add points
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Apply Delaunay triangulation on the poly data object
    triangulation = vtk.vtkDelaunay3D() if use_delaunay3d else vtk.vtkDelaunay2D()
    triangulation.SetInputData(polydata)

    # Map triangulated surface to the graphics primitives
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(triangulation.GetOutputPort())
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)

    # Return the actor
    return actor
Esempio n. 27
0
def triangulate(pd):
    """
    Generates a triangle mesh for a spherical point cloud. It is assumed that
    'pd' is an object of dsa.PolyData type.
    """
    # Project on a sphere
    sphereXyz = alg.norm(pd.Points) * np.linalg.norm(pd.Points, axis=1).mean()
    sphereXyz = np.around(sphereXyz, decimals=2)
    sphereArr = dsa.numpyTovtkDataArray(sphereXyz, name='SpherePts')
    pts = v.vtkPoints()
    pts.SetData(sphereArr)
    sphere = v.vtkPolyData()
    sphere.SetPoints(pts)

    # Store the original point ids
    idf = v.vtkIdFilter()
    idf.SetIdsArrayName('PointIds')
    idf.PointIdsOn()
    idf.SetInputData(sphere)

    # Delaunay3D to make a convex hull
    d3d = v.vtkDelaunay3D()
    d3d.SetInputConnection(idf.GetOutputPort())

    # Extract the surface
    surf = v.vtkDataSetSurfaceFilter()
    surf.SetInputConnection(d3d.GetOutputPort())
    surf.Update()

    # Now make a new cell array mapping to the old ids
    polyCells = v.vtkCellArray()
    sphereCells = surf.GetOutput().GetPolys()
    sphereCells.InitTraversal()
    origIds = surf.GetOutput().GetPointData().GetArray('PointIds')
    ptIds = v.vtkIdList()
    while (sphereCells.GetNextCell(ptIds)):
        polyCells.InsertNextCell(3)
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(0))))
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(1))))
        polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(2))))

    return polyCells
Esempio n. 28
0
    def convert__pointData2vtu( self, tag=None ):

        # ------------------------------------------------- #
        # --- [1] Arguments Check                       --- #
        # ------------------------------------------------- #
        if ( tag is None ): sys.exit( "[convert__pointData2vtu -@vtkDataManager-] tag == ???" )
        if ( self.Data[tag].fieldData is None ):
            self.Data[tag].generate__fieldData()
        if ( self.Data[tag].coordinateData is None ):
            self.Data[tag].generate__coordinateData()
        # ------------------------------------------------- #
        # --- [2] Coordinates Points Settings           --- #
        # ------------------------------------------------- #
        coordinates_ = vtknp.numpy_to_vtk( self.Data[tag].coordinateData, deep=True )
        points       = vtk.vtkPoints()
        points.SetData( coordinates_ )
        self.uGrid.SetPoints( points )
        # ------------------------------------------------- #
        # --- [3] store points & pointData              --- #
        # ------------------------------------------------- #
        for ik in range( self.Data[tag].nFields ):
            pointData_   = vtknp.numpy_to_vtk( self.Data[tag].fieldData[:,ik], deep=True )
            pointData_.SetName( self.Data[tag].fieldLabel[ik] )
            self.uGrid.GetPointData().AddArray( pointData_ )
        # ------------------------------------------------- #
        # --- [4] Delaunay triangulation                --- #
        # ------------------------------------------------- #
        delaunay = vtk.vtkDelaunay3D()
        delaunay.SetInputData( self.uGrid )
        delaunay.Update()
        # ------------------------------------------------- #
        # --- [5] save in vtu File                      --- #
        # ------------------------------------------------- #
        writer = vtk.vtkXMLUnstructuredGridWriter()
        if ( self.DataFormat.lower() == "ascii"  ):
            writer.SetDataModeToAscii()
        if ( self.DataFormat.lower() == "binary" ):
            writer.SetDataModeToBinary()
        writer.SetFileName( self.vtkFile )
        writer.SetInputData( delaunay.GetOutput() )
        writer.Write()
        print( "[vtkDataConverter] output :: {0} ".format( self.vtkFile ) )
Esempio n. 29
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)
Esempio n. 30
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)
Esempio n. 31
0
def delaunay3D(mesh, alphaPar=0, tol=None, boundary=False):
    """Create 3D Delaunay triangulation of input points."""
    deln = vtk.vtkDelaunay3D()
    if utils.isSequence(mesh):
        pd = vtk.vtkPolyData()
        vpts = vtk.vtkPoints()
        vpts.SetData(numpy_to_vtk(np.ascontiguousarray(mesh), deep=True))
        pd.SetPoints(vpts)
        deln.SetInputData(pd)
    else:
        deln.SetInputData(mesh.GetMapper().GetInput())
    deln.SetAlpha(alphaPar)
    deln.AlphaTetsOn()
    deln.AlphaTrisOff()
    deln.AlphaLinesOff()
    deln.AlphaVertsOff()
    if tol:
        deln.SetTolerance(tol)
    deln.SetBoundingTriangulation(boundary)
    deln.Update()
    m = TetMesh(deln.GetOutput())
    return m
Esempio n. 32
0
def cuboid(resolution=7, size=[1, 1, 1]):
    points = vtk.vtkPoints()

    dx = float(size[0]) / float(resolution)
    dy = float(size[1]) / float(resolution)
    dz = float(size[2]) / float(resolution)

    xh = float(size[0]) / 2.0
    yh = float(size[1]) / 2.0
    zh = float(size[2]) / 2.0

    for x in range(0, resolution + 1):
        for y in range(0, resolution + 1):
            for z in range(0, resolution + 1):
                points.InsertNextPoint(x * dx - xh, y * dy - yh, z * dz - zh)

    grid = vtk.vtkPolyData()
    grid.SetPoints(points)

    mesh = vtk.vtkDelaunay3D()
    mesh.SetInput(grid)

    return mesh
Esempio n. 33
0
def tetra(size=1):
    size = size / 2.0

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, -size, -size)
    points.InsertNextPoint(-size, -size, size)
    points.InsertNextPoint(size, -size, size)
    points.InsertNextPoint(0, size, 0)

    tetra = vtk.vtkTetra()
    tetra.GetPointIds().SetId(0, 0)
    tetra.GetPointIds().SetId(1, 1)
    tetra.GetPointIds().SetId(2, 2)
    tetra.GetPointIds().SetId(3, 3)

    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.InsertNextCell(tetra.GetCellType(), tetra.GetPointIds())

    mesh = vtk.vtkDelaunay3D()  # vtk.vtkPassThroughFilter()
    mesh.SetInput(grid)

    return mesh
Esempio n. 34
0
def create_actor_tri(pts, color, **kwargs):
    """ Creates a VTK actor for rendering triangulated plots.

    :param pts: points
    :type pts: vtkFloatArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Get keyword arguments
    use_delaunay3d = kwargs.get("d3d", False)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Convert points to poly data
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Apply Delaunay triangulation on the poly data object
    triangulation = vtk.vtkDelaunay3D(
    ) if use_delaunay3d else vtk.vtkDelaunay2D()
    triangulation.SetInputData(polydata)

    # Map triangulated surface to the graphics primitives
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(triangulation.GetOutputPort())

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)

    # Return the actor
    return actor
Esempio n. 35
0
def generateVTKFromPoints(listOfPoints):
    math = vtk.vtkMath()
    points = vtk.vtkPoints()
    for elt in listOfPoints:
        (i,x,y,z) = elt
        points.InsertPoint(i,x,y,z)

    profile = vtk.vtkPolyData()
    profile.SetPoints(points)

    delny = vtk.vtkDelaunay3D()
    delny.SetInputData(profile)
    delny.SetTolerance(0.0001)
    delny.SetAlpha(0)
    print("alpha :",delny.GetAlpha())

    print("Output :", delny.GetOutput())
    delny.BoundingTriangulationOff()

    toSave = vtk.vtkUnstructuredGridWriter()
    toSave.SetInputConnection(delny.GetOutputPort())

    toSave.SetFileName("Cube"+str(len(listOfPoints))+".vtk")
    toSave.Write()
Esempio n. 36
0
points.InsertNextPoint(5,1,7)
points.InsertNextPoint(11,1,5)
points.InsertNextPoint(10,1,4)
points.InsertNextPoint(10,0,4)
points.InsertNextPoint(11,0,5)
points.InsertNextPoint(10,0,0)
points.InsertNextPoint(11,0,0)
points.InsertNextPoint(11,1,0)
points.InsertNextPoint(10,1,0)

profile = vtk.vtkPolyData()
profile.SetPoints(points)

# triangulate them
#
del1 = vtk.vtkDelaunay3D()
del1.SetInputData(profile)
del1.SetTolerance(0.01)
del1.SetAlpha(2.8)
del1.AlphaTetsOn()
del1.AlphaTrisOn()
del1.AlphaLinesOff()
del1.AlphaVertsOn()

map = vtk.vtkDataSetMapper()
map.SetInputConnection(del1.GetOutputPort())
triangulation = vtk.vtkActor()
triangulation.SetMapper(map)
triangulation.GetProperty().SetColor(1,0,0)
# Create graphics stuff
#
Esempio n. 37
0
disk.SetRadius(1.0)

diskGlyph = vtk.vtkGlyph3D()
diskGlyph.SetInput(data)
diskGlyph.SetSource(disk.GetOutput())
diskGlyph.SetScaleModeToScaleByScalar()

ctfun = vtk.vtkColorTransferFunction()
ctfun.AddRGBPoint(1.0, 1, 1, 1)
ctfun.AddRGBPoint(2.0, 0.5, 0.0, 0.0)
ctfun.AddRGBPoint(5.5, 1.0, 0.5, 0.5)
ctfun.AddRGBPoint(7.0, 0.9, 0.2, 0.3)
ctfun.AddRGBPoint(9.0, 0.81, 0.27, 0.1)
ctfun.AddRGBPoint(11.0, 0.5, 0.5, 0.5)

delny = vtk.vtkDelaunay3D()
delny.SetInput(diskGlyph.GetOutput())
delny.SetTolerance(1.0)
delny.SetAlpha(2.0)
delny.BoundingTriangulationOff()
delnyMapper=vtk.vtkDataSetMapper()
delnyMapper.SetInput(delny.GetOutput())

volumeMapper=vtk.vtkUnstructuredGridVolumeRayCastMapper()
volumeMapper.SetInput(delny.GetOutput())
volprop=vtk.vtkVolumeProperty()
volprop.SetColor(ctfun)
volprop.SetInterpolationTypeToLinear()


# Create a renderer and add the actors to it
Esempio n. 38
0
	u = vtk.vtkUnstructuredGrid()
	bgridreader=vtk.vtkXMLUnstructuredGridReader()
	bgridreader.SetFileName(Plane)
	bgridreader.Update()
	u = bgridreader.GetOutput() 
	GeomFilt2 = vtk.vtkGeometryFilter()
	GeomFilt2.SetInput(u)
	GeomFilt2.Update()
	y = GeomFilt2.GetOutput()

	append = vtk.vtkAppendPolyData()
	append.AddInput(x)
	append.AddInput(y)
	data = append.GetOutput()
	
	d = vtk.vtkDelaunay3D()
	d.SetInput(data)
	d.Update
	d.BoundingTriangulationOff()  
	d.SetTolerance(0.01)
	d.SetAlpha(0)
	d.Update()
	z = d.GetOutput()
	return z

if __name__ == '__main__':
	z = Create_topo()
	writer = vtk.vtkGenericDataObjectWriter()
	writer.SetFileName("test31.vtu")
	writer.SetInput(z)
	writer.Update()
Esempio n. 39
0
"""
Example of plotting a set of isosurfaces
"""

# set up some data to plot
from numpy import *

import vtk

# load a vtk file as input
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("../../temp-0500.vtk")
reader.Update()

# need to do a delaunay 3D here to get decent looking isosurfaces
del3D = vtk.vtkDelaunay3D()
del3D.SetInput(reader.GetOutput())
del3D.SetOffset(2.5)
del3D.SetTolerance(0.001)
del3D.SetAlpha(0.0)

# set up a contour filter
cont = vtk.vtkContourGrid()
cont.SetInput(del3D.GetOutput())
cont.GenerateValues(5, 0.25, 0.75)  # need to automate this!!
cont.ComputeScalarsOn()

# get the model centre and bounds
centre = reader.GetOutput().GetCenter()
bounds = reader.GetOutput().GetBounds()
Esempio n. 40
0
    def setWidgetView(self, widget, color = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]):
        super(SurfaceView, self).setWidgetView(widget)
        
        if type(self.parent) is MdiChildRegistration:
            point_array_move = self.parent.getData('move').pointSet
            point_data_move = npy.array(point_array_move.getData('Contour'))
            point_data_result = npy.array(point_data_move)
            
            if point_data_result is None or not point_data_result.shape[0]:
                return
                
            self.spacing_mov = self.parent.getData('move').getResolution().tolist()
            self.spacing = self.parent.getData().getResolution().tolist()
            
            para = npy.array(self.parent.getData().getInfo().getData('transform'))
            R = ml.mat(para[:9].reshape(3, 3))
            T = ml.mat(para[9:12].reshape(3, 1))
            
            T = R.I * T
            T = -T
            point_data_result[:, :3] *= self.spacing_mov[:3]
            point_data_result[:, :3] = ml.mat(point_data_result[:, :3]) * R + ml.ones((point_data_result.shape[0], 1)) * T.T
            point_data_result[:, :3] /= self.spacing[:3]
        else:
            point_array_result = self.parent.getData().pointSet
            point_data_result = npy.array(point_array_result.getData('Contour'))
            point_array_move = point_array_result
            point_data_move = npy.array(point_array_move.getData('Contour'))

        
        zmin = int(npy.min(point_data_move[:, 2]) + 0.5)
        zmax = int(npy.max(point_data_move[:, 2]) + 0.5)
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing = [float(x) / self.spacing[-1] for x in self.spacing]
        point_data_result[:, :2] *= self.spacing[:2]
        
        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)
        
        self.contours = []
        self.delaunay3D = []
        self.delaunayMapper = []
        self.surface_actor = []
        
        for cnt in range(3):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_result = point_data_result[npy.where(npy.round(point_data_result[:, -1]) == cnt)]
            point_move = point_data_move[npy.where(npy.round(point_data_move[:, -1]) == cnt)]
            if not point_result.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(zmin, zmax + 1):
                data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(color[cnt][0], color[cnt][1], color[cnt][2])
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()
        
        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
Esempio n. 41
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')
        
        if self.CheckNonManifold:
            self.PrintLog('NonManifold check.')
            nonManifoldChecker = vmtkNonManifoldSurfaceChecker()
            nonManifoldChecker.Surface = self.Surface
            nonManifoldChecker.PrintError = self.PrintError
            nonManifoldChecker.Execute()

            if nonManifoldChecker.NumberOfNonManifoldEdges > 0:
                self.PrintLog(nonManifoldChecker.Report)
                return

        self.PrintLog('Cleaning surface.')
        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInput(self.Surface)
        surfaceCleaner.Update()

        self.PrintLog('Triangulating surface.')
        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInput(surfaceCleaner.GetOutput())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        surfaceCapper = vtkvmtk.vtkvmtkCapPolyData()
        surfaceCapper.SetInput(surfaceTriangulator.GetOutput())
        surfaceCapper.SetDisplacement(self.CapDisplacement)
        surfaceCapper.SetInPlaneDisplacement(self.CapDisplacement)
        surfaceCapper.Update()

        capCenterIds = surfaceCapper.GetCapCenterIds()

        surfaceNormals = vtk.vtkPolyDataNormals()
        surfaceNormals.SetInput(surfaceCapper.GetOutput())
        surfaceNormals.SplittingOff()
        surfaceNormals.AutoOrientNormalsOn()
        surfaceNormals.SetFlipNormals(self.FlipNormals)
        surfaceNormals.ComputePointNormalsOn()
        surfaceNormals.ConsistencyOn()
        surfaceNormals.Update()
        
        inputSurface = surfaceNormals.GetOutput()

        if self.UseTetGen:
            self.PrintLog('Running TetGen.')
            import vmtkscripts
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = inputSurface
            surfaceToMesh.Execute()
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.PLC = 1
            tetgen.NoMerge = 1
            tetgen.Quality = 0
            if self.TetGenDetectInter:
                tetgen.DetectInter = 1
                tetgen.NoMerge = 0
            tetgen.OutputSurfaceElements = 0
            tetgen.Execute()
            self.DelaunayTessellation = tetgen.Mesh
        else:
            delaunayTessellator = vtk.vtkDelaunay3D()
            delaunayTessellator.CreateDefaultLocator()
            delaunayTessellator.SetInput(surfaceNormals.GetOutput())
            delaunayTessellator.SetTolerance(self.DelaunayTolerance)
            delaunayTessellator.Update()
            self.DelaunayTessellation = delaunayTessellator.GetOutput()

        normalsArray = surfaceNormals.GetOutput().GetPointData().GetNormals()
        self.DelaunayTessellation.GetPointData().AddArray(normalsArray)

        internalTetrahedraExtractor = vtkvmtk.vtkvmtkInternalTetrahedraExtractor()
        internalTetrahedraExtractor.SetInput(self.DelaunayTessellation)
        internalTetrahedraExtractor.SetOutwardNormalsArrayName(normalsArray.GetName())
        if self.RemoveSubresolutionTetrahedra:
            internalTetrahedraExtractor.RemoveSubresolutionTetrahedraOn()
            internalTetrahedraExtractor.SetSubresolutionFactor(self.SubresolutionFactor)
            internalTetrahedraExtractor.SetSurface(inputSurface)
        if capCenterIds.GetNumberOfIds() > 0:
          internalTetrahedraExtractor.UseCapsOn()
          internalTetrahedraExtractor.SetCapCenterIds(capCenterIds)
        internalTetrahedraExtractor.Update()

        self.DelaunayTessellation = internalTetrahedraExtractor.GetOutput()

        voronoiDiagramFilter = vtkvmtk.vtkvmtkVoronoiDiagram3D()
        voronoiDiagramFilter.SetInput(self.DelaunayTessellation)
        voronoiDiagramFilter.SetRadiusArrayName(self.RadiusArrayName)
        voronoiDiagramFilter.Update()

        self.PoleIds = voronoiDiagramFilter.GetPoleIds()

        self.VoronoiDiagram = voronoiDiagramFilter.GetOutput()

        if self.SimplifyVoronoi:
            voronoiDiagramSimplifier = vtkvmtk.vtkvmtkSimplifyVoronoiDiagram()
            voronoiDiagramSimplifier.SetInput(voronoiDiagramFilter.GetOutput())
            voronoiDiagramSimplifier.SetUnremovablePointIds(voronoiDiagramFilter.GetPoleIds())
            voronoiDiagramSimplifier.Update()
            self.VoronoiDiagram = voronoiDiagramSimplifier.GetOutput()

        self.Mesh = self.DelaunayTessellation
        self.Surface = self.VoronoiDiagram
Esempio n. 42
0
    def _getECMstrain(self):
        """
        Generates tetrahedrons from object centroids in the reference and deformed states.
        The highest quality tetrahedron (edge ratio closest to 1) is used to construct a
        linear system of equations,

        :math:`\|\mathbf{w}\|^2 - \|\mathbf{W}\|^2 = \mathbf{W}.\mathbf{E}.\mathbf{W}`,

        where, :math:`\mathbf{W}` are the reference tetrahedron edges (as vectors) and
        :math:`\mathbf{w}` are the deformed tetrahedron edges, to solve for Green-Lagrange
        strain, :math:`\mathbf{E}`.

        Returns
        -------
        ecm_strain
        """
        #get the ECM strain
        rc = np.array(self.rcentroids)
        dc = np.array(self.dcentroids)
        if rc.shape[0] < 4:
            print(("WARNING: There are less than 4 objects in the space; "
                   "therefore, tissue strain was not calculated."))
            return
        da = numpy_to_vtk(rc)
        p = vtk.vtkPoints()
        p.SetData(da)
        pd = vtk.vtkPolyData()
        pd.SetPoints(p)

        tet = vtk.vtkDelaunay3D()
        tet.SetInputData(pd)
        tet.Update()
        quality = vtk.vtkMeshQuality()
        quality.SetInputData(tet.GetOutput())
        quality.Update()
        mq = quality.GetOutput().GetCellData().GetArray("Quality")
        mq = vtk_to_numpy(mq)
        try:
            #tet with edge ratio closest to 1
            btet = np.argmin(abs(mq - 1.0))
        except:
            return
        idlist = tet.GetOutput().GetCell(btet).GetPointIds()
        P = np.zeros((4, 3), float)
        p = np.zeros((4, 3), float)
        for i in range(idlist.GetNumberOfIds()):
            P[i, :] = rc[idlist.GetId(i), :]
            p[i, :] = dc[idlist.GetId(i), :]
        X = np.array([P[1, :] - P[0, :],
                      P[2, :] - P[0, :],
                      P[3, :] - P[0, :],
                      P[3, :] - P[1, :],
                      P[3, :] - P[2, :],
                      P[2, :] - P[1, :]], float)

        x = np.array([p[1, :] - p[0, :],
                      p[2, :] - p[0, :],
                      p[3, :] - p[0, :],
                      p[3, :] - p[1, :],
                      p[3, :] - p[2, :],
                      p[2, :] - p[1, :]], float)

        #assemble the system
        dX = np.zeros((6, 6), float)
        ds = np.zeros((6, 1), float)
        for i in range(6):
            dX[i, 0] = 2 * X[i, 0] ** 2
            dX[i, 1] = 2 * X[i, 1] ** 2
            dX[i, 2] = 2 * X[i, 2] ** 2
            dX[i, 3] = 4 * X[i, 0] * X[i, 1]
            dX[i, 4] = 4 * X[i, 0] * X[i, 2]
            dX[i, 5] = 4 * X[i, 1] * X[i, 2]

            ds[i, 0] = np.linalg.norm(
                x[i, :]) ** 2 - np.linalg.norm(X[i, :]) ** 2

        E = np.linalg.solve(dX, ds)
        E = np.array([[E[0, 0], E[3, 0], E[4, 0]],
                      [E[3, 0], E[1, 0], E[5, 0]],
                      [E[4, 0], E[5, 0], E[2, 0]]], float)
        self.ecm_strain = E
Esempio n. 43
0
def prepareDelaunayData3d(
    dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs
):

    local_nodeidx2global_nodeidx = {}
    no_of_aggnodes = len(agg_globalnodeidx)
    no_aggs = len(aggid2nodes)

    Points = vtk.vtkPoints()
    Vertices = vtk.vtkCellArray()

    for i in range(0, len(agg_globalnodeidx)):
        id = -1
        local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
        nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
        id = Points.InsertNextPoint(
            nodecoords[0] + 0.0001 * random.random(),
            nodecoords[1] + 0.0001 * random.random(),
            nodecoords[2] + 0.0001 * random.random(),
        )
        Vertices.InsertNextCell(1)
        Vertices.InsertCellPoint(id)

    polydata2 = vtk.vtkPolyData()
    polydata2.SetPoints(Points)
    polydata2.Modified()
    polydata2.Update()

    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInput(polydata2)
    delaunay.Update()

    # create surfaceFilter
    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
    surfaceFilter.Update()

    pt_polydata = surfaceFilter.GetOutput()

    lookupTable = vtk.vtkLookupTable()
    lookupTable.SetNumberOfTableValues(no_aggs)
    lookupTable.Build()

    Ids = vtk.vtkUnsignedIntArray()
    Ids.SetNumberOfComponents(1)
    Ids.SetName("Ids")
    for i in range(0, Points.GetNumberOfPoints()):
        Ids.InsertNextTuple1(int(aggid))
    Ids.SetLookupTable(lookupTable)

    Procs = vtk.vtkUnsignedCharArray()
    Procs.SetNumberOfComponents(1)
    Procs.SetName("proc")
    for i in range(0, Points.GetNumberOfPoints()):
        Procs.InsertNextTuple1(aggid2procs[aggid])

    polydata3 = vtk.vtkPolyData()
    polydata3 = surfaceFilter.GetOutput()
    polydata3.GetPointData().SetScalars(Ids)
    polydata3.GetPointData().AddArray(Procs)

    polydata4 = vtk.vtkPolyData()
    polydata4.SetPoints(Points)
    polydata4.SetVerts(Vertices)
    polydata4.GetPointData().SetScalars(Ids)
    polydata4.GetPointData().AddArray(Procs)

    # datamapper = vtk.vtkDataSetMapper()
    # datamapper.SetInputConnection(delaunay.GetOutputPort())
    # datamapper.SetInput(polydata3)

    # actor = vtk.vtkActor()
    # actor.SetMapper(datamapper)

    # renderer = vtk.vtkRenderer()
    # renderWindow = vtk.vtkRenderWindow()
    # renderWindow.AddRenderer(renderer)
    # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    # renderWindowInteractor.SetRenderWindow(renderWindow)
    # renderer.AddActor(actor)
    # renderWindow.Render()
    # renderWindowInteractor.Start()

    # print polydata.GetVertices()

    aggpolygons.AddInput(polydata3)
    aggpolygons.AddInput(polydata4)
vtk_env_set.vtk_env_set('''C:/Program Files (x86)/VTK 6.3.0''')
os.environ = vtk_env_set.os.environ
os.environ['VTK_DATA_ROOT'] = os.path.abspath('''D:\lwtworker\VTK-6.3.0\VTKData''')

import vtk
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

# Begin by generating 25 random points in the unit sphere.
sphere = vtk.vtkPointSource()
sphere.SetNumberOfPoints(25)

# Triangulate the points with vtkDelaunay3D. This generates a convex hull
# of tetrahedron.
delny = vtk.vtkDelaunay3D()
delny.SetInputConnection(sphere.GetOutputPort())
delny.SetTolerance(0.01)

# The triangulation has texture coordinates generated so we can map
# a texture onto it.
tmapper = vtk.vtkTextureMapToCylinder()
tmapper.SetInputConnection(delny.GetOutputPort())
tmapper.PreventSeamOn()

# We scale the texture coordinate to get some repeat patterns.
xform = vtk.vtkTransformTextureCoords()
xform.SetInputConnection(tmapper.GetOutputPort())
xform.SetScale(4, 4, 1)

# vtkDataSetMapper internally uses a vtkGeometryFilter to extract the
Esempio n. 45
0
    def setWidgetView(self, widget):
        super(ComparingSurfaceView, self).setWidgetView(widget, [[1, 0, 0], [1, 0, 0], [1, 0, 0]])
        
        point_array_fix = self.parent.getData('fix').pointSet
        point_data_fix = npy.array(point_array_fix.getData('Contour'))
        
        if point_data_fix is None or not point_data_fix.shape[0]:
            return
        zmin = int(npy.min(point_data_fix[:, 2]) + 0.5)
        zmax = int(npy.max(point_data_fix[:, 2]) + 0.5)
        
        point_data_fix[:, :2] *= self.spacing[:2]
        
        for cnt in range(3, 6):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_fix = point_data_fix[npy.where(npy.round(point_data_fix[:, -1]) == cnt - 3)]
            if not point_fix.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(zmin, zmax + 1):
                data = point_fix[npy.where(npy.round(point_fix[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetXSpline(vtk.vtkKochanekSpline())
                    para_spline.SetYSpline(vtk.vtkKochanekSpline())
                    para_spline.SetZSpline(vtk.vtkKochanekSpline())
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(0, 0, 1)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.render_window.Render()
Esempio n. 46
0
def delaunay3D(points ,file_out=None,render=True,sizeX=800,sizeY=800,alpha=10.0,tolerance=0.001,offset=2.5,voxelspace=None):
    """
    Reads a file of vertices in VTK or OBJ format (ignoring any other info)
    Calls vtk Delaunay triangulation
    If file_out specified, writes the result in VTK and OBJ format
    As option, renders the result and displays it using OpenGL
    Optional parameters:
    - alpha (or distance) value to control output shape. VALUE=0.0 => convex hull
    - tolerance to control discarding of closely spaced points
    - offset to control the size of the initial, bounding Delaunay triangulation
    """

    vtkFile = tempfile.NamedTemporaryFile()

    # writes a copy compliant to VTK format
    # as the number of vertices musts be stated in the beginning
    # writing of the file must wait the input is totaly read
    vtkFile.write("# vtk DataFile Version 2.0\n"+vtkFile.name+'\n')
    vtkFile.write("ASCII\nDATASET UNSTRUCTURED_GRID\n")
    vtkFile.write("POINTS "+str(len(points))+" float\n")
    for p in points:
        vtkFile.write("%f %f %f\n" % tuple(p.xyz))
    vtkFile.flush()

    # read VTK input data
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(vtkFile.name)
    reader.Update()

    # delaunay3D
    delaunay = vtk.vtkDelaunay3D()
    delaunay.SetInputConnection(reader.GetOutputPort())
    delaunay.SetAlpha(alpha)
    delaunay.SetTolerance(tolerance)
    delaunay.SetOffset(offset)

    # extract geometry
    geometry = vtk.vtkGeometryFilter()
    geometry.SetInputConnection(delaunay.GetOutputPort())

    # triangulate
    triangle = vtk.vtkTriangleFilter()
    triangle.PassVertsOff()
    triangle.PassLinesOff()
    triangle.SetInputConnection(geometry.GetOutputPort())

    # write output data VTK
    if (file_out):
        writer = vtk.vtkPolyDataWriter()
        writer.SetFileName(file_out)
        writer.SetInputConnection(triangle.GetOutputPort())
        writer.Update()
    # write output data OBJ
    # as VTK format allows writing multiple points coordinates
    # on a single line, all the coordinates are read before writing
        pointsSection=False
        polygonsSection=False
        vtkFile=open(file_out,'r')
        objFile=open(file_out+'.obj','w')
        for line in vtkFile:
            liste=line.strip().split()
            if len(liste)>2 and liste[0]!='#':
                if polygonsSection:
                    if liste[0]=='3':
        # this polygon is a triangle
        # the indices of the vertices start from 0
        # in OBJ format, they start from 1
                        objFile.write('f')
                        for j in range(1,4):
                            objFile.write(' '+str(int(liste[j])+1))
                        objFile.write('\n')
                elif pointsSection:
                    if liste[0]=="POLYGONS":
                        pointsSection=False
                        polygonsSection=True
                        nTriangles=int(liste[1])
                        assert len(coord)==3*nPoints
                        for i in range(nPoints):
                            color = [0x77, 0x77, 0x77]
                            if voxelspace:
                                x, y, z = map(float, (coord[3*i], coord[3*i+1], coord[3*i+2]))
                                color = voxelspace.closestPointTo(voxel.Point(x, y, z)).toRGB()
                            objFile.write('v')
                            for j in range(3):
                                objFile.write(' '+coord[3*i+j])
                            for j in range(3):
                                objFile.write(' '+str(color[j]))
                            objFile.write('\n')	
                    else:
                        for c in liste:
                            coord.append(c)
                elif liste[0]=="POINTS":
                    pointsSection=True
                    nPoints=int(liste[1])
                    coord=[]
        vtkFile.close()
        objFile.close()
Esempio n. 47
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Generate texture coordinates on a "random" sphere.
# create some random points in a sphere
#
sphere = vtk.vtkPointSource()
sphere.SetNumberOfPoints(25)
# triangulate the points
#
del1 = vtk.vtkDelaunay3D()
del1.SetInputConnection(sphere.GetOutputPort())
del1.SetTolerance(0.01)
# texture map the sphere (using cylindrical coordinate system)
#
tmapper = vtk.vtkTextureMapToCylinder()
tmapper.SetInputConnection(del1.GetOutputPort())
tmapper.PreventSeamOn()
xform = vtk.vtkTransformTextureCoords()
xform.SetInputConnection(tmapper.GetOutputPort())
xform.SetScale(4, 4, 1)
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(xform.GetOutputPort())
# load in the texture map and assign to actor
#
bmpReader = vtk.vtkBMPReader()
bmpReader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/masonry.bmp")
atext = vtk.vtkTexture()
Esempio n. 48
0
 def initialize(self):
     debug("In Delaunay3D::initialize()")
     self.fil = vtk.vtkDelaunay3D()
     self.fil.SetInput(self.prev_fil.GetOutput())
     self.fil.Update()
Esempio n. 49
0
def prepareDelaunayData(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs):
    local_nodeidx2global_nodeidx = {}
    no_of_aggnodes = len(agg_globalnodeidx)
    dim = len(global_nodecoords[0])

    no_aggs = len(aggid2nodes)

    Points = vtk.vtkPoints()
    Vertices = vtk.vtkCellArray()

    for i in range(0, len(agg_globalnodeidx)):
        local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i]
        nodecoords = global_nodecoords[int(agg_globalnodeidx[i])]
        if dimension == 2:
            id = Points.InsertNextPoint(nodecoords[0], nodecoords[1], 0.0)
        elif dimension == 3:
            id = Points.InsertNextPoint(
                nodecoords[0] + 0.001 * random.random(),
                nodecoords[1] + 0.001 * random.random(),
                nodecoords[2] + 0.001 * random.random(),
            )
        Vertices.InsertNextCell(1)
        Vertices.InsertCellPoint(id)

    # create polygon for current aggregate
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetVerts(Vertices)
    polydata.Modified()
    polydata.Update()

    polydata2 = vtk.vtkPolyData()
    if Points.GetNumberOfPoints() > 2:  # todo: avoid error messages + add support for lines/surfaces
        # create delaunay object
        if dimension == 2:
            delaunay = vtk.vtkDelaunay2D()
        elif dimension == 3:
            delaunay = vtk.vtkDelaunay3D()
            # delaunay.SetAlpha(0.1)
        delaunay.SetInput(polydata)
        delaunay.Update()

        # create surfaceFilter
        surfaceFilter = vtk.vtkDataSetSurfaceFilter()
        surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
        surfaceFilter.Update()

        polydata2 = surfaceFilter.GetOutput()

    lookupTable = vtk.vtkLookupTable()
    lookupTable.SetNumberOfTableValues(no_aggs)
    lookupTable.Build()

    Ids = vtk.vtkUnsignedIntArray()
    Ids.SetNumberOfComponents(1)
    Ids.SetName("Ids")
    for i in range(0, Points.GetNumberOfPoints()):
        Ids.InsertNextTuple1(int(aggid))
    Ids.SetLookupTable(lookupTable)

    Procs = vtk.vtkUnsignedCharArray()
    Procs.SetNumberOfComponents(1)
    Procs.SetName("proc")
    for i in range(0, Points.GetNumberOfPoints()):
        Procs.InsertNextTuple1(aggid2procs[aggid])

    polydata2.SetPoints(Points)
    polydata2.SetVerts(Vertices)
    polydata2.GetPointData().SetScalars(Ids)
    polydata2.GetPointData().AddArray(Procs)
    polydata2.Modified()
    polydata2.Update()

    aggpolygons.AddInput(polydata2)
Esempio n. 50
0
    def _makeSTL(self):
        local_dir = self._gray_dir
        surface_dir = self._vol_dir+'_surfaces'+self._path_dlm
        try:
            os.mkdir(surface_dir)
        except:
            pass
        files = fnmatch.filter(sorted(os.listdir(local_dir)),'*.tif')
        counter = re.search("[0-9]*\.tif", files[0]).group()
        prefix = self._path_dlm+string.replace(files[0],counter,'')
        counter = str(len(counter)-4)
        prefixImageName = local_dir + prefix

        ### Create the renderer, the render window, and the interactor. The renderer
        # The following reader is used to read a series of 2D slices (images)
        # that compose the volume. The slice dimensions are set, and the
        # pixel spacing. The data Endianness must also be specified. The reader
        v16=vtk.vtkTIFFReader()

        v16.SetFilePrefix(prefixImageName)
        v16.SetDataExtent(0,100,0,100,1,len(files))
        v16.SetFilePattern("%s%0"+counter+"d.tif")
        v16.Update()

        im = v16.GetOutput()
        im.SetSpacing(self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2])

        v = vte.vtkImageExportToArray()
        v.SetInputData(im)

        n = np.float32(v.GetArray())
        idx = np.argwhere(n)
        (ystart,xstart,zstart), (ystop,xstop,zstop) = idx.min(0),idx.max(0)+1
        I,J,K = n.shape
        if ystart > 5:
            ystart -= 5
        else:
            ystart = 0
        if ystop < I-5:
            ystop += 5
        else:
            ystop = I
        if xstart > 5:
            xstart -= 5
        else:
            xstart = 0
        if xstop < J-5:
            xstop += 5
        else:
            xstop = J
        if zstart > 5:
            zstart -= 5
        else:
            zstart = 0
        if zstop < K-5:
            zstop += 5
        else:
            zstop = K

        a = n[ystart:ystop,xstart:xstop,zstart:zstop]
        itk_img = sitk.GetImageFromArray(a)
        itk_img.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        
        print "\n"
        print "-------------------------------------------------------"
        print "-- Applying Patch Based Denoising - this can be slow --"
        print "-------------------------------------------------------"
        print "\n"
        pb = sitk.PatchBasedDenoisingImageFilter()
        pb.KernelBandwidthEstimationOn()
        pb.SetNoiseModel(3) #use a Poisson noise model since this is confocal
        pb.SetNoiseModelFidelityWeight(1)
        pb.SetNumberOfSamplePatches(20)
        pb.SetPatchRadius(4)
        pb.SetNumberOfIterations(10)

        fimg = pb.Execute(itk_img)
        b = sitk.GetArrayFromImage(fimg)
        intensity = b.max()

        #grad = sitk.GradientMagnitudeRecursiveGaussianImageFilter()
        #grad.SetSigma(0.05)
        gf = sitk.GradientMagnitudeImageFilter()
        gf.UseImageSpacingOn()
        grad = gf.Execute(fimg)
        edge = sitk.Cast(sitk.BoundedReciprocal( grad ),sitk.sitkFloat32)


        print "\n"
        print "-------------------------------------------------------"
        print "---- Thresholding to deterimine initial level sets ----"
        print "-------------------------------------------------------"
        print "\n"
        t = 0.5
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        ids = sorted(np.unique(labels))
        N = len(ids)
        if N > 2:
            i = np.copy(N)
            while i == N and (t-self._tratio)>-1e-7:
                t -= 0.01
                seed = sitk.BinaryThreshold(fimg,t*intensity)
                #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
                seed = sitk.BinaryMorphologicalOpening(seed,2)
                seed = sitk.BinaryFillhole(seed!=0)
                #Get connected regions
                r = sitk.ConnectedComponent(seed)
                labels = sitk.GetArrayFromImage(r)
                i = len(np.unique(labels))
                if i > N:
                    N = np.copy(i)
            t+=0.01
        else:
            t = np.copy(self._tratio)
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        labels = np.unique(labels)[1:]

        '''
        labels[labels==0] = -1
        labels = sitk.GetImageFromArray(labels)
        labels.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        #myshow3d(labels,zslices=range(20))
        #plt.show()
        ls = sitk.ScalarChanAndVeseDenseLevelSetImageFilter()
        ls.UseImageSpacingOn()
        ls.SetLambda2(1.5)
        #ls.SetCurvatureWeight(1.0)
        ls.SetAreaWeight(1.0)
        #ls.SetReinitializationSmoothingWeight(1.0)
        ls.SetNumberOfIterations(100)
        seg = ls.Execute(sitk.Cast(labels,sitk.sitkFloat32),sitk.Cast(fimg,sitk.sitkFloat32))
        seg = sitk.Cast(seg,sitk.sitkUInt8)
        seg = sitk.BinaryMorphologicalOpening(seg,1)
        seg = sitk.BinaryFillhole(seg!=0)
        #Get connected regions
        #r = sitk.ConnectedComponent(seg)
        contours = sitk.BinaryContour(seg)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        segmentation = sitk.Image(r.GetSize(),sitk.sitkUInt8)
        segmentation.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        for l in labels:
            d = sitk.SignedMaurerDistanceMap(r==l,insideIsPositive=False,squaredDistance=True,useImageSpacing=True)
            #d = sitk.BinaryThreshold(d,-1000,0)
            #d = sitk.Cast(d,edge.GetPixelIDValue() )*-1+0.5
            #d = sitk.Cast(d,edge.GetPixelIDValue() )
            seg = sitk.GeodesicActiveContourLevelSetImageFilter()
            seg.SetPropagationScaling(1.0)
            seg.SetAdvectionScaling(1.0)
            seg.SetCurvatureScaling(0.5)
            seg.SetMaximumRMSError(0.01)
            levelset = seg.Execute(d,edge)
            levelset = sitk.BinaryThreshold(levelset,-1000,0)
            segmentation = sitk.Add(segmentation,levelset)
            print ("RMS Change for Cell %d: "% l,seg.GetRMSChange())
            print ("Elapsed Iterations for Cell %d: "% l, seg.GetElapsedIterations())
        '''
        contours = sitk.BinaryContour(segmentation)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        n[ystart:ystop,xstart:xstop,zstart:zstop] = sitk.GetArrayFromImage(segmentation)*100

        i = vti.vtkImageImportFromArray()
        i.SetDataSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        i.SetDataExtent([0,100,0,100,1,len(files)])
        i.SetArray(n)
        i.Update()

        thres=vtk.vtkImageThreshold()
        thres.SetInputData(i.GetOutput())
        thres.ThresholdByLower(0)
        thres.ThresholdByUpper(101)

        iso=vtk.vtkImageMarchingCubes()
        iso.SetInputConnection(thres.GetOutputPort())
        iso.SetValue(0,1)

        regions = vtk.vtkConnectivityFilter()
        regions.SetInputConnection(iso.GetOutputPort())
        regions.SetExtractionModeToAllRegions()
        regions.ColorRegionsOn()
        regions.Update()

        N = regions.GetNumberOfExtractedRegions()
        for i in xrange(N):
            r = vtk.vtkConnectivityFilter()
            r.SetInputConnection(iso.GetOutputPort())
            r.SetExtractionModeToSpecifiedRegions()
            r.AddSpecifiedRegion(i)
            g = vtk.vtkExtractUnstructuredGrid()
            g.SetInputConnection(r.GetOutputPort())
            geo = vtk.vtkGeometryFilter()
            geo.SetInputConnection(g.GetOutputPort())
            geo.Update()
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(geo.GetOutputPort())
            t.Update()
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputConnection(t.GetOutputPort())
            s = vtk.vtkSmoothPolyDataFilter()
            s.SetInputConnection(cleaner.GetOutputPort())
            s.SetNumberOfIterations(50)
            dl = vtk.vtkDelaunay3D()
            dl.SetInputConnection(s.GetOutputPort())
            dl.Update()

            self.cells.append(dl)

        for i in xrange(N):
            g = vtk.vtkGeometryFilter()
            g.SetInputConnection(self.cells[i].GetOutputPort())
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(g.GetOutputPort())

            #get the surface points of the cells and save to points attribute
            v = t.GetOutput()
            points = []
            for j in xrange(v.GetNumberOfPoints()):
                p = [0,0,0]
                v.GetPoint(j,p)
                points.append(p)
            self.points.append(points)

            #get the volume of the cell
            vo = vtk.vtkMassProperties()
            vo.SetInputConnection(t.GetOutputPort())
            self.volumes.append(vo.GetVolume())

            stl = vtk.vtkSTLWriter()
            stl.SetInputConnection(t.GetOutputPort())
            stl.SetFileName(surface_dir+'cell%02d.stl' % (i+self._counter))
            stl.Write()

        if self._display:
            skinMapper = vtk.vtkDataSetMapper()
            skinMapper.SetInputConnection(regions.GetOutputPort())
            skinMapper.SetScalarRange(regions.GetOutput().GetPointData().GetArray("RegionId").GetRange())
            skinMapper.SetColorModeToMapScalars()
            #skinMapper.ScalarVisibilityOff()
            skinMapper.Update()

            skin = vtk.vtkActor()
            skin.SetMapper(skinMapper)
            #skin.GetProperty().SetColor(0,0,255)

            # An outline provides context around the data.
            #
            outlineData = vtk.vtkOutlineFilter()
            outlineData.SetInputConnection(v16.GetOutputPort())

            mapOutline = vtk.vtkPolyDataMapper()
            mapOutline.SetInputConnection(outlineData.GetOutputPort())

            outline = vtk.vtkActor()
            #outline.SetMapper(mapOutline)
            #outline.GetProperty().SetColor(0,0,0)

            colorbar = vtk.vtkScalarBarActor()
            colorbar.SetLookupTable(skinMapper.GetLookupTable())
            colorbar.SetTitle("Cells")
            colorbar.SetNumberOfLabels(N)


            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and 
            # keyboard-based interaction with the data within the render window.
            #
            aRenderer = vtk.vtkRenderer()
            renWin = vtk.vtkRenderWindow()
            renWin.AddRenderer(aRenderer)
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)

            # It is convenient to create an initial view of the data. The FocalPoint
            # and Position form a vector direction. Later on (ResetCamera() method)
            # this vector is used to position the camera to look at the data in
            # this direction.
            aCamera = vtk.vtkCamera()
            aCamera.SetViewUp (0, 0, -1)
            aCamera.SetPosition (0, 1, 0)
            aCamera.SetFocalPoint (0, 0, 0)
            aCamera.ComputeViewPlaneNormal()

            # Actors are added to the renderer. An initial camera view is created.
            # The Dolly() method moves the camera towards the FocalPoint,
            # thereby enlarging the image.
            aRenderer.AddActor(outline)
            aRenderer.AddActor(skin)
            aRenderer.AddActor(colorbar)
            aRenderer.SetActiveCamera(aCamera)
            aRenderer.ResetCamera ()
            aCamera.Dolly(1.5)

            # Set a background color for the renderer and set the size of the
            # render window (expressed in pixels).
            aRenderer.SetBackground(0.0,0.0,0.0)
            renWin.SetSize(800, 600)

            # Note that when camera movement occurs (as it does in the Dolly()
            # method), the clipping planes often need adjusting. Clipping planes
            # consist of two planes: near and far along the view direction. The 
            # near plane clips out objects in front of the plane the far plane
            # clips out objects behind the plane. This way only what is drawn
            # between the planes is actually rendered.
            aRenderer.ResetCameraClippingRange()

            im=vtk.vtkWindowToImageFilter()
            im.SetInput(renWin)

            iren.Initialize();
            iren.Start();

        #remove gray directory
        shutil.rmtree(local_dir)
Esempio n. 51
0
    def _getECMstrain(self):
        """
        Generates tetrahedrons from object centroids in the reference and deformed states.
        The highest quality tetrahedron (edge ratio closest to 1) is used to construct a
        linear system of equations,

        :math:`\|\mathbf{w}\|^2 - \|\mathbf{W}\|^2 = \mathbf{W}.\mathbf{E}.\mathbf{W}`,

        where, :math:`\mathbf{W}` are the reference tetrahedron edges (as vectors) and
        :math:`\mathbf{w}` are the deformed tetrahedron edges, to solve for Green-Lagrange
        strain, :math:`\mathbf{E}`.

        Returns
        -------
        ecm_strain
        """
        #get the ECM strain
        rc = np.array(self.rcentroids)
        dc = np.array(self.dcentroids)
        if rc.shape[0] < 4:
            print(("WARNING: There are less than 4 objects in the space; "
                   "therefore, tissue strain was not calculated."))
            return
        da = numpy_to_vtk(rc)
        p = vtk.vtkPoints()
        p.SetData(da)
        pd = vtk.vtkPolyData()
        pd.SetPoints(p)

        tet = vtk.vtkDelaunay3D()
        tet.SetInputData(pd)
        tet.Update()
        quality = vtk.vtkMeshQuality()
        quality.SetInputData(tet.GetOutput())
        quality.Update()
        mq = quality.GetOutput().GetCellData().GetArray("Quality")
        mq = vtk_to_numpy(mq)
        try:
            #tet with edge ratio closest to 1
            btet = np.argmin(abs(mq - 1.0))
        except:
            return
        idlist = tet.GetOutput().GetCell(btet).GetPointIds()
        P = np.zeros((4, 3), float)
        p = np.zeros((4, 3), float)
        for i in range(idlist.GetNumberOfIds()):
            P[i, :] = rc[idlist.GetId(i), :]
            p[i, :] = dc[idlist.GetId(i), :]
        X = np.array([
            P[1, :] - P[0, :], P[2, :] - P[0, :], P[3, :] - P[0, :],
            P[3, :] - P[1, :], P[3, :] - P[2, :], P[2, :] - P[1, :]
        ], float)

        x = np.array([
            p[1, :] - p[0, :], p[2, :] - p[0, :], p[3, :] - p[0, :],
            p[3, :] - p[1, :], p[3, :] - p[2, :], p[2, :] - p[1, :]
        ], float)

        #assemble the system
        dX = np.zeros((6, 6), float)
        ds = np.zeros((6, 1), float)
        for i in range(6):
            dX[i, 0] = 2 * X[i, 0]**2
            dX[i, 1] = 2 * X[i, 1]**2
            dX[i, 2] = 2 * X[i, 2]**2
            dX[i, 3] = 4 * X[i, 0] * X[i, 1]
            dX[i, 4] = 4 * X[i, 0] * X[i, 2]
            dX[i, 5] = 4 * X[i, 1] * X[i, 2]

            ds[i, 0] = np.linalg.norm(x[i, :])**2 - np.linalg.norm(X[i, :])**2

        E = np.linalg.solve(dX, ds)
        E = np.array([[E[0, 0], E[3, 0], E[4, 0]], [E[3, 0], E[1, 0], E[5, 0]],
                      [E[4, 0], E[5, 0], E[2, 0]]], float)
        self.ecm_strain = E
Esempio n. 52
0
    def setWidgetView(self, widget):
        super(SurfaceGifView, self).setWidgetView(widget)
        
        self.point_array_move = self.parent.getData('move').pointSet
        self.point_data_move = npy.array(self.point_array_move.getData('Contour'))
        self.point_array_fix = self.parent.getData('fix').pointSet
        self.point_data_fix = npy.array(self.point_array_fix.getData('Contour'))
        
        if self.point_data_move is None or not self.point_data_move.shape[0]:
            return
        if self.point_data_fix is None or not self.point_data_fix.shape[0]:
            return
        
        #self.spacing = [1, 1, 1]
        self.spacing = self.parent.getData().getResolution().tolist()
        self.spacing_move = self.parent.getData('move').getResolution().tolist()
        self.tmp_space = self.spacing[-1]
        self.spacing = [float(x) / self.tmp_space for x in self.spacing]
        #point_data_move[:, :2] *= self.spacing_move[:2]
        self.point_data_fix[:, :2] *= self.spacing[:2]
        self.zmin = int(npy.min(self.point_data_fix[:, 2]) + 0.5)
        self.zmax = int(npy.max(self.point_data_fix[:, 2]) + 0.5)
        
        self.renderer = vtk.vtkRenderer()
        self.render_window = widget.GetRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.render_window.SetInteractor(self.window_interactor)
        
        self.contours = []
        self.delaunay3D = []
        self.delaunayMapper = []
        self.surface_actor = []
        
        for cnt in range(3):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_fix = self.point_data_fix[npy.where(npy.round(self.point_data_fix[:, -1]) == cnt)]
            if not point_fix.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(self.zmin, self.zmax + 1):
                data = point_fix[npy.where(npy.round(point_fix[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(0, 0, 1)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.renderer.ResetCamera()
        point = self.renderer.GetActiveCamera().GetFocalPoint()
        dis = self.renderer.GetActiveCamera().GetDistance()
        self.renderer.GetActiveCamera().SetViewUp(0, 0, 1)
        self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2])
        self.renderer.ResetCameraClippingRange()
        self.render_window.Render()
        
        # Manually set to trackball style
        self.window_interactor.SetKeyCode('t')
        self.window_interactor.CharEvent()
        self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback)
        self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
        
        self.tmp_data_move = npy.array(self.point_data_move)
        self.tmp_data_move[:, :3] *= self.spacing_move[:3]
        
        self.spacing_move = [float(x) / self.spacing_move[-1] for x in self.spacing_move]
        self.point_data_move[:, :2] *= self.spacing_move[:2]
        self.zmin = int(npy.min(self.point_data_move[:, 2]) + 0.5)
        self.zmax = int(npy.max(self.point_data_move[:, 2]) + 0.5)
        
        self.point_data_result = self.point_data_move
        
        for cnt in range(3, 6):
            self.contours.append(vtk.vtkPolyData())
            self.delaunay3D.append(vtk.vtkDelaunay3D())
            self.delaunayMapper.append(vtk.vtkDataSetMapper())
            self.surface_actor.append(vtk.vtkActor())
            
            point_result = self.point_data_result[npy.where(npy.round(self.point_data_result[:, -1]) == cnt - 3)]
            point_move = self.point_data_move[npy.where(npy.round(self.point_data_move[:, -1]) == cnt - 3)]
            if not point_result.shape[0]:
                continue
                
            self.cells = vtk.vtkCellArray()
            self.points = vtk.vtkPoints()
            l = 0
            for i in range(self.zmin, self.zmax + 1):
                data = point_result[npy.where(npy.round(point_move[:, 2]) == i)]
                if data is not None:
                    if data.shape[0] == 0:
                        continue
                    count = data.shape[0]
                    points = vtk.vtkPoints()
                    for j in range(count):
                        points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2])
                    
                    para_spline = vtk.vtkParametricSpline()
                    para_spline.SetXSpline(vtk.vtkKochanekSpline())
                    para_spline.SetYSpline(vtk.vtkKochanekSpline())
                    para_spline.SetZSpline(vtk.vtkKochanekSpline())
                    para_spline.SetPoints(points)
                    para_spline.ClosedOn()
                    
                    # The number of output points set to 10 times of input points
                    numberOfOutputPoints = count * 10
                    self.cells.InsertNextCell(numberOfOutputPoints)
                    for k in range(0, numberOfOutputPoints):
                        t = k * 1.0 / numberOfOutputPoints
                        pt = [0.0, 0.0, 0.0]
                        para_spline.Evaluate([t, t, t], pt, [0] * 9)
                        if pt[0] != pt[0]:
                            print pt
                            continue
                        self.points.InsertPoint(l, pt[0], pt[1], pt[2])
                        self.cells.InsertCellPoint(l)
                        l += 1

            self.contours[cnt].SetPoints(self.points)
            self.contours[cnt].SetPolys(self.cells)
            
            self.delaunay3D[cnt].SetInput(self.contours[cnt])
            self.delaunay3D[cnt].SetAlpha(2)
            
            self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput())
            
            self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt])
            self.surface_actor[cnt].GetProperty().SetDiffuseColor(1, 0, 0)
            self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1)
            self.surface_actor[cnt].GetProperty().SetSpecular(0.4)
            self.surface_actor[cnt].GetProperty().SetSpecularPower(50)
            
            self.renderer.AddViewProp(self.surface_actor[cnt])
        
        self.render_window.Render()
Esempio n. 53
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
         
        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(1, 1, 1)
        sphere.SetRadius(1)
        sphere.SetThetaResolution(100)
        sphere.SetPhiResolution(100)
        sphere.Update()
         
        cube = vtk.vtkCubeSource()
        cube.SetBounds(-1,1,-1,1,-1,1)
        cube.Update()
         
        # Create 3D cells so vtkImplicitDataSet evaluates inside vs outside correctly
        tri = vtk.vtkDelaunay3D()
        tri.SetInput(cube.GetOutput())
        tri.BoundingTriangulationOff()
         
        # vtkImplicitDataSet needs some scalars to interpolate to find inside/outside
        elev = vtk.vtkElevationFilter()
        elev.SetInputConnection(tri.GetOutputPort())
         
        implicit = vtk.vtkImplicitDataSet()
        implicit.SetDataSet(elev.GetOutput())
         
        clipper = vtk.vtkClipPolyData()
        clipper.SetClipFunction(implicit)
        clipper.SetInputConnection(sphere.GetOutputPort())
        clipper.InsideOutOn()
        clipper.Update()
         
        # Vis for clipped sphere
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(clipper.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetRepresentationToWireframe()
         
        # Vis for cube so can see it in relation to clipped sphere
        mapper2 = vtk.vtkDataSetMapper()
        mapper2.SetInputConnection(elev.GetOutputPort())
        actor2 = vtk.vtkActor()
        actor2.SetMapper(mapper2)
        #actor2.GetProperty().SetRepresentationToWireframe()
         
        #create renderers and add actors of plane and cube
        self.ren.AddActor(actor)
        self.ren.AddActor(actor2)
        self.ren.SetBackground(0.1, 0.2, 0.4)

        self.ren.ResetCamera()
        self._initialized = False
Esempio n. 54
0
def delaunay3DArea(system, radius=None, render=False):
  """
  Estimates system's area by summing all the triangles from Delaunay's triangulation
  
  """
  if radius is None:
    delaunayAlpha = 2.0
  else:
    delaunayAlpha = radius
    
  delaunayTolerance = 1.0
  
  clusterPoints = vtk.vtkPoints()
    
  for i in range(system.NAtoms):
    clusterPoints.InsertPoint(i, system.pos[i*3 + 0], system.pos[i*3 + 1], system.pos[i*3 + 2])
  
  polyCluster = vtk.vtkPolyData()
  polyCluster.SetPoints(clusterPoints)
  
  delaunayCluster = vtk.vtkDelaunay3D()
  delaunayCluster.SetInputData(polyCluster)
#   delaunayCluster.SetTolerance(delaunayTolerance)
  delaunayCluster.SetAlpha(delaunayAlpha)
  delaunayCluster.BoundingTriangulationOff()
  delaunayCluster.Update()
  
  clusterSurfaceFilter = vtk.vtkGeometryFilter()
  clusterSurfaceFilter.SetInputConnection(delaunayCluster.GetOutputPort())
  clusterSurfaceFilter.Update()
  
  mapClipper = vtk.vtkDataSetMapper()
  mapClipper.SetInputConnection(clusterSurfaceFilter.GetOutputPort())
  
  surfaceArea = 0.0
    
  clipperPointInput = mapClipper.GetInput()  
  for i in range(clipperPointInput.GetNumberOfCells()):
    p1 = clipperPointInput.GetCell(i).GetPoints().GetPoint(0)
    p2 = clipperPointInput.GetCell(i).GetPoints().GetPoint(1)
    p3 = clipperPointInput.GetCell(i).GetPoints().GetPoint(2)
    
    triangleArea = vtk.vtkTriangle.TriangleArea(p1, p2, p3)
    surfaceArea += triangleArea
  
  if render:
    
    # Shrink the result to help see it better.
    shrink = vtk.vtkShrinkFilter()
    shrink.SetInputConnection(delaunayCluster.GetOutputPort())
    shrink.SetShrinkFactor(0.9)
    
    map = vtk.vtkDataSetMapper()
    map.SetInputConnection(shrink.GetOutputPort())
    
    triangulation = vtk.vtkActor()
    triangulation.SetMapper(map)
    triangulation.GetProperty().SetColor(1, 0, 0)
    
    
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    # Add the actors to the renderer, set the background and size
    ren.AddActor(triangulation)
    ren.SetBackground(1, 1, 1)
    renWin.SetSize(250, 250)
    renWin.Render()
    
    cam1 = ren.GetActiveCamera()
    cam1.Zoom(1.5)
    
    iren.Initialize()
    renWin.Render()
    iren.Start()
  
  return surfaceArea