def Centerline_Extraction(path_reader,
                          path_writer,
                          coeff_smooth=0.001,
                          nb_iterations=50):

    #READ THE SURFACE
    print(" ---> Reading Mesh Closed STL surface")
    myReader = vmtkscripts.vmtkSurfaceReader()
    myReader.InputFileName = path_reader
    myReader.Format = 'stl'
    myReader.Execute()

    print("---> Computing Centerline")
    myCenterline = vmtkscripts.vmtkCenterlines()
    myCenterline.Surface = myReader.Surface
    myCenterline.AppendEndPoints = 1
    myCenterline.Resampling = 1
    myCenterline.ResamplingStepLength = 0.2
    myCenterline.Execute()

    myCenterlineSmoother = vmtkscripts.vmtkCenterlineSmoothing()
    myCenterlineSmoother.Centerlines = myCenterline.Centerlines
    myCenterlineSmoother.SmoothingFactor = coeff_smooth
    myCenterlineSmoother.NumberOfSmoothingIterations = nb_iterations
    myCenterlineSmoother.Execute()

    #WRITE TO STL FILE
    print(" ---> Writing results to VTP file ")
    myWriter = vmtkscripts.vmtkSurfaceWriter()
    myWriter.Surface = myCenterlineSmoother.Centerlines
    myWriter.OutputFileName = path_writer
    #myWriter.Format = 'vtp'
    myWriter.Execute()
Exemple #2
0
def vmtkcenterlines(surface, endpoints=0, interactive=False,
                    sourcepoints=[0, 0, 0], targetpoints=[0, 0, 0]):
    """Compute centerlines of a vascular geometry.

    Args:
        surface: Surface mesh of a vascular geometry.
        endpoints (bool): Include endpoints. By construction, centerlines do
            not reach the source/targetpoints. endpoints=1 bridges the
            start/end of the centerlines to the source/targetpoints.
        interactive (bool): Select source/targetpoints interactively. This
            pops up a VTK window. Follow instructions in terminal.
        sourcepoints: Give barycenters of sourcepoints as in '[0.0, 1.0, 2.0]'.
            In case of multiple sourcepoints, append the lists of each three
            coordinates as in '[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]'.
        targetpoints: Give barycenters of targetpoints following same notation
            as with sourcepoints.

    Returns:
        Centerlines. Each cell of the centerlines polydata is a centerline from
        one of the sourcepoints to one of the targetpoints.

    """
    centerliner = vmtkscripts.vmtkCenterlines()
    centerliner.Surface = surface
    centerliner.AppendEndPoints = endpoints
    if interactive:
        centerliner.SeedSelectorName = 'pickpoint'
    else:
        centerliner.SeedSelectorName = 'pointlist'
        centerliner.SourcePoints = sourcepoints
        centerliner.TargetPoints = targetpoints
    centerliner.Execute()
    return centerliner.Centerlines
def vmtkcenterlinesinteractive(surface, endpoints=0):
    computer = vmtkscripts.vmtkCenterlines()
    computer.Surface = surface
    computer.AppendEndPoints = endpoints
    computer.SeedSelectorName = 'pickpoint'
    computer.Execute()
    return computer.Centerlines
    def extract_center_lines(self, params):
        """ Extract the centerlines of a surface.

           The centerline geometry is returned as a vtkPolyData object.
        """
        ## Get the centers of the inlet and outlet surfaces. 
        self.get_inlet_outlet_centers(params)

        ## Read the surface model used for centerline calculation.
        self.logger.info("Read surface model from %s" % params.surface_model)
        surface_mesh = read_surface(params.surface_model)
        #print(surface_mesh)
        self.logger.info("Number of points in params.outlet_centers %d" % len(self.outlet_centers))

        ## Extract centerlines using vmtk.
        self.logger.info("Calculating surface centerlines ...");
        centerlines = vmtkscripts.vmtkCenterlines()
        centerlines.Surface = surface_mesh 
        centerlines.SeedSelectorName = "pointlist"
        centerlines.AppendEndPoints = 1
        centerlines.SourcePoints = self.inlet_center
        centerlines.TargetPoints = self.outlet_centers
        centerlines.Execute()
        self.geometry = centerlines.Centerlines
        self.logger.info("The surface centerlines have been calculated.");

        # Write outlet face names.
        self.write_outlet_face_names(params)
def vmtk_compute_centerlines(end_point,
                             inlet,
                             method,
                             outlet,
                             pole_ids,
                             resampling_step,
                             surface,
                             voronoi,
                             flip_normals=False,
                             cap_displacement=None,
                             delaunay_tolerance=None,
                             simplify_voronoi=False):
    """
    Wrapper for vmtkCenterlines.
    compute centerlines from a branching tubular surface. Seed points can be interactively selected on the surface,
    or specified as the barycenters of the open boundaries of the surface.

    Args:
        end_point (int): Toggle append open profile barycenters to centerlines
        surface (vktPolyData): Surface model
        voronoi (vtkPolyData): Voronoi diagram based on previous centerlines (Optional)
        inlet (ndarray): List of source point coordinates
        method (str): Seed point selection method
        outlet (ndarray): List of target point coordinates
        pole_ids (ndarray): Pole ID list of Voronoi diagram (Optional)
        resampling_step (float): Resampling step
        flip_normals (float): Flip normals after outward normal computation
        cap_displacement (float): Displacement of the center points of caps at open profiles along their normals
        delaunay_tolerance (float): Tolerance for evaluating coincident points during Delaunay tessellation
        simplify_voronoi (bool): Toggle simplification of Voronoi diagram

    Returns:

    """
    centerlines = vmtkscripts.vmtkCenterlines()
    centerlines.Surface = surface
    centerlines.SeedSelectorName = method
    centerlines.AppendEndPoints = end_point
    centerlines.Resampling = 1
    centerlines.ResamplingStepLength = resampling_step
    centerlines.SourcePoints = inlet
    centerlines.TargetPoints = outlet

    if voronoi is not None and pole_ids is not None:
        centerlines.VoronoiDiagram = voronoi
        centerlines.PoleIds = pole_ids
    if flip_normals:
        centerlines.FlipNormals = 1
    if cap_displacement is not None:
        centerlines.CapDisplacement = cap_displacement
    if delaunay_tolerance is not None:
        centerlines.DelaunayTolerance = delaunay_tolerance
    if simplify_voronoi:
        centerlines.SimplifyVoronoi = 1
    centerlines.Execute()
    centerlines_output = centerlines.Centerlines

    return centerlines, centerlines_output
def vmtkcenterlinesvoronoi(surface, sourcepoints, targetpoints):
    computer = vmtkscripts.vmtkCenterlines()
    computer.Surface = surface
    computer.AppendEndPoints = 1
    computer.SeedSelectorName = 'pointlist'
    computer.SourcePoints = sourcepoints
    computer.TargetPoints = targetpoints
    computer.Execute()
    return computer.Centerlines, computer.VoronoiDiagram
Exemple #7
0
def vmtkcenterlines(surface, sourcepoints, targetpoints,endpoints=0):
    computer = vmtkscripts.vmtkCenterlines()
    computer.Surface = surface
    computer.SeedSelectorName = 'pointlist'
    computer.SourcePoints = sourcepoints
    computer.TargetPoints = targetpoints
    computer.AppendEndPoints = endpoints

    computer.Execute()
    return computer.Centerlines
def vmtkcenterlines(surface, sourcepoints, targetpoints, endpoints=0):
    computer = vmtkscripts.vmtkCenterlines()
    computer.Surface = surface
    computer.SeedSelectorName = 'pointlist'
    computer.SourcePoints = sourcepoints
    computer.TargetPoints = targetpoints
    computer.AppendEndPoints = endpoints

    # computer.DelaunayTessellationOutputFileName = 'delaunay.vtp'
    # computer.VoronoiDiagramOutputFileName = 'voronoi.vtp'
    computer.Execute()
    return computer.Centerlines
Exemple #9
0
def compute(infile, outfile):
    """
    Calls VMTK routine for centerline extraction.

    Parameters
    ----------
    infile : string
        Path to input mesh with open inlet/outlets (.stl format).
    outfile : string
        Path to output centerline (.vtp format).

    Returns
    -------
    None

    """

    # read surface
    centerlineReader = vmtkscripts.vmtkSurfaceReader()
    centerlineReader.InputFileName = infile
    centerlineReader.Execute()

    # centerline
    centerline = vmtkscripts.vmtkCenterlines()
    centerline.Surface = centerlineReader.Surface
    centerline.SeedSelectorName = 'openprofiles'
    centerline.AppendEndPoints = 1
    centerline.Execute()

    # extract branches
    branchExtractor = vmtkscripts.vmtkBranchExtractor()
    branchExtractor.Centerlines = centerline.Centerlines
    branchExtractor.Execute()

    # merge centerlines
    centerlineMerge = vmtkscripts.vmtkCenterlineMerge()
    centerlineMerge.Centerlines = branchExtractor.Centerlines
    centerlineMerge.Execute()

    # write surface
    centerlineWriter = vmtkscripts.vmtkSurfaceWriter()
    centerlineWriter.OutputFileName = outfile
    centerlineWriter.Surface = centerlineMerge.Centerlines
    centerlineWriter.Execute()
def Add_extension(path_reader,
                  path_writer,
                  extension_ratio=10,
                  target_edge_length=0.7,
                  nb_iterations=5):

    myReader = vmtkscripts.vmtkSurfaceReader()
    myReader.InputFileName = path_reader
    myReader.Format = 'stl'
    myReader.Execute()

    myCenterline = vmtkscripts.vmtkCenterlines()
    myCenterline.Surface = myReader.Surface
    myCenterline.SeedSelectorName = 'openprofiles'
    myCenterline.Execute()

    myExtension = vmtkscripts.vmtkFlowExtensions()
    myExtension.Surface = myReader.Surface
    myExtension.Centerlines = myCenterline.Centerlines
    myExtension.AdaptiveExtensionLength = 1
    myExtension.AdaptiveExtensionRadius = 1
    myExtension.ExtensionMode = "boundarynormal"
    myExtension.ExtensionRatio = extension_ratio
    myExtension.Interactive = 0
    myExtension.Execute()

    mySmoother = vmtkscripts.vmtkSurfaceSmoothing()
    mySmoother.Surface = myExtension.Surface
    mySmoother.PassBand = 0.3
    mySmoother.NumberOfIterations = 5
    mySmoother.Execute()

    myRemesh = vmtkscripts.vmtkSurfaceRemeshing()
    myRemesh.Surface = mySmoother.Surface
    myRemesh.ElementSizeMode = 'edgelength'
    myRemesh.TargetEdgeLength = target_edge_length
    myRemesh.NumberOfIterations = nb_iterations
    myRemesh.Execute()

    myWriter = vmtkscripts.vmtkSurfaceWriter()
    myWriter.Surface = myRemesh.Surface
    myWriter.OutputFileName = path_writer
    myWriter.Format = 'stl'
    myWriter.Execute()
Exemple #11
0
def vmtkcenterlines(surface,
                    endpoints=0,
                    interactive=False,
                    sourcepoints=[0, 0, 0],
                    targetpoints=[0, 0, 0]):
    """Compute centerlines of a vascular geometry.

    Args:
        surface: Surface mesh of a vascular geometry.
        endpoints (bool): Include endpoints. By construction, centerlines do
            not reach the source/targetpoints. endpoints=1 bridges the
            start/end of the centerlines to the source/targetpoints.
        interactive (bool): Select source/targetpoints interactively. This
            pops up a VTK window. Follow instructions in terminal.
        sourcepoints: Give barycenters of sourcepoints as in '[0.0, 1.0, 2.0]'.
            In case of multiple sourcepoints, append the lists of each three
            coordinates as in '[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]'.
        targetpoints: Give barycenters of targetpoints following same notation
            as with sourcepoints.

    Returns:
        Centerlines. Each cell of the centerlines polydata is a centerline from
        one of the sourcepoints to one of the targetpoints.

    """
    centerliner = vmtkscripts.vmtkCenterlines()
    centerliner.Surface = surface
    centerliner.AppendEndPoints = endpoints
    if interactive:
        centerliner.SeedSelectorName = 'pickpoint'
    else:
        centerliner.SeedSelectorName = 'pointlist'
        centerliner.SourcePoints = sourcepoints
        centerliner.TargetPoints = targetpoints
    centerliner.Execute()
    return centerliner.Centerlines
Exemple #12
0
    def Execute(self):
        # Error handling
        if self.Surface == None:
            self.PrintError(
                'Error: no input surface was supplied, ensure file exists, ensure correct environment'
            )

        # Allocate a renderer and label own renderer in use to prevent multiple renderers from being used
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        # Render and build view of the input surface
        self.SurfaceViewer = vmtkscripts.vmtkSurfaceViewer()
        self.SurfaceViewer.vmtkRenderer = self.vmtkRenderer

        self.SurfaceViewer.Surface = self.Surface
        self.SurfaceViewer.BuildView()

        # Test question in render window
        #queryStr = 'Is this the question you wanted to see? '
        #inputStr = self.YesNoInput(queryStr, self.YesNoValidator)

        # Surface smoothing, try defaults first then take user input if not adequate
        acceptableResult = 0
        response = 0
        while acceptableResult == 0:
            if response == 0:
                self.SurfaceSmoothing = vmtkscripts.vmtkSurfaceSmoothing()
                self.SurfaceSmoothing.NumberOfIterations = 100
                self.PassBand = 0.001
            elif response == 1:
                self.SurfaceViewer.Surface = self.Surface
                self.SurfaceViewer.BuildView()
                self.SurfaceSmoothing = vmtkscripts.vmtkSurfaceSmoothing()

                #Take passband from user
                queryStr = 'Please enter value for pass band (0.001 - 0.1): '
                self.SurfaceSmoothing.PassBand = float(
                    self.InputText(queryStr, self.PassBandValidator))

                #Take number of iterations from user
                queryStr = 'Please enter number of iterations (1-999): '
                self.SurfaceSmoothing.NumberOfIterations = int(
                    self.InputText(queryStr, self.IterationValidator))

            self.SurfaceSmoothing.Surface = self.Surface
            self.SurfaceSmoothing.Execute()
            self.SurfaceViewer.Surface = self.SurfaceSmoothing.Surface
            self.SurfaceViewer.BuildView()

            # Accept or reject result of smoothing surface
            queryStr = 'Accept result of smoothing?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.SurfaceSmoothing.Surface
            else:
                acceptableResult = 0
                response = 1

        # Surface clipping
        # The only issue here is that 2 renderers get built 2/2 the structure of vmtkSurfaceClipper
        # Issue to be revisited later
        acceptableResult = 0
        while acceptableResult == 0:

            self.SurfaceClipper = vmtkscripts.vmtkSurfaceClipper()
            self.SurfaceClipper.Surface = self.Surface
            self.SurfaceClipper.Execute()

            self.SurfaceViewer.Surface = self.SurfaceClipper.Surface
            self.SurfaceViewer.BuildView()

            queryStr = 'Accept result of clipping?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.SurfaceClipper.Surface
            else:
                acceptableResult = 0

            self.SurfaceViewer.Surface = self.SurfaceClipper.Surface
            self.SurfaceViewer.BuildView()

        # Create centerlines based off the acceptable clipped surface
        centerliner = vmtkscripts.vmtkCenterlines()
        centerliner.Surface = self.Surface
        centerliner.SeedSelectorName = 'openprofiles'
        centerliner.Execute()

        self.Centerlines = centerliner.Centerlines

        # Add flow extensions until user has acceptable result
        acceptableResult = 0
        response = 0
        while (acceptableResult == 0):

            self.FlowExtensions = vmtkscripts.vmtkFlowExtensions()
            self.FlowExtensions.Surface = self.Surface
            self.FlowExtensions.Centerlines = self.Centerlines
            self.FlowExtensions.AdaptiveExtensionLength = 1
            #self.FlowExtensions.CenterlineNormalEstimationDistanceRatio = 1
            self.FlowExtensions.Interactive = 0

            # Take user extension ratio if response to acceptable outcome question
            # Default extension ratio is 10
            if (response == 0):
                self.FlowExtensions.ExtensionRatio = 10
            elif (response == 1):
                #Take extension ratio from user
                queryStr = 'Please enter value for pass band; default is 20 (min/max 1-50): '
                self.FlowExtensions.ExtensionRatio = float(
                    self.InputText(queryStr, self.ExtensionRatioValidator))

            self.FlowExtensions.Execute()

            self.SurfaceViewer.Surface = self.FlowExtensions.Surface
            self.SurfaceViewer.BuildView()

            queryStr = 'Accept flow extensions?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.FlowExtensions.Surface
            else:
                acceptableResult = 0
                response = 1

        # self.SurfaceViewer.BuildView()

        # Deallocate renderer
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
    def extract_center_lines(self):
        """ Extract the centerlines of a surface.

           The centerline geometry is returned as a vtkPolyData object.
        """
        self.logger.info("---------- Extract Centerlines ---------- ")
        mesh = self.mesh
        surface = mesh.surface
        surface_caps = mesh.surface_caps
        source_centers = []
        source_ids = []
        target_centers = []
        target_ids = []

        ## Get source and target face centers.
        #
        for faceID, face in surface_caps.items():
            self.logger.info(" ")
            self.logger.info("-----  Face ID %d ----- " % int(faceID))
            center = face.get_center()
            ptID, id_center = face.get_id(center)
            if face.source:
                self.logger.info("Source")
                source_centers.extend(center)
                self.graphics.add_sphere(center, [1.0, 0.0, 0.0])
                self.graphics.add_sphere(id_center, [1.0, 0.0, 0.0])
                source_ids.append(ptID)
            else:
                self.logger.info("Target")
                target_centers.extend(center)
                self.graphics.add_sphere(center, [0.0, 1.0, 0.0])
                self.graphics.add_sphere(id_center, [0.0, 1.0, 0.0])
                target_ids.append(ptID)
            self.logger.info("Center ID: %d" % ptID)
            self.logger.info("Center: %s" % str(center))
            self.logger.info("ID Center: %s" % str(id_center))
        #__for faceID in face_ids

        ## Extract centerlines using vmtk.
        #
        self.logger.info(" ")
        self.logger.info("Calculating surface centerlines ...")
        centerlines = vmtkscripts.vmtkCenterlines()
        centerlines.Surface = mesh.surface
        centerlines.AppendEndPoints = 1
        """
        source_ids = [67628]
        target_ids = [67626, 67627 ,67628 ,67629 ,67630 ,67631 ,67632 ,67633]
        surface.GetPoint(source_ids[0], id_center);
        self.graphics.add_sphere(id_center, [1.0,0.0,0.0])
        """

        use_id_list = True

        if use_id_list:
            self.logger.info("Use source and target IDs")
            self.logger.info("Source IDs: %s" % str(source_ids))
            self.logger.info("Target IDs: %s" % str(target_ids))
            centerlines.SeedSelectorName = "idlist"
            centerlines.SourceIds = source_ids
            centerlines.TargetIds = target_ids
        else:
            centerlines.SeedSelectorName = "pointlist"
            centerlines.SourcePoints = source_centers
            centerlines.TargetPoints = target_centers

        centerlines.Execute()
        self.geometry = centerlines.Centerlines
        self.logger.info("The surface centerlines have been calculated.")
        self.graphics.add_graphics_geometry(self.geometry, [0.0, 0.0, 1.0])

        self.logger.info("Split and group centerlines along branches ...")
        branch_extractor = vmtkscripts.vmtkBranchExtractor()
        branch_extractor.Centerlines = self.geometry
        branch_extractor.Execute()
        self.branch_geometry = branch_extractor.Centerlines
        #print(self.centerlines_branch_geometry)
        self.logger.info("The centerlines branches have been calculated.")

        file_name = "branch_geometry.vtp"
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(file_name)
        writer.SetInputData(self.branch_geometry)
        writer.Update()
        writer.Write()
Exemple #14
0
        outputName = fname1.split('.') + str(diameter) + 'mm.vtp'
        vessel = VesselTruncation()
        vessel.SetInputSurface(readSurface.GetOutput())
        vessel.SetInputCenterlines(readCenterlines.GetOutput())
        vessel.SetDiameter(diameter)
        vessel.Update()
        vessel.SetOutputinputSurface(outputName)
        vessel.Write()
        vessel.GetVolume()
else:
    readSurface = vtk.vtkSTLReader()
    readSurface.SetinputSurface(inputSurface)
    readSurface.Update()

    # generate centerline
    centerlines = vmtkscripts.vmtkCenterlines()
    centerlines.Surface = readSurface.GetOutput()
    centerlines.RadiusArrayName = 'MaximumInscribedSphereRadius'
    centerlines.Execute()

    centerlines = GenerateCenterline.ExtractGeometry(centerlines)
    centerlineviewer = vmtkscripts.vmtkCenterlineViewer()
    centerlineviewer.Centerlines = centerlines.Centerlines
    #centerlineviewer.CellDataArrayName='GroupIds'
    centerlineviewer.PointDataArrayName = 'MaximumInscribedSphereRadius'
    centerlineviewer.Legend = 1
    centerlineviewer.Execute()

    branchClipper = vmtkscripts.vmtkBranchClipper()
    branchClipper.Centerlines = centerlines.Centerlines
    branchClipper.Surface = readSurface.GetOutput()
Exemple #15
0
    def Execute(self):
        print("Compute VC orientation")
        self.ctrliner = vmtkscripts.vmtkCenterlines()
        self.ctrliner.Surface = self.Surface
        self.ctrliner.Execute()
        self.Centerlines = self.ctrliner.Centerlines
        cc = self.Centerlines

        ptCoord = []

        for c in xrange(cc.GetNumberOfPoints()):
            ptCoord.append(cc.GetPoints().GetPoint(c))

        ptCoord = np.array(ptCoord)
        datamean = ptCoord.mean(axis=0)
        uu, dd, vv = np.linalg.svd(ptCoord - datamean)
        # vector of the general direction of the VC
        # print(vv[0], datamean, datamean+10*vv[0])
        VCvect = vv[0]

        if self.ComputeCenterlines:
            # print(self.Surface)
            self.ctrliner = vmtkscripts.vmtkCenterlines()
            self.ctrliner.Surface = self.Surface
            # self.ctrliner.SeedSelector = 'openprofiles'
            self.ctrliner.Execute()
            self.Centerlines = self.ctrliner.Centerlines
            # self.Surface = self.Centerlines
        else:
            self.Centerlines = self.Surface

        # if self.Centerlines == None:
        #     self.PrintError('DUMBASS')

        self.vmtkReader = vmtkscripts.vmtkSurfaceReader()

        self.vmtkRenderer = vmtkscripts.vmtkRenderer()
        self.vmtkRenderer.Initialize()
        self.SurfaceViewer = vmtkscripts.vmtkSurfaceViewer()

        # self.Surface = self.Centerlines
        self.SurfaceViewer.Surface = self.Surface
        self.SurfaceViewer.Execute()

        self.myattr = vmtkscripts.vmtkCenterlineAttributes()
        self.myattr.Centerlines = self.Centerlines
        self.myattr.Execute()

        self.mybranchextractor = vmtkscripts.vmtkBranchExtractor()
        self.mybranchextractor.Centerlines = self.myattr.Centerlines
        self.mybranchextractor.RadiusArrayName = self.RadiusArrayName
        self.mybranchextractor.Execute()

        self.ctrl = self.mybranchextractor.Centerlines

        self.mywriter = vmtkscripts.vmtkSurfaceWriter()
        self.mywriter.Surface = self.mybranchextractor.Centerlines
        self.mywriter.OutputFileName = '/home/florian/liverSim/morpho_analysis/test_surf_open_small_ctrlTESTbranc1.vtp'
        self.mywriter.Execute()

        self.mybifref = vmtkscripts.vmtkBifurcationReferenceSystems()
        self.mybifref.Centerlines = self.ctrl
        self.mybifref.RadiusArrayName = self.RadiusArrayName
        self.mybifref.BlankingArrayName = self.BlankingArrayName
        self.mybifref.GroupIdsArrayName = self.GroupIdsArrayName
        self.mybifref.CenterlineIdsArrayName = self.CenterlineIdsArrayName
        self.mybifref.TractIdsArrayName = self.TractIdsArrayName
        self.mybifref.Execute()

        self.myvect = vmtkscripts.vmtkBifurcationVectors()
        self.myvect.Centerlines = self.ctrl
        self.myvect.ReferenceSystems = self.mybifref.ReferenceSystems
        self.myvect.RadiusArrayName = self.RadiusArrayName
        self.myvect.BlankingArrayName = self.BlankingArrayName
        self.myvect.GroupIdsArrayName = self.GroupIdsArrayName
        self.myvect.TractIdsArrayName = self.TractIdsArrayName
        self.myvect.CenterlineIdsArrayName = self.CenterlineIdsArrayName
        self.myvect.ReferenceSystemsNormalArrayName = self.mybifref.ReferenceSystemsNormalArrayName
        self.myvect.ReferenceSystemsUpNormalArrayName = self.mybifref.ReferenceSystemsUpNormalArrayName
        self.myvect.Execute()

        '''TEMP'''
        self.mywriter = vmtkscripts.vmtkSurfaceWriter()
        self.mywriter.Surface = self.myvect.BifurcationVectors
        self.mywriter.OutputFileName = '/home/florian/liverSim/morpho_analysis/test_surf_open_small_bifvect.vtp'
        self.mywriter.Execute()

        self.mywriter.Surface = self.ctrl
        self.mywriter.OutputFileName = '/home/florian/liverSim/morpho_analysis/test_surf_open_small_ctrl.vtp'
        self.mywriter.Execute()
        '''/TEMP'''



        self.numpytator = vmtksurfacetonumpy.vmtkSurfaceToNumpy()
        self.numpytator.Surface = self.myvect.BifurcationVectors
        self.numpytator.Execute()
        vectData = self.numpytator.ArrayDict.values()

        cprint(figlet_format('Results!', font='bubble'))
        print('\n InPlaneBifurcationVectors angle:')
        print(np.degrees(self.angle_between(vectData[0]["InPlaneBifurcationVectors"][1, :],
                                            vectData[0]["InPlaneBifurcationVectors"][2, :])))
        # print('\n OutOfPlaneBifurcationVectors angle:')
        # print(np.degrees(self.angle_between(vectData[0]["OutOfPlaneBifurcationVectors"][1, :],
        #                                     vectData[0]["OutOfPlaneBifurcationVectors"][2, :])))
        print('\n bifurcation angle with the VC:')
        print(np.degrees(self.angle_between(vectData[0]["OutOfPlaneBifurcationVectors"][0, :],
                                            VCvect)))
        '''
        weighted average vector between the vectors pointing from the second 
        to the first reference point on each centerline
        '''
        print('\n global direction of the birfurcation:')
        print(vectData[0]["BifurcationVectors"][0, :])
        '''
        the origin of the bifurcation is defined as the barycenter of the four reference points
         weighted by the surface of the maximum inscribed sphere defined on the reference points. 
         The reason of the weighting is that small branches have less impact on the position of 
         the bifurcation origin
        '''
        print('\n Origin of the bifurcation:')
        print(vectData[1][0])
        pass
    def extract_center_lines(self):
        """ Extract the centerlines of a surface.

           The centerline geometry is returned as a vtkPolyData object.
        """
        self.logger.info("---------- Extract Centerlines ---------- ")
        mesh = self.mesh
        surface = mesh.surface
        surface_caps = mesh.surface_caps
        source_centers = []
        source_ids = []
        target_centers = []
        target_ids = []

        ## Get source and target face centers.
        #
        for faceID, face in surface_caps.items():
            self.logger.info(" ")
            self.logger.info("-----  Face ID %d ----- " % int(faceID))
            center = face.get_center()
            ptID, id_center = face.get_id(center)
            if face.source:
                self.logger.info("Source")
                source_centers.extend(center)
                self.graphics.add_sphere(center, [1.0, 0.0, 0.0])
                self.graphics.add_sphere(id_center, [1.0, 0.0, 0.0])
                source_ids.append(ptID)
            else:
                self.logger.info("Target")
                target_centers.extend(center)
                self.graphics.add_sphere(center, [0.0, 1.0, 0.0])
                self.graphics.add_sphere(id_center, [0.0, 1.0, 0.0])
                target_ids.append(ptID)
            self.logger.info("Center ID: %d" % ptID)
            self.logger.info("Center: %s" % str(center))
            self.logger.info("ID Center: %s" % str(id_center))
        #__for faceID in face_ids

        ## Extract centerlines using vmtk.
        #
        self.logger.info("Calculating surface centerlines ...")
        centerlines = vmtkscripts.vmtkCenterlines()
        centerlines.Surface = mesh.surface
        centerlines.AppendEndPoints = 1
        """
        source_ids = [67628]
        target_ids = [67626, 67627 ,67628 ,67629 ,67630 ,67631 ,67632 ,67633]
        surface.GetPoint(source_ids[0], id_center);
        self.graphics.add_sphere(id_center, [1.0,0.0,0.0])
        """

        use_id_list = True

        if use_id_list:
            self.logger.info("Use source and target IDs")
            self.logger.info("Source IDs: %s" % str(source_ids))
            self.logger.info("Target IDs: %s" % str(target_ids))
            centerlines.SeedSelectorName = "idlist"
            centerlines.SourceIds = source_ids
            centerlines.TargetIds = target_ids
        else:
            centerlines.SeedSelectorName = "pointlist"
            centerlines.SourcePoints = source_centers
            centerlines.TargetPoints = target_centers
Exemple #17
0
surfaceFile = '/home/florian/liverSim/morpho_analysis/test_surf_open_small.vtp'
centerlinesFileName = surfaceFile[:-4] + '_ctrlTEST1.vtp'
# centerlinesFile = '/home/florian/liverSim/images/nkouka_piggy_LL/nkouka_ctrlines.vtp'

if not os.path.isfile(surfaceFile):
    print('check your input, exiting code\n you failed on the',
          time.asctime(time.localtime(time.time())))
    exit()

start_time = time()

args = "vmtksurfacereader -ifile " + surfaceFile
myPype = pypes.PypeRun(args)
mySurface = myPype.GetScriptObject('vmtksurfacereader', '0').Surface

myctrl = vmtkscripts.vmtkCenterlines()
myctrl.Surface = mySurface
myctrl.SeedSelectorName = 'openprofiles'
# myctrl.Centerlines = centerlinesFile
myctrl.Execute()

myattr = vmtkscripts.vmtkCenterlineAttributes()
myattr.Centerlines = myctrl.Centerlines
myattr.Execute()

mybranchextractor = vmtkscripts.vmtkBranchExtractor()
mybranchextractor.Centerlines = myattr.Centerlines
mybranchextractor.RadiusArrayName = 'MaximumInscribedSphereRadius'
mybranchextractor.Execute()

# mywriter = vmtkscripts.vmtkSurfaceWriter()