def splitDomainBetweenEndoAndEpi(
        pdata_domain,
        r=0.99,
        verbose=1):

    myVTK.myPrint(verbose, "*** splitDomainBetweenEndoAndEpi ***")

    bounds = pdata_domain.GetBounds()
    assert (r > 0.)
    assert (r < 1.)
    origin = [(1./2)*bounds[0]+(1./2)*bounds[1],
              (1./2)*bounds[2]+(1./2)*bounds[3],
              (1.-r)*bounds[4]+(  r )*bounds[5]]
    #myVTK.myPrint(verbose-1, "bounds = "+str(bounds))
    #myVTK.myPrint(verbose-1, "origin = "+str(origin))

    (pdata_domain,
     cap) = myVTK.clipPDataUsingPlane(
         pdata_mesh=pdata_domain,
         plane_O=origin,
         plane_N=[0,0,1],
         verbose=verbose-1)

    connectivity0 = vtk.vtkPolyDataConnectivityFilter()
    connectivity0.SetExtractionModeToSpecifiedRegions()
    connectivity0.AddSpecifiedRegion(0)
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        connectivity0.SetInputData(pdata_domain)
    else:
        connectivity0.SetInput(pdata_domain)
    connectivity0.Update()
    pdata0 = connectivity0.GetOutput()
    assert (pdata0.GetNumberOfPoints())

    connectivity1 = vtk.vtkPolyDataConnectivityFilter()
    connectivity1.SetExtractionModeToSpecifiedRegions()
    connectivity1.AddSpecifiedRegion(1)
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        connectivity1.SetInputData(pdata_domain)
    else:
        connectivity1.SetInput(pdata_domain)
    connectivity1.Update()
    pdata1 = connectivity1.GetOutput()
    assert (pdata1.GetNumberOfPoints())

    if (myVTK.getPDataSurfaceArea(pdata0,0) < myVTK.getPDataSurfaceArea(pdata1,0)):
        return pdata0, pdata1
    else:
        return pdata1, pdata0
Exemple #2
0
def splitDomainBetweenEndoAndEpi(
        pdata_domain,
        r=0.99,
        verbose=0):

    myVTK.myPrint(verbose, "*** splitDomainBetweenEndoAndEpi ***")

    bounds = pdata_domain.GetBounds()
    assert (r > 0.)
    assert (r < 1.)
    origin = [(1./2)*bounds[0]+(1./2)*bounds[1],
              (1./2)*bounds[2]+(1./2)*bounds[3],
              (1.-r)*bounds[4]+(  r )*bounds[5]]
    #myVTK.myPrint(verbose-1, "bounds = "+str(bounds))
    #myVTK.myPrint(verbose-1, "origin = "+str(origin))

    (pdata_domain,
     cap) = myVTK.clipPDataUsingPlane(
         pdata_mesh=pdata_domain,
         plane_O=origin,
         plane_N=[0,0,1],
         verbose=verbose-1)

    connectivity0 = vtk.vtkPolyDataConnectivityFilter()
    connectivity0.SetExtractionModeToSpecifiedRegions()
    connectivity0.AddSpecifiedRegion(0)
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        connectivity0.SetInputData(pdata_domain)
    else:
        connectivity0.SetInput(pdata_domain)
    connectivity0.Update()
    pdata0 = connectivity0.GetOutput()
    assert (pdata0.GetNumberOfPoints())

    connectivity1 = vtk.vtkPolyDataConnectivityFilter()
    connectivity1.SetExtractionModeToSpecifiedRegions()
    connectivity1.AddSpecifiedRegion(1)
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        connectivity1.SetInputData(pdata_domain)
    else:
        connectivity1.SetInput(pdata_domain)
    connectivity1.Update()
    pdata1 = connectivity1.GetOutput()
    assert (pdata1.GetNumberOfPoints())

    if (myVTK.getPDataSurfaceArea(pdata0,0) < myVTK.getPDataSurfaceArea(pdata1,0)):
        return pdata0, pdata1
    else:
        return pdata1, pdata0
def SurfaceDistance(threeDRA_path, CBCT_path, output_path):
    reader3DRA = vtk.vtkSTLReader()
    reader3DRA.SetFileName(threeDRA_path)
    reader3DRA.Update()
    threeDRA = reader3DRA.GetOutput()

    readerCBCT = vtk.vtkSTLReader()
    readerCBCT.SetFileName(CBCT_path)
    readerCBCT.Update()
    CBCT = readerCBCT.GetOutput()

    distanceFilter = vtk.vtkDistancePolyDataFilter()
    distanceFilter.SetInputData(0, threeDRA)
    distanceFilter.SetInputData(1, CBCT)
    distanceFilter.Update()

    # extract lcc object
    connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
    connectivityFilter.SetInputData(distanceFilter.GetOutput())
    connectivityFilter.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(output_path)
    writer.SetInputData(connectivityFilter.GetOutput())
    writer.Update()
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkPolyDataConnectivityFilter(), 'Processing.',
         ('vtkPolyData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemple #5
0
def loadSurface(fname):
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(fileName)
    reader.Update()

    # Take the largest connected component
    connectFilter = vtk.vtkPolyDataConnectivityFilter()
    connectFilter.SetInputConnection(reader.GetOutputPort())
    connectFilter.SetExtractionModeToLargestRegion()
    connectFilter.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(connectFilter.GetOutputPort())
    normals.Update()

    pd = normals.GetOutput()
    com = vtk.vtkCenterOfMass()
    com.SetInputData(pd)
    com.SetUseScalarsAsWeights(False)
    com.Update()
    center = com.GetCenter()

    # Mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(normals.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    prop = actor.GetProperty()
    prop.SetColor(vtk.vtkColor3d(hexCol("#873927")))

    # Assign actor to the renderer
    prop.SetOpacity(0.35)
    return actor, center
    def extractSurfaces(self):
        self.PrintLog("Extracting surfaces.")

        def bnorm(data):
            bounds = data.GetBounds()
            return math.sqrt(sum((bounds[2*i+1]-bounds[2*i])**2 for i in range(3)))

        # Get bounds of entire surface
        bounds_norm = bnorm(self.Surface)

        # Currently assuming that this is the region numbers that were produced by coloring!
        # TODO: If necessary, get from array to be more robust.
        region_ids = (0, 1)

        # Extract each surface in turn to find the smallest one
        subsurfaces = {}
        for k in region_ids:
            connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
            connectivityFilter.SetInputData(self.ColoredSurface)
            connectivityFilter.SetExtractionModeToSpecifiedRegions()
            connectivityFilter.AddSpecifiedRegion(k)
            connectivityFilter.ColorRegionsOff()
            connectivityFilter.SetScalarConnectivity(0)
            connectivityFilter.Update()
            subsurfaces[k] = connectivityFilter.GetOutput()

        # The inner surface has smaller bounds
        if bnorm(subsurfaces[region_ids[0]]) < bnorm(subsurfaces[region_ids[1]]):
            self.InnerRegionId = region_ids[0]
            self.OuterRegionId = region_ids[1]
        else:
            self.InnerRegionId = region_ids[1]
            self.OuterRegionId = region_ids[0]
        self.InnerSurface = subsurfaces[self.InnerRegionId]
        self.OuterSurface = subsurfaces[self.OuterRegionId]
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: No Image.')

        extent = self.Image.GetExtent()
        translateExtent = vtk.vtkImageTranslateExtent()
        translateExtent.SetInputData(self.Image)
        translateExtent.SetTranslation(-extent[0],-extent[2],-extent[4])
        translateExtent.Update()

        if (self.ArrayName != ''):
            translateExtent.GetOutput().GetPointData().SetActiveScalars(self.ArrayName)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputConnection(translateExtent.GetOutputPort())
        marchingCubes.SetValue(0,self.Level)
        marchingCubes.Update()

        self.Surface = marchingCubes.GetOutput()

        if self.Connectivity == 1:
            connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
            connectivityFilter.SetInputData(self.Surface)
            connectivityFilter.SetExtractionModeToLargestRegion()
            connectivityFilter.Update()
            self.Surface = connectivityFilter.GetOutput()
def get_region(mesh, mesh_out, region):
    """
    From a region with two connected components,
    get either first or second connected component
    and save them to mesh_out.

    Returns the output mesh
    """
    # Get region
    cc = vtk.vtkPolyDataConnectivityFilter()
    cc.SetInputData(mesh)
    cc.SetExtractionModeToSpecifiedRegions()
    cc.AddSpecifiedRegion(region)
    cc.Update()
    mesh_1 = cc.GetOutput(0)

    # Remove connected points
    clean = vtk.vtkCleanPolyData()
    clean.SetInputData(mesh_1)
    clean.Update()
    mesh_1 = clean.GetOutput(0)

    # Save
    rd = vtk.vtkPolyDataWriter()
    rd.SetInputData(mesh_1)
    rd.SetFileName(mesh_out)
    rd.Write()

    return mesh_1
    def _Clip(self, pd):
        # The plane implicit function will be >0 for all the points in the positive side
        # of the plane (i.e. x s.t. n.(x-o)>0, where n is the plane normal and o is the 
        # plane origin).
        plane = vtkPlane()
        plane.SetOrigin(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z)
        plane.SetNormal(self.Iolet.Normal.x, self.Iolet.Normal.y, self.Iolet.Normal.z)
        
        # The sphere implicit function will be >0 for all the points outside the sphere.
        sphere = vtkSphere()
        sphere.SetCenter(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z)
        sphere.SetRadius(self.Iolet.Radius)
        
        # The VTK_INTERSECTION operator takes the maximum value of all the registered 
        # implicit functions. This will result in the function evaluating to >0 for all 
        # the points outside the sphere plus those inside the sphere in the positive 
        # side of the plane.
        clippingFunction = vtkImplicitBoolean()
        clippingFunction.AddFunction(plane)
        clippingFunction.AddFunction(sphere)
        clippingFunction.SetOperationTypeToIntersection() 
        
        clipper = vtkClipPolyData()
        clipper.SetInput(pd)
        clipper.SetClipFunction(clippingFunction)

        # Filter to get part closest to seed point
        connectedRegionGetter = vtkPolyDataConnectivityFilter()
        connectedRegionGetter.SetExtractionModeToClosestPointRegion()
        connectedRegionGetter.SetClosestPoint(*self.SeedPoint)
        connectedRegionGetter.SetInputConnection(clipper.GetOutputPort())
        connectedRegionGetter.Update()
        return connectedRegionGetter.GetOutput()
Exemple #10
0
def cleanMesh(mesh, connectivityFilter=False):
    try:
        t = time.clock()
        connect = vtk.vtkPolyDataConnectivityFilter()
        clean = vtk.vtkCleanPolyData()

        if (connectivityFilter):
            if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
                connect.SetInputData( mesh )
            else:
                connect.SetInput( mesh )
            connect.SetExtractionModeToLargestRegion()
            clean.SetInputConnection( connect.GetOutputPort() )
        else:
            if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
                clean.SetInputData( mesh )
            else:
                clean.SetInput( mesh )

        clean.Update()
        print ("Surface cleaned")
        m2 = clean.GetOutput()
        print "    ", m2.GetNumberOfPolys(), "polygons"
        elapsedTime(t)
        clean = None
        connect = None
        return m2
    except:
        print "Surface cleaning failed"
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    return None
Exemple #11
0
def capsurface(polydata, arrayname=''):
    """Cap holes in surface with a flat cover."""
    # generates a flat cover for a convex hole defined by edges
    fedges = extractboundaryedge(polydata)

    # find each connected edge
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(fedges)
    connect.Update()

    ncontours = connect.GetNumberOfExtractedRegions()

    append = vtk.vtkAppendPolyData()
    append.AddInput(polydata)

    # generate each flat cover
    for i in range(ncontours):
        connect.AddSpecifiedRegion(i)
        connect.SetExtractionModeToSpecifiedRegions()
        connect.Update()
        edges = connect.GetOutput()
        cover = vtk.vtkPolyData()
        generatecover(edges, cover, arrayname)
        # append to original polydata
        append.AddInput(cover)
        connect.DeleteSpecifiedRegion(i)

    append.Update()
    outsurface = cleanpolydata(append.GetOutput())
    return outsurface
Exemple #12
0
def getregionsrange(polydata):
    """Return range of connected regions."""
    # extract surface
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInput(polydata)
    surfer.Update()

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

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

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

    # get range
    regions = surfer.GetOutput().GetPointData().GetArray('RegionId')
    regionsrange = regions.GetRange()
    return regionsrange
Exemple #13
0
def extractconnectedregion(polydata, regionid):
    """Run connectivity filter to assign regionsids and return region with
    given regionid."""
    # extract surface
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInput(polydata)
    surfer.Update()

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

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

    # threshold especified region
    surface = pointthreshold(connect.GetOutput(), 'RegionId', float(regionid),
                             float(regionid))
    return surface
Exemple #14
0
    def Execute(self):

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

        if (self.GroupId != -1) & (self.GroupIdsArrayName != ''):
            self.Surface.GetPointData().SetActiveScalars(
                self.GroupIdsArrayName)

        connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
        connectivityFilter.SetInput(self.Surface)
        connectivityFilter.ColorRegionsOff()
        connectivityFilter.SetExtractionModeToLargestRegion()
        if self.GroupId != -1:
            connectivityFilter.ScalarConnectivityOn()
            scalarRange = [self.GroupId, self.GroupId]
            connectivityFilter.SetScalarRange(scalarRange)
        connectivityFilter.Update()

        self.Surface = connectivityFilter.GetOutput()

        if self.CleanOutput == 1:
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(connectivityFilter.GetOutput())
            cleaner.Update()

            self.Surface = cleaner.GetOutput()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
Exemple #15
0
def cleanMesh(mesh, connectivityFilter=False):
    try:
        connect = vtk.vtkPolyDataConnectivityFilter()
        clean = vtk.vtkCleanPolyData()

        if (connectivityFilter):
            if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
                connect.SetInputData(mesh)
            else:
                connect.SetInput(mesh)
            connect.SetExtractionModeToLargestRegion()
            clean.SetInputConnection(connect.GetOutputPort())
        else:
            if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
                clean.SetInputData(mesh)
            else:
                clean.SetInput(mesh)

        clean.Update()
        print("Surface cleaned")
        m2 = clean.GetOutput()
        print("    ", m2.GetNumberOfPolys(), "polygons")
        return m2
    except:
        print("Surface cleaning failed")
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(
            exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    return None
Exemple #16
0
    def extractInnerSurface(self):
        self.PrintLog("Extracting inner surface.")

        def bnorm(data):
            bounds = data.GetBounds()
            return math.sqrt(sum((bounds[2*i+1]-bounds[2*i])**2 for i in range(3)))

        # Get bounds of entire surface
        bounds_norm = bnorm(self.Surface)

        # Currently assuming that this is the region numbers that were produced by coloring!
        # TODO: If necessary, get from array to be more robust.
        region_ids = (0, 1)

        # Extract each surface in turn to find the smallest one
        for k in region_ids:
            connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
            connectivityFilter.SetInputData(self.ColoredSurface)
            connectivityFilter.SetExtractionModeToSpecifiedRegions()
            connectivityFilter.AddSpecifiedRegion(k)
            connectivityFilter.ColorRegionsOff()
            connectivityFilter.SetScalarConnectivity(0)
            connectivityFilter.Update()
            subsurface = connectivityFilter.GetOutput()

            # The inner surface has smaller bounds
            if bnorm(subsurface) < bounds_norm - 1e-12:
                self.InnerRegionId = k
                self.InnerSurface = subsurface
                break

        assert self.InnerRegionId in region_ids
Exemple #17
0
def extractlargestregion(polydata):
    """Extract largest of several disconnected regions."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToLargestRegion()
    connect.Update()
    return connect.GetOutput()
Exemple #18
0
def extractlargestregion(polydata):
    """Extract largest of several disconnected regions."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToLargestRegion()
    connect.Update()
    return connect.GetOutput()
def ExtractGeometryZ(pd, nx, ny, nz, z0):
    """
    cut the mesh using z > z0
    could try vtkClipPolyData too
    """
    filter = vtk.vtkExtractPolyDataGeometry()

    function = vtk.vtkPlane()
    function.SetNormal(nx, ny, nz)
    function.SetOrigin(0, 0, z0)

    triangleFilter = vtk.vtkTriangleFilter()
    triangleFilter.SetInputData(pd)
    triangleFilter.Update()

    filter.SetImplicitFunction(function)
    filter.SetInputData(triangleFilter.GetOutput())
    filter.Update()

    #geometryFilter = vtk.vtkGeometryFilter()
    #geometryFilter.SetInputData(filter.GetOutput())
    #geometryFilter.Update()

    connectFilter = vtk.vtkPolyDataConnectivityFilter()
    connectFilter.SetExtractionModeToLargestRegion()
    connectFilter.SetInputData(filter.GetOutput())
    connectFilter.Update()

    return connectFilter.GetOutput()
Exemple #20
0
def get_largest_connected_polydata(poly):
    connectivity = vtk.vtkPolyDataConnectivityFilter()
    connectivity.SetInputData(poly)
    connectivity.SetExtractionModeToLargestRegion()
    connectivity.Update()
    poly = connectivity.GetOutput()
    return poly
 def __init__(self):
     """Setup the pipeline.
     """
     self.reader = vtkSTLReader()
     
     self.cutter = vtkCutter()
     self.cutter.SetInputConnection(self.reader.GetOutputPort())
     
     self.regionPicker = vtkPolyDataConnectivityFilter()
     self.regionPicker.SetInputConnection(self.cutter.GetOutputPort())
     self.regionPicker.SetExtractionModeToClosestPointRegion()
     
     self.scaler = vtkTransformPolyDataFilter()
     self.scaler.SetInputConnection(self.regionPicker.GetOutputPort())
     
     self.GetFileName = self.reader.GetFileName
     self.SetFileName = self.reader.SetFileName
     
     self.GetOutputPort = self.scaler.GetOutputPort
     self.GetOutput = self.scaler.GetOutput
     self.Update = self.scaler.Update
     
     self.iolet = None
     self.fileUnitLength = None
     
     return
def test_connectivity(pd):
    conn = vtk.vtkPolyDataConnectivityFilter()
    conn.SetInput(pd)
    conn.SetExtractionModeToAllRegions()
    conn.Update()

    return conn.GetNumberOfExtractedRegions()
Exemple #23
0
def vtp2vtuPolyhedron(vtpObject):
    """
    Convert a Polydata to individual polyhedron cells in a vtu grid
    """
    # Find individual
    conFilt = vtk.vtkPolyDataConnectivityFilter()
    conFilt.SetInputData(vtpObject)
    conFilt.SetExtractionMode(5)
    conFilt.SetColorRegions(1)
    conFilt.Update()
    #
    phAppFilt = vtk.vtkAppendFilter()
    # phAppFilt.MergePointsOn()
    for nr in np.arange(conFilt.GetNumberOfExtractedRegions()):
        thresh = vtk.vtkThreshold()
        thresh.SetInputConnection(conFilt.GetOutputPort())
        thresh.ThresholdBetween(nr - .1, nr + .1)
        thresh.SetInputArrayToProcess(1, 0, 0, 0, "Regionid")
        thresh.Update()
        # Convert to a Polyhedron and add to the append filter
        phAppFilt.AddInputData(
            makePolyhedronCell(vtu2vtp(thresh.GetOutput()), returnGrid=True))
    phAppFilt.Update()
    # Return the grid
    return phAppFilt.GetOutput()
  def vtkCreateIsoContour(self , config = 'MARCHINGCUBES'):
     """ Fonction pour la creation de l'isocontour pour une valeur de seuillage"""
     
     #-----------------------------------------
     # Creation de l isocontour
     #-----------------------------------------
     if config == 'CONTOUR' :
        self.aneurysmExtractor = vtk.vtkContourFilter()
     if config == 'MARCHINGCUBES' :
        self.aneurysmExtractor = vtk.vtkMarchingCubes()
        
     self.aneurysmExtractor.SetInputConnection(self.vtkVolumBlur.GetOutputPort())
     self.aneurysmExtractor.SetValue(0, self.valSeuil)
     
     self.aneurysmExtractor.ComputeNormalsOn()
        
     self.aneurysmTriangleFilter = vtk.vtkTriangleFilter()
     self.aneurysmTriangleFilter.SetInputConnection(self.aneurysmExtractor.GetOutputPort())
 
     self.aneurysmCleanFilter = vtk.vtkCleanPolyData()
     self.aneurysmCleanFilter.SetInputConnection(self.aneurysmTriangleFilter.GetOutputPort()) 
     
     self.aneurysmConnectFilter = vtk.vtkPolyDataConnectivityFilter()
     self.aneurysmConnectFilter.SetExtractionModeToLargestRegion()
     self.aneurysmConnectFilter.ScalarConnectivityOff() 
     self.aneurysmConnectFilter.SetInputConnection(self.aneurysmCleanFilter.GetOutputPort()) 
     
     self.aneurysmNormals = vtk.vtkPolyDataNormals()
     self.aneurysmNormals.SetInputConnection(self.aneurysmConnectFilter.GetOutputPort())
     self.aneurysmNormals.SetFeatureAngle(60.0)
     self.aneurysmNormals.ComputeCellNormalsOn()
     self.aneurysmNormals.ComputePointNormalsOn()
     self.aneurysmNormals.ConsistencyOn()
     self.aneurysmNormals.AutoOrientNormalsOn()
     self.aneurysmNormals.Update()
Exemple #25
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: No Image.')

        extent = self.Image.GetExtent()
        translateExtent = vtk.vtkImageTranslateExtent()
        translateExtent.SetInputData(self.Image)
        translateExtent.SetTranslation(-extent[0],-extent[2],-extent[4])
        translateExtent.Update()

        if (self.ArrayName != ''):
            translateExtent.GetOutput().GetPointData().SetActiveScalars(self.ArrayName)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputConnection(translateExtent.GetOutputPort())
        marchingCubes.SetValue(0,self.Level)
        marchingCubes.Update()

        self.Surface = marchingCubes.GetOutput()

        if self.Connectivity == 1:
            connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
            connectivityFilter.SetInputData(self.Surface)
            connectivityFilter.SetExtractionModeToLargestRegion()
            connectivityFilter.Update()
            self.Surface = connectivityFilter.GetOutput()
Exemple #26
0
    def createVTKisocontour(self, dataVTK, isovalue, filename, poidsVTK, s):
        "Creation des isocontours"

        # Creation des contours
        contours = vtk.vtkContourFilter()
        contours.SetInput(dataVTK)
        #~ contours.GenerateValues(nb_isocontour, values.min(), values.max())
        contours.SetValue(0, isovalue)
        contours.Update()

        # Gestion des contours
        connectFilter = vtk.vtkPolyDataConnectivityFilter()
        connectFilter.SetInputConnection(contours.GetOutputPort())
        connectFilter.ScalarConnectivityOff()
        connectFilter.ColorRegionsOn()
        connectFilter.SetExtractionModeToSpecifiedRegions()
        connectFilter.AddSpecifiedRegion(0)
        connectFilter.Update()

        if connectFilter.GetNumberOfExtractedRegions() == 1:

            # Recuperation des ponderations
            probe = vtk.vtkProbeFilter()
            probe.SetInputConnection(connectFilter.GetOutputPort())
            probe.SetSource(poidsVTK)
            probe.Update()
            ponderation = VN.vtk_to_numpy(
                probe.GetOutput().GetPointData().GetArray('Value'))

            numPoints = probe.GetOutput().GetNumberOfPoints(
            )  # get the number of points on the line
            #intialise the points on the line
            x = np.zeros(numPoints)
            y = np.zeros(numPoints)
            z = np.zeros(numPoints)
            pts = np.zeros((numPoints, 3))
            #get the coordinates of the points on the line
            for i in range(numPoints):
                x[i], y[i], z[i] = probe.GetOutput().GetPoint(i)
            pts[:, 0] = x
            pts[:, 1] = y
            pts[:, 2] = z

            # Organisation des noeuds
            pts, ponderation = self.orderingNodesOnLine(pts, ponderation)
            #~ plot3Dcontour(pts)

            # scaling ponderation
            ponderation, seuil = self.seuilMass(ponderation, s)

            # Estimation du centre de gravite
            center = self.getCdGfromContour(pts, ponderation, seuil)

            # Ecriture du contour pour post traitement
            #~ self.writeVTKContour(pts, filename)

        else:
            center = np.array([0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0])

        return center, connectFilter.GetOutput()
    def Execute(self):

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

        if (self.GroupId != -1) & (self.GroupIdsArrayName!=''):
            self.Surface.GetPointData().SetActiveScalars(self.GroupIdsArrayName)

        connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
        connectivityFilter.SetInput(self.Surface)
        connectivityFilter.ColorRegionsOff()       
        connectivityFilter.SetExtractionModeToLargestRegion()
        if self.GroupId != -1:
            connectivityFilter.ScalarConnectivityOn()
            scalarRange = [self.GroupId,self .GroupId]
            connectivityFilter.SetScalarRange(scalarRange)
        connectivityFilter.Update()

        self.Surface = connectivityFilter.GetOutput()
	
      	if self.CleanOutput == 1:
      	    cleaner = vtk.vtkCleanPolyData()
      	    cleaner.SetInput(connectivityFilter.GetOutput())
      	    cleaner.Update()

            self.Surface = cleaner.GetOutput()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
Exemple #28
0
    def __init__(self):
        """Setup the pipeline.
        """
        self.reader = vtkSTLReader()

        self.cutter = vtkCutter()
        self.cutter.SetInputConnection(self.reader.GetOutputPort())

        self.regionPicker = vtkPolyDataConnectivityFilter()
        self.regionPicker.SetInputConnection(self.cutter.GetOutputPort())
        self.regionPicker.SetExtractionModeToClosestPointRegion()

        self.scaler = vtkTransformPolyDataFilter()
        self.scaler.SetInputConnection(self.regionPicker.GetOutputPort())

        self.GetFileName = self.reader.GetFileName
        self.SetFileName = self.reader.SetFileName

        self.GetOutputPort = self.scaler.GetOutputPort
        self.GetOutput = self.scaler.GetOutput
        self.Update = self.scaler.Update

        self.iolet = None
        self.fileUnitLength = None

        return
    def load_nii_save_stl(self,
                          in_name='data/skull.nii',
                          out_name='data/skull.stl',
                          threshold=100.0):
        print "Function: load_nii_save_stl"
        print "Para1: input file name (.nii file)\nPara2: output file name (.stl file)"

        reader = vtk.vtkNIFTIImageReader()
        reader.SetFileName(in_name)
        reader.Update()
        image = reader.GetOutput()

        surface = vtk.vtkMarchingCubes()
        surface.SetInputData(image)
        surface.SetValue(0, threshold)
        surface.Update()
        # extract largest connectivity area
        confilter = vtk.vtkPolyDataConnectivityFilter()
        confilter.SetInputData(surface.GetOutput())
        confilter.SetExtractionModeToLargestRegion()
        confilter.Update()

        skull = confilter.GetOutput()

        writer = vtk.vtkSTLWriter()
        writer.SetFileName(out_name)
        writer.SetInputData(skull)
        writer.Update()
        print out_name, '  saved!'
Exemple #30
0
    def loadSurface(self, fileName):
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(fileName)
        reader.Update()

        # Take the largest connected component
        connectFilter = vtk.vtkPolyDataConnectivityFilter()
        connectFilter.SetInputConnection(reader.GetOutputPort())
        connectFilter.SetExtractionModeToLargestRegion()
        connectFilter.Update()

        self.vesselPolyData = connectFilter.GetOutput()

        # Compute normals
        self.vesselNormals = vtk.vtkPolyDataNormals()
        self.vesselNormals.SetInputData(self.vesselPolyData)

        # Mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(self.vesselNormals.GetOutputPort())

        # Actor for vessels
        self.vessels = vtk.vtkActor()
        self.vessels.SetMapper(mapper)
        prop = self.vessels.GetProperty()
        prop.SetColor(vtk.vtkColor3d(hexCol("#517487")))  # 25% lighter

        # Assign actor to the renderer
        prop.SetOpacity(0.35)
        self.planeWidget[0].GetDefaultRenderer().AddActor(self.vessels)

        for i in range(3):
            self.vtk_widgets[i].InitializeContour(self.vesselNormals)
        self.Render()
Exemple #31
0
def marchingSquares(img, iso=0.0, mode='center'):
    s = img.shape
    alg = vtk.vtkMarchingSquares()

    sp = VTKNumpytoSP(img)

    alg.SetInputData(sp)
    alg.SetValue(0, iso)
    alg.Update()
    pds = alg.GetOutput()

    a = vtk.vtkPolyDataConnectivityFilter()
    a.SetInputData(pds)

    if mode == 'center':
        a.SetExtractionModeToClosestPointRegion()
        a.SetClosestPoint(float(s[0]) / 2, float(s[1]) / 2, 0.0)

    elif mode == 'all':
        a.SetExtractionModeToAllRegions()

    a.Update()
    pds = a.GetOutput()

    if pds.GetPoints() is None:
        return np.asarray([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]])
    else:
        pds = VTKPDPointstoNumpy(pds)
        if len(pds) <= 1:
            return np.asarray([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]])
        return pds
Exemple #32
0
def separate_disconnected_polydata(poly):
    """
    Separate disconnected PolyData into separate PolyData objects

    Args:
        poly: VTK PolyData
    Returns:
        components: list of VTK PolyData objects
    """
    cc_filter = vtk.vtkPolyDataConnectivityFilter()
    cc_filter.SetInputData(poly)
    cc_filter.SetExtractionModeToSpecifiedRegions()
    components = list()
    idx = 0
    while True:
        cc_filter.AddSpecifiedRegion(idx)
        cc_filter.Update()

        component = vtk.vtkPolyData()
        component.DeepCopy(cc_filter.GetOutput())
        component = clean_polydata(component, 0.)
        # Make sure we got something
        if component.GetNumberOfCells() <= 0:
            break
        components.append(component)
        cc_filter.DeleteSpecifiedRegion(idx)
        idx += 1
    return components
Exemple #33
0
def marchingSquares(img, iso=0.0, mode='center', asNumpy=True):
    alg = vtk.vtkMarchingSquares()

    if asNumpy:
        sp = VTKNumpytoSP(img)
    else:
        sp = img
    alg.SetInputData(sp)
    alg.SetValue(0, iso)
    alg.Update()
    pds = alg.GetOutput()

    a = vtk.vtkPolyDataConnectivityFilter()
    a.SetInputData(pds)

    if mode == 'center':
        a.SetExtractionModeToClosestPointRegion()
        a.SetClosestPoint(0.0, 0.0, 0.0)

    elif mode == 'all':
        a.SetExtractionModeToAllRegions()

    a.Update()
    pds = a.GetOutput()

    return pds
Exemple #34
0
def SplitDisconectedParts(polydata):
    """
    """
    conn = vtk.vtkPolyDataConnectivityFilter()
    conn.SetInputData(polydata)
    conn.SetExtractionModeToAllRegions()
    conn.Update()

    nregions = conn.GetNumberOfExtractedRegions()

    conn.SetExtractionModeToSpecifiedRegions()
    conn.Update()

    polydata_collection = []

    # Update progress value in GUI
    progress = nregions -1
    if progress:
        UpdateProgress = vu.ShowProgress(progress)

    for region in xrange(nregions):
        conn.InitializeSpecifiedRegionList()
        conn.AddSpecifiedRegion(region)
        conn.Update()

        p = vtk.vtkPolyData()
        p.DeepCopy(conn.GetOutput())

        polydata_collection.append(p)
        if progress:
            UpdateProgress(region, _("Splitting disconnected regions..."))

    return polydata_collection
Exemple #35
0
def labelregions(polydata):
    """Label connected regions by assigning a 'RegionId' as pointdata."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()
    return connect.GetOutput()
Exemple #36
0
def extractclosestpointregion(polydata, point=[0, 0, 0]):
    """Extract region closest to specified point."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToClosestPointRegion()
    connect.SetClosestPoint(point)
    connect.Update()
    return connect.GetOutput()
Exemple #37
0
def extractclosestpointregion(polydata, point=[0, 0, 0]):
    """Extract region closest to specified point."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToClosestPointRegion()
    connect.SetClosestPoint(point)
    connect.Update()
    return connect.GetOutput()
Exemple #38
0
def extract_surface(poly):
    connectivity = vtk.vtkPolyDataConnectivityFilter()
    connectivity.SetInputData(poly)
    connectivity.ColorRegionsOn()
    connectivity.SetExtractionModeToAllRegions()
    connectivity.Update()
    poly = connectivity.GetOutput()
    return poly
Exemple #39
0
def labelregions(polydata):
    """Label connected regions by assigning a 'RegionId' as pointdata."""
    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInput(polydata)
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()
    return connect.GetOutput()
 def extractLargestConnectedComponent(inputModel, outputModel):
   """Extract the largest connected portion of a surface model.
   """
   connect = vtk.vtkPolyDataConnectivityFilter()
   connect.SetInputData(inputModel.GetPolyData())
   connect.SetExtractionModeToLargestRegion()
   connect.Update()
   outputModel.SetAndObservePolyData(connect.GetOutput())
Exemple #41
0
def extractNearestPoly(poly, x, y, z):
    # mergeDuplicateNodes may be needed before applying this filter
    connectivity = vtk.vtkPolyDataConnectivityFilter()
    connectivity.SetInput(poly)
    connectivity.SetExtractionModeToClosestPointRegion()
    connectivity.SetClosestPoint(x, y, z)
    connectivity.Update()
    return connectivity.GetOutput()
Exemple #42
0
    def loadSurface(self, fileName, index=0):
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(fileName)
        reader.Update()

        # Take the largest connected component
        connectFilter = vtk.vtkPolyDataConnectivityFilter()
        connectFilter.SetInputConnection(reader.GetOutputPort())
        connectFilter.SetExtractionModeToLargestRegion()
        connectFilter.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInputConnection(connectFilter.GetOutputPort())

        # 3D viewer

        # Mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(normals.GetOutputPort())

        # Actor for vessels
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        prop = actor.GetProperty()

        if index == 0:
            # Veins
            prop.SetColor(vtk.vtkColor3d(hexCol("#517487")))  # 25% lighter
        else:
            # Liver
            prop.SetColor(vtk.vtkColor3d(hexCol("#873927")))

        self.vessels = actor

        # Assign actor to the renderer
        prop.SetOpacity(0.35)
        self.viewer3D.planeWidgets[0].GetDefaultRenderer().AddActor(actor)

        # 2D Views
        polyData = normals.GetOutput()

        self.appendFilter.AddInputData(polyData)
        self.appendFilter.Update()

        # TODO: Make this work if read before US
        for i in range(self.stackCT.count()):
            self.stackCT.widget(i).InitializeContours(self.appendFilter,
                                                      color=pink)

        for i in range(len(self.viewUS)):
            self.viewUS[i].InitializeContours(self.appendFilter)
            # TODO: Assign instead product of two identity matrices
            self.viewUS[i].SetTransform(self.alignment)

        if self.vessels is not None:
            self.vessels.SetUserTransform(self.misAlignment)

        self.Render()
def computeComponents(vertices, faces):
    pts, tris = arrayToPolydata(vertices, faces)
    polys = vtk.vtkPolyData()
    polys.SetPoints(pts)
    polys.SetPolys(tris)
    polys.Update()
    
    cleanFilter = vtk.vtkCleanPolyData()
    #cleanFilter.PointMergingOff()
    cleanFilter.ConvertStripsToPolysOff()
    cleanFilter.ConvertPolysToLinesOff()
    cleanFilter.ConvertLinesToPointsOff()
    cleanFilter.SetInput(polys)
    cleanFilter.Update()
    
    connFilter = vtk.vtkPolyDataConnectivityFilter()
    connFilter.ScalarConnectivityOff()
    connFilter.SetExtractionModeToAllRegions()
    connFilter.SetInput(cleanFilter.GetOutput())
    connFilter.Update()
    
    nregions = connFilter.GetNumberOfExtractedRegions()
    print "Regions extracted: %d" % (nregions)
    
    components = []
    for i in range(nregions):
        connFilter = vtk.vtkPolyDataConnectivityFilter()
        connFilter.ScalarConnectivityOff()
        connFilter.SetExtractionModeToSpecifiedRegions()
        connFilter.AddSpecifiedRegion(i)
        connFilter.SetInput(cleanFilter.GetOutput())
        connFilter.Update()
    
        cFilter = vtk.vtkCleanPolyData()
#        cFilter.ConvertStripsToPolysOff()
#        cFilter.ConvertPolysToLinesOff()
#        cFilter.ConvertLinesToPointsOff()
        cFilter.SetInput(connFilter.GetOutput())
        cFilter.Update()
    
        v,f = polydataToArray(cFilter.GetOutput())
        components.append([v,f])
        
    return components
Exemple #44
0
def connectivityFilter(polyData):
    connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
    connectivityFilter.SetInputConnection(polyData.GetOutputPort())
    connectivityFilter.SetExtractionModeToAllRegions()
    connectivityFilter.ColorRegionsOn()
    connectivityFilter.Update()
    global n_regions
    n_regions = connectivityFilter.GetNumberOfExtractedRegions()
    print ("number of regions extracted: " + str(n_regions) + "\n")
    return connectivityFilter
Exemple #45
0
  def applyFilters(self, state):

    surface = None
    surface = state.inputModelNode.GetPolyDataConnection()

    if state.decimation:
      triangle = vtk.vtkTriangleFilter()
      triangle.SetInputConnection(surface)
      decimation = vtk.vtkDecimatePro()
      decimation.SetTargetReduction(state.reduction)
      decimation.SetBoundaryVertexDeletion(state.boundaryDeletion)
      decimation.PreserveTopologyOn()
      decimation.SetInputConnection(triangle.GetOutputPort())
      surface = decimation.GetOutputPort()

    if state.smoothing:
      if state.smoothingMethod == "Laplace":
        smoothing = vtk.vtkSmoothPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.laplaceIterations)
        smoothing.SetRelaxationFactor(state.laplaceRelaxation)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()
      elif state.smoothingMethod == "Taubin":
        smoothing = vtk.vtkWindowedSincPolyDataFilter()
        smoothing.SetBoundarySmoothing(state.boundarySmoothing)
        smoothing.SetNumberOfIterations(state.taubinIterations)
        smoothing.SetPassBand(state.taubinPassBand)
        smoothing.SetInputConnection(surface)
        surface = smoothing.GetOutputPort()

    if state.normals:
      normals = vtk.vtkPolyDataNormals()
      normals.AutoOrientNormalsOn()
      normals.SetFlipNormals(state.flipNormals)
      normals.SetSplitting(state.splitting)
      normals.SetFeatureAngle(state.featureAngle)
      normals.ConsistencyOn()
      normals.SetInputConnection(surface)
      surface = normals.GetOutputPort()

    if state.cleaner:
      cleaner = vtk.vtkCleanPolyData()
      cleaner.SetInputConnection(surface)
      surface = cleaner.GetOutputPort()

    if state.connectivity:
      connectivity = vtk.vtkPolyDataConnectivityFilter()
      connectivity.SetExtractionModeToLargestRegion()
      connectivity.SetInputConnection(surface)
      surface = connectivity.GetOutputPort()

    state.outputModelNode.SetPolyDataConnection(surface)
    return True
Exemple #46
0
def concomp(opts, argv):
	p = nv.readVTK(argv[0])
	c = vtk.vtkPolyDataConnectivityFilter()
	c.SetInput(p)
	c.SetExtractionModeToLargestRegion()
	c.Update()
	d = vtk.vtkCleanPolyData()
	d.SetInput(c.GetOutput())
	d.Update()
	p = d.GetOutput()
	nv.writeVTK(argv[1],p)
    def PickCallback(self, obj):
        picker = vtk.vtkPointPicker()
        eventPosition = self.vmtkRenderer.RenderWindowInteractor.GetEventPosition()
        result = picker.Pick(float(eventPosition[0]),float(eventPosition[1]),0.0,self.vmtkRenderer.Renderer)
        # We treat result as a boolean value (which can also be nonetype if a selection outside the render windw is made)
        # If the value of result is False or None, then an invalid actor was selected in the scene. 
        if result is None:
            return
        elif result == 0:
            return

        # find the value of "RegionId" stored in the vtkPolyData PointData array. This is a unique number
        # which is generated for each connected surface point by the allRegionConnectivity 
        # vtkPolyDataConnectivityFilter function
        pickedPointId = picker.GetPointId()
        self.CurrentPickedActor = picker.GetActor()
        self.CurrentPickedPolyData = self.CurrentPickedActor.GetMapper().GetInputAsDataSet()
        regionId = self.CurrentPickedPolyData.GetPointData().GetArray('RegionId').GetValue(pickedPointId)
        
        # extract only the desired region Id from the dataset
        isolatedFilter = vtk.vtkPolyDataConnectivityFilter()
        isolatedFilter.SetInputData(self.CurrentPickedPolyData)
        isolatedFilter.SetExtractionModeToSpecifiedRegions()
        isolatedFilter.AddSpecifiedRegion(regionId)

        # remove all points not in the extracted cells
        cleanedFilter = vtk.vtkCleanPolyData()
        cleanedFilter.SetInputConnection(isolatedFilter.GetOutputPort())
        cleanedFilter.Update()

        outputSurface = cleanedFilter.GetOutput()

        # create a new mapper and actor for this extracted surface object
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(outputSurface)
        mapper.ScalarVisibilityOff()
        mapper.Update()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(1.0, 0.0, 0.0) # red color
        actor.GetProperty().SetDiffuse(1.0)
        actor.GetProperty().SetSpecular(0.2)
        actor.GetProperty().SetRepresentationToSurface()
        actor.GetProperty().EdgeVisibilityOff()

        # place the extracted surface object's actor instance in the necessary render windows
        # and lists to log it's selection        
        self.PastPickedActorList.append(actor)
        self._OutputPolyDataList.append(outputSurface)
        self.vmtkRenderer.Renderer.AddActor(actor)
        self.vmtkRenderer.RenderWindow.Render()
        return
    def colorSurfaceRegions(self):
        self.PrintLog("Coloring surface regions.")

        connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
        connectivityFilter.SetInputData(self.DoubleSurface)
        connectivityFilter.ColorRegionsOn()
        connectivityFilter.SetExtractionModeToAllRegions()
        connectivityFilter.Update()

        assert connectivityFilter.GetNumberOfExtractedRegions() == 2

        self.ColoredSurface = connectivityFilter.GetOutput()
 def GetTargetSurface(self):
     """Get the connected part of the clipped surface that lies
     closest to the first clipping plane's origin, using
     vtkPolyDataConnectivityFilter.
     
     """
     filter = vtk.vtkPolyDataConnectivityFilter()
     filter.SetExtractionModeToClosestPointRegion()
     filter.SetClosestPoint(self.Planes[0].GetOrigin())
     filter.SetInput(self.Clipped)
     filter.Update()
     self.Output = filter.GetOutput()
     return
Exemple #50
0
def SelectLargestPart(polydata):
    """
    """
    UpdateProgress = vu.ShowProgress(1)
    conn = vtk.vtkPolyDataConnectivityFilter()
    conn.SetInputData(polydata)
    conn.SetExtractionModeToLargestRegion()
    conn.AddObserver("ProgressEvent", lambda obj, evt:
                  UpdateProgress(conn, "Getting largest part..."))
    conn.Update()

    result = vtk.vtkPolyData()
    result.DeepCopy(conn.GetOutput())
    return result
Exemple #51
0
    def Execute(self):

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

        if (self.GroupId != -1) and (self.GroupIdsArrayName!=''):
            self.Surface.GetPointData().SetActiveScalars(self.GroupIdsArrayName)

        barycenter = [0.0,0.0,0.0]
        if self.Method == 'closest' and self.ClosestPoint == None:
            n = self.ReferenceSurface.GetNumberOfPoints()
            for i in range(n):
                point = self.ReferenceSurface.GetPoint(i)
                barycenter[0] += point[0]
                barycenter[1] += point[1]
                barycenter[2] += point[2]
            barycenter[0] /= n
            barycenter[1] /= n
            barycenter[2] /= n

        connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
        connectivityFilter.SetInputData(self.Surface)
        connectivityFilter.ColorRegionsOff()       
        if self.Method == 'largest':
            connectivityFilter.SetExtractionModeToLargestRegion()
        elif self.Method == 'closest':
            connectivityFilter.SetExtractionModeToClosestPointRegion()
            if self.ClosestPoint:
                connectivityFilter.SetClosestPoint(self.ClosestPoint)
            else:
                connectivityFilter.SetClosestPoint(barycenter)
        elif self.Method == 'all':
            connectivityFilter.SetExtractionModeToAllRegions()
            connectivityFilter.ColorRegionsOn()

        if self.GroupId != -1:
            connectivityFilter.ScalarConnectivityOn()
            scalarRange = [self.GroupId,self.GroupId]
            connectivityFilter.SetScalarRange(scalarRange)
        connectivityFilter.Update()

        self.Surface = connectivityFilter.GetOutput()

        if self.CleanOutput == 1:
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputConnection(connectivityFilter.GetOutputPort())
            cleaner.Update()

            self.Surface = cleaner.GetOutput()
def GetWholeConnectedRegions(poly, coord):
    # for each of the connected regions, make a (likely non-convex)
    # whole polygon, divided at the self intersections.
    # for small image, reduces by 4.975
    # big image improves by 3.918
    numCells = poly.GetNumberOfCells()
    #print "numcells before", numCells
    connectivity = vtk.vtkPolyDataConnectivityFilter()
    connectivity.SetInput(poly)
    connectivity.SetExtractionModeToAllRegions()
    connectivity.Update()
    numRegions = connectivity.GetNumberOfExtractedRegions()
    connectivity.SetExtractionModeToSpecifiedRegions()
    featureEdges = vtk.vtkFeatureEdges()
    featureEdges.BoundaryEdgesOn()

    numResult = 0
    for r in range(numRegions):
        numResult += 1
        connectivity.InitializeSpecifiedRegionList()
        connectivity.AddSpecifiedRegion(r)
        region = connectivity.GetOutput()
        region.Update()
        #print "region has ", region.GetNumberOfCells(), " cells"
        featureEdges.SetInput(region)
        edges = featureEdges.GetOutput()
        edges.Update()
        edges.BuildLinks(0)
        #print "edges has", edges.GetNumberOfCells(), " cells"
        numCells = edges.GetNumberOfCells()
        # for i in xrange(numCells):
        #     print edges.GetCell(i).GetPoints().GetPoint(0), edges.GetCell(i).GetPoints().GetPoint(1)
        # edges not given in order, we need to traverse
        # first look for self intersections
        points = edges.GetPoints()
        selfIntersections = []
        cellIds = vtk.vtkIdList()
        for p in range(points.GetNumberOfPoints()):
            edges.GetPointCells(p,cellIds)
            if cellIds.GetNumberOfIds() == 4:
                selfIntersections.append(p)
                numResult += 1
        #print selfIntersections
##         if not selfIntersections:
##             selfIntersections.append(edges.GetCell(0).GetPointIds().GetId(0))
        
        # for now just return number of cells in result
    return numResult
Exemple #53
0
def countregions(polydata):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

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

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.Update()
    return connect.GetNumberOfExtractedRegions()
Exemple #54
0
def CloseSurface( shape, output ):
    """
    Closes holes in a surface with a flat cover

    shape vtkPolyData: input shape
    output vtkPolyData: output shape

    Return nothing.
    """
    fe = vtk.vtkFeatureEdges()
    fe.SetInputData( shape )
    fe.BoundaryEdgesOn()
    fe.NonManifoldEdgesOff()
    fe.FeatureEdgesOff()
    fe.ManifoldEdgesOff()
    fe.Update()

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputData(fe.GetOutput())
    connect.Update()

    ncontours = connect.GetNumberOfExtractedRegions()

    append = vtk.vtkAppendPolyData()
    append.AddInput(shape)


    for i in range(ncontours):
        connect.AddSpecifiedRegion(i)
        connect.SetExtractionModeToSpecifiedRegions()
        connect.Update()
        edges = connect.GetOutput()
        cover = vtk.vtkPolyData()
        GenerateHoleCover(edges, cover)

        append.AddInput(cover)
        connect.DeleteSpecifiedRegion(i)


    append.Update()


    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputData(append.GetOutput())
    cleaner.Update()

    output.DeepCopy(cleaner.GetOutput())
Exemple #55
0
def extractclosestpointregion(polydata, point=[0, 0, 0]):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

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

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

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

    connect = vtk.vtkPolyDataConnectivityFilter()
    connect.SetInputConnection(cleaner.GetOutputPort())
    connect.SetExtractionModeToAllRegions()
    connect.ColorRegionsOn()
    connect.Update()
    surface = pointthreshold(connect.GetOutput(),'RegionId',float(regionid),float(regionid))
    return surface
Exemple #57
0
def CreateSurface(input, midPoint):
    connectivityFilter = vtk.vtkPolyDataConnectivityFilter()
    connectivityFilter.SetInput(input)
    connectivityFilter.SetClosestPoint(midPoint)
    connectivityFilter.SetExtractionModeToClosestPointRegion()
    connectivityFilter.Update()
    contour = connectivityFilter.GetOutput()
    numberOfContourPoints = contour.GetNumberOfPoints()
    surf = vtk.vtkPolyData()
    sectionPoints = vtk.vtkPoints()
    sectionCellArray = vtk.vtkCellArray() 
    sectionCellArray.InsertNextCell(numberOfContourPoints)
    for j in range(numberOfContourPoints):
        point = contour.GetPoint(j)
        sectionPoints.InsertNextPoint(point)
        sectionCellArray.InsertCellPoint(j)
    sectionCellArray.InsertCellPoint(0)
    surf.SetPoints(sectionPoints)
    surf.SetPolys(sectionCellArray)
    return surf
Exemple #58
0
    def __init__(self, module_manager):

        # call parent constructor
        ModuleBase.__init__(self, module_manager)

        self._polyDataConnect = vtk.vtkPolyDataConnectivityFilter()
        # we're not going to use this feature just yet
        self._polyDataConnect.ScalarConnectivityOff()
        #
        self._polyDataConnect.SetExtractionModeToPointSeededRegions()

        module_utils.setup_vtk_object_progress(self, self._polyDataConnect,
                                           'Finding connected surfaces')

        # default is point seeded regions (we store zero-based)
        self._config.extraction_mode = 0
        self._config.colour_regions = 0

        config_list = [
                ('Extraction mode:', 'extraction_mode', 'base:int',
                 'choice', 
                 'What kind of connected regions should be extracted.',
                 [EMODES[i] for i in range(1,7)]),
                ('Colour regions:', 'colour_regions', 'base:int',
                 'checkbox', 
                 'Should connected regions be coloured differently.')
                ]
        
        # and the mixin constructor
        ScriptedConfigModuleMixin.__init__(
            self, config_list,
            {'Module (self)' : self,
             'vtkPolyDataConnectivityFilter' : self._polyDataConnect})

        # we'll use this to keep a binding (reference) to the passed object
        self._input_points = None
        # this will be our internal list of points
        self._seedIds = []

        self.sync_module_logic_with_config()
Exemple #59
0
def extractlargestregion(polydata):
    # NOTE: preventive measures: clean before connectivity filter
    # to avoid artificial regionIds
    # It slices the surface down the middle
    surfer = vtk.vtkDataSetSurfaceFilter()
    surfer.SetInputData(polydata)
    surfer.Update()

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

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

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