def computeCenterlines(self,polydata,inletSeedIds,outletSeedIds):


        centerlineFilter = slicer.vtkvmtkPolyDataCenterlines()
        centerlineFilter.SetInput(polydata)
        centerlineFilter.SetSourceSeedIds(inletSeedIds)
        centerlineFilter.SetTargetSeedIds(outletSeedIds)
        centerlineFilter.SetRadiusArrayName(self._radiusArrayName)
        centerlineFilter.SetCostFunction(self._costFunction)
        centerlineFilter.SetFlipNormals(self._flipNormals)
        centerlineFilter.SetAppendEndPointsToCenterlines(self._appendEndPoints)
        centerlineFilter.SetSimplifyVoronoi(self._simplifyVoronoi)
        centerlineFilter.SetCenterlineResampling(self._resampling)
        centerlineFilter.SetResamplingStepLength(self._resamplingStepLength)
        centerlineFilter.Update()

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(centerlineFilter.GetOutput())
        polyDataNew.Update()

        self._vd = slicer.vtkPolyData()
        self._vd.DeepCopy(centerlineFilter.GetVoronoiDiagram())
        self._vd.Update()

        return polyDataNew
예제 #2
0
    def GenerateEvolutionModel(self, resultContainer):

        matrix = slicer.vtkMatrix4x4()

        image = resultContainer.GetNode().GetImageData()

        resultContainer.GetNode().GetIJKToRASMatrix(matrix)
        threshold = 0.0

        polyData = slicer.vtkPolyData()

        if image.GetPointData().GetScalars():
            # marching Cubes, only if image has content
            polyData.DeepCopy(self._mainGUIClass.GetMyLogic().MarchingCubes(
                image, matrix, threshold))

        scene = self._mainGUIClass.GetLogic().GetMRMLScene()
        if self._mainGUIClass._outEvolModel == None:

            # no node so far
            self._mainGUIClass._outEvolModel = slicer.vtkMRMLModelNode()
            self._mainGUIClass._outEvolModel.SetName(
                "VMTK Level-Set Evolution Output Model")
            self._mainGUIClass._outEvolModel.SetAndObservePolyData(
                slicer.vtkPolyData())
            self._mainGUIClass._outEvolModel.SetScene(scene)
            scene.AddNode(self._mainGUIClass._outEvolModel)

            self._mainGUIClass._outEvolModelDisplay = slicer.vtkMRMLModelDisplayNode(
            )
            self._mainGUIClass._outEvolModelDisplay.SetColor(0.0, 0.0, 0.8)
            self._mainGUIClass._outEvolModelDisplay.SetPolyData(
                slicer.vtkPolyData())
            self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
            self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
            self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(
                1)

        self._mainGUIClass._outEvolModel.SetAndObservePolyData(polyData)
        self._mainGUIClass._outEvolModel.SetModifiedSinceRead(1)
        self._mainGUIClass._outEvolModelDisplay.SetPolyData(
            self._mainGUIClass._outEvolModel.GetPolyData())
        self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(
            1)
        self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
        scene.AddNode(self._mainGUIClass._outEvolModelDisplay)

        self._mainGUIClass._outEvolModel.SetAndObserveDisplayNodeID(
            self._mainGUIClass._outEvolModelDisplay.GetID())
        self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(
            1)
        self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
예제 #3
0
    def Extract(self):
        inModel = self._inModelSelector.GetSelected()
        seeds = self._seedsSelector.GetSelected()
        outModel = self._outModelSelector.GetSelected()

        vmtkFound=self.CheckForVmtkLibrary()

        if inModel and outModel and seeds and vmtkFound:

            result = slicer.vtkPolyData()
            result.DeepCopy(self._logic.extractNetwork(inModel.GetPolyData(),seeds.GetNthFiducialXYZ(0)))
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0, 0, 0)
            displayNode.SetScalarVisibility(1)
            displayNode.SetActiveScalarName("Topology")
            displayNode.SetAndObserveColorNodeID(self.GetLogic().GetMRMLScene().GetNodesByName("Labels").GetItemAsObject(0).GetID())
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())

            dNode = inModel.GetModelDisplayNode()
            dNode.SetOpacity(0.5)
            inModel.SetAndObserveDisplayNodeID(dNode.GetID())
예제 #4
0
    def PrepCenterlines(self):
        inModel = self._inModelSelector.GetSelected()
        outModel = self._outModelPrepSelector.GetSelected()

        vmtkFound = self.CheckForVmtkLibrary()

        if inModel and outModel and vmtkFound:

            displayNodeIn = inModel.GetModelDisplayNode()
            if displayNodeIn:
                displayNodeIn.SetVisibility(0)

            result = slicer.vtkPolyData()
            result.DeepCopy(self._logic.prepareModel(inModel.GetPolyData()))
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0, 0.8, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(0.7)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
    def PrepCenterlines(self):
        inModel = self._inModelSelector.GetSelected()
        outModel = self._outModelPrepSelector.GetSelected()


        vmtkFound = self.CheckForVmtkLibrary()

        if inModel and outModel and vmtkFound:

            displayNodeIn = inModel.GetModelDisplayNode()
            if displayNodeIn:
                displayNodeIn.SetVisibility(0)

            result = slicer.vtkPolyData()
            result.DeepCopy(self._logic.prepareModel(inModel.GetPolyData()))
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0, 0.8, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(0.7)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
    def GenerateEvolutionModel(self,resultContainer):

        matrix = slicer.vtkMatrix4x4()

        image = resultContainer.GetNode().GetImageData()

        resultContainer.GetNode().GetIJKToRASMatrix(matrix)
        threshold = 0.0

        polyData = slicer.vtkPolyData()

        if image.GetPointData().GetScalars():
            # marching Cubes, only if image has content
            polyData.DeepCopy(self._mainGUIClass.GetMyLogic().MarchingCubes(image,matrix,threshold))

        scene = self._mainGUIClass.GetLogic().GetMRMLScene()
        if self._mainGUIClass._outEvolModel == None:

            # no node so far
            self._mainGUIClass._outEvolModel = slicer.vtkMRMLModelNode()
            self._mainGUIClass._outEvolModel.SetName("VMTK Level-Set Evolution Output Model")
            self._mainGUIClass._outEvolModel.SetAndObservePolyData(slicer.vtkPolyData())
            self._mainGUIClass._outEvolModel.SetScene(scene)
            scene.AddNode(self._mainGUIClass._outEvolModel)

            self._mainGUIClass._outEvolModelDisplay = slicer.vtkMRMLModelDisplayNode()
            self._mainGUIClass._outEvolModelDisplay.SetColor(0.0, 0.0, 0.8)
            self._mainGUIClass._outEvolModelDisplay.SetPolyData(slicer.vtkPolyData())
            self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
            self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
            self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(1)


        self._mainGUIClass._outEvolModel.SetAndObservePolyData(polyData)
        self._mainGUIClass._outEvolModel.SetModifiedSinceRead(1)
        self._mainGUIClass._outEvolModelDisplay.SetPolyData(self._mainGUIClass._outEvolModel.GetPolyData())
        self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
        scene.AddNode(self._mainGUIClass._outEvolModelDisplay)

        self._mainGUIClass._outEvolModel.SetAndObserveDisplayNodeID(self._mainGUIClass._outEvolModelDisplay.GetID())
        self._mainGUIClass._outEvolModelDisplay.SetSliceIntersectionVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetVisibility(1)
        self._mainGUIClass._outEvolModelDisplay.SetOpacity(0.5)
    def MarchingCubes(self, image, matrix, threshold):

        self._parentClass.GetHelper().debug("Starting MarchingCubes..")

        transformIJKtoRAS = slicer.vtkTransform()
        transformIJKtoRAS.SetMatrix(matrix)

        marchingCubes = slicer.vtkMarchingCubes()
        marchingCubes.SetInput(image)
        marchingCubes.SetValue(0, threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.GetOutput().ReleaseDataFlagOn()
        marchingCubes.Update()

        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            self.debug("Determinant smaller than 0")
            reverser = slicer.vtkReverseSense()
            reverser.SetInput(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.GetOutput().ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = slicer.vtkTransformPolyDataFilter()
        transformer.SetInput(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.GetOutput().ReleaseDataFlagOn()
        transformer.Update()

        normals = slicer.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInput(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.GetOutput().ReleaseDataFlagOn()
        normals.Update()

        stripper = slicer.vtkStripper()
        stripper.SetInput(normals.GetOutput())
        stripper.GetOutput().ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput().Update()

        result = slicer.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())
        result.Update()

        self._parentClass.GetHelper().debug("End MarchingCubes..")

        return result
    def MarchingCubes(self,image,matrix,threshold):

        self._parentClass.GetHelper().debug("Starting MarchingCubes..")

        transformIJKtoRAS = slicer.vtkTransform()
        transformIJKtoRAS.SetMatrix(matrix)

        marchingCubes = slicer.vtkMarchingCubes()
        marchingCubes.SetInput(image)
        marchingCubes.SetValue(0,threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.GetOutput().ReleaseDataFlagOn()
        marchingCubes.Update()

        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            self.debug("Determinant smaller than 0")
            reverser = slicer.vtkReverseSense()
            reverser.SetInput(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.GetOutput().ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = slicer.vtkTransformPolyDataFilter()
        transformer.SetInput(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.GetOutput().ReleaseDataFlagOn()
        transformer.Update()

        normals = slicer.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInput(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.GetOutput().ReleaseDataFlagOn()
        normals.Update()
        
        stripper = slicer.vtkStripper()
        stripper.SetInput(normals.GetOutput())
        stripper.GetOutput().ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput().Update()

        result = slicer.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())
        result.Update()

        self._parentClass.GetHelper().debug("End MarchingCubes..")

        return result
    def splitModels(self, Surface):
        dataArray = Surface.GetPointData().GetScalars("GroupIds")
        scalarRange = dataArray.GetRange()

        newPdList = []
        newCaList = []
        self._parentClass._helper.debug("started splitter")
        # generate containers CellArray & PolyData + copy points
        for i in range(1, int(scalarRange[1]) + 2):
            newCellArray = slicer.vtkCellArray()
            newPolyData = slicer.vtkPolyData()

            points = slicer.vtkPoints()
            points.DeepCopy(Surface.GetPoints())
            newPolyData.SetPoints(points)
            newPolyData.SetPolys(newCellArray)
            newPolyData.Update()

            newPdList.append(newPolyData)
            newCaList.append(newCellArray)

        #Fill containers with Polys
        for i in range(0, Surface.GetPolys().GetNumberOfCells()):
            poi = Surface.GetCell(i).GetPointIds()

            if (poi.GetNumberOfIds() == 0):
                continue

            scalarsOfPoints = []

            for pid in range(0, poi.GetNumberOfIds()):
                p = poi.GetId(pid)
                scalarsOfPoints.append(dataArray.GetValue(p))

            max = 0
            largestIndex = 0
            for j in range(1, int(scalarRange[1]) + 2):
                c = scalarsOfPoints.count(j)
                if c >= max:
                    max = c
                    largestIndex = j
            newCaList[largestIndex].InsertNextCell(Surface.GetCell(i))

        # clean PolyData
        for pd in newPdList:
            cleanPolyData = slicer.vtkCleanPolyData()
            cleanPolyData.SetInput(pd)
            cleanPolyData.Update()
            pd.DeepCopy(cleanPolyData.GetOutput())

        self._parentClass._helper.debug("finished splitter")

        return newPdList
  def splitModels(self,Surface):
    dataArray=Surface.GetPointData().GetScalars("GroupIds")
    scalarRange=dataArray.GetRange()
    
    newPdList=[]
    newCaList=[]
    self._parentClass._helper.debug("started splitter")
    # generate containers CellArray & PolyData + copy points
    for i in range(1,int(scalarRange[1])+2):
      newCellArray=slicer.vtkCellArray()
      newPolyData=slicer.vtkPolyData()

      points=slicer.vtkPoints()
      points.DeepCopy(Surface.GetPoints())		
      newPolyData.SetPoints(points)
      newPolyData.SetPolys(newCellArray)
      newPolyData.Update()

      newPdList.append(newPolyData)
      newCaList.append(newCellArray)

    #Fill containers with Polys
    for i in range (0,Surface.GetPolys().GetNumberOfCells()):
      poi=Surface.GetCell(i).GetPointIds()

      if(poi.GetNumberOfIds()==0):
        continue

      scalarsOfPoints =[]
  
      for pid in range(0,poi.GetNumberOfIds()): 
        p=poi.GetId(pid)
        scalarsOfPoints.append(dataArray.GetValue(p))

      max=0
      largestIndex=0
      for j in range(1,int(scalarRange[1])+2):
        c=scalarsOfPoints.count(j)
        if c >= max:
          max=c
          largestIndex=j
      newCaList[largestIndex].InsertNextCell(Surface.GetCell(i))

    # clean PolyData
    for pd in newPdList:
      cleanPolyData = slicer.vtkCleanPolyData();
      cleanPolyData.SetInput(pd);
      cleanPolyData.Update();
      pd.DeepCopy(cleanPolyData.GetOutput())
      
    self._parentClass._helper.debug("finished splitter")

    return newPdList
  def branchSplitting(self,centerlines,model):
    self.Centerlines = centerlines

    self._parentClass._helper.debug("started branchExtractor")
    branchExtractor = slicer.vtkvmtkCenterlineBranchExtractor()
    branchExtractor.SetInput(centerlines)
    branchExtractor.SetBlankingArrayName(self._BlankingArrayName)
    branchExtractor.SetRadiusArrayName(self._RadiusArrayName)
    branchExtractor.SetGroupIdsArrayName(self._GroupIdsArrayName)
    branchExtractor.SetCenterlineIdsArrayName(self._CenterlineIdsArrayName)
    branchExtractor.SetTractIdsArrayName(self._TractIdsArrayName)
    branchExtractor.Update()
    self._parentClass._helper.debug("finished branchExtractor")
    self._parentClass._helper.debug("started clipper")
    clipper = slicer.vtkvmtkPolyDataCenterlineGroupsClipper()
    clipper.SetInput(model)
    clipper.SetCenterlines(branchExtractor.GetOutput())
    clipper.SetCenterlineGroupIdsArrayName(self._GroupIdsArrayName)
    clipper.SetGroupIdsArrayName(self._GroupIdsArrayName)
    clipper.SetCenterlineRadiusArrayName(self._RadiusArrayName)
    clipper.SetBlankingArrayName(self._BlankingArrayName)
    clipper.SetCutoffRadiusFactor(self._CutoffRadiusFactor)
    clipper.SetClipValue(self._ClipValue)
    clipper.SetUseRadiusInformation(self._UseRadiusInformation)
    clipper.ClipAllCenterlineGroupIdsOn()
    clipper.Update()
    self._parentClass._helper.debug("finished clipper")
    if not self._InsideOut:
      clipper.GenerateClippedOutputOff()
    else:
      clipper.GenerateClippedOutputOn()
    clipper.Update()

    if not self._InsideOut:
      Surface = clipper.GetOutput()
    else:
      Surface = clipper.GetClippedOutput()

    # shift values because first value is invisible in default LabelMap
    dataArray=Surface.GetPointData().GetScalars("GroupIds")
    newDa=slicer.vtkIntArray()
    newDa.SetName("GroupIds")
    newDa.InsertTuple1(0, 0)
    for i in range (1,dataArray.GetSize()):
      newDa.InsertTuple1(i, dataArray.GetValue(i)+1)

    polyDataNew = slicer.vtkPolyData()
    polyDataNew.DeepCopy(Surface)
    polyDataNew.GetPointData().SetScalars(newDa)
    polyDataNew.Update()

    return polyDataNew
    def branchSplitting(self, centerlines, model):
        self.Centerlines = centerlines

        self._parentClass._helper.debug("started branchExtractor")
        branchExtractor = slicer.vtkvmtkCenterlineBranchExtractor()
        branchExtractor.SetInput(centerlines)
        branchExtractor.SetBlankingArrayName(self._BlankingArrayName)
        branchExtractor.SetRadiusArrayName(self._RadiusArrayName)
        branchExtractor.SetGroupIdsArrayName(self._GroupIdsArrayName)
        branchExtractor.SetCenterlineIdsArrayName(self._CenterlineIdsArrayName)
        branchExtractor.SetTractIdsArrayName(self._TractIdsArrayName)
        branchExtractor.Update()
        self._parentClass._helper.debug("finished branchExtractor")
        self._parentClass._helper.debug("started clipper")
        clipper = slicer.vtkvmtkPolyDataCenterlineGroupsClipper()
        clipper.SetInput(model)
        clipper.SetCenterlines(branchExtractor.GetOutput())
        clipper.SetCenterlineGroupIdsArrayName(self._GroupIdsArrayName)
        clipper.SetGroupIdsArrayName(self._GroupIdsArrayName)
        clipper.SetCenterlineRadiusArrayName(self._RadiusArrayName)
        clipper.SetBlankingArrayName(self._BlankingArrayName)
        clipper.SetCutoffRadiusFactor(self._CutoffRadiusFactor)
        clipper.SetClipValue(self._ClipValue)
        clipper.SetUseRadiusInformation(self._UseRadiusInformation)
        clipper.ClipAllCenterlineGroupIdsOn()
        clipper.Update()
        self._parentClass._helper.debug("finished clipper")
        if not self._InsideOut:
            clipper.GenerateClippedOutputOff()
        else:
            clipper.GenerateClippedOutputOn()
        clipper.Update()

        if not self._InsideOut:
            Surface = clipper.GetOutput()
        else:
            Surface = clipper.GetClippedOutput()

        # shift values because first value is invisible in default LabelMap
        dataArray = Surface.GetPointData().GetScalars("GroupIds")
        newDa = slicer.vtkIntArray()
        newDa.SetName("GroupIds")
        newDa.InsertTuple1(0, 0)
        for i in range(1, dataArray.GetSize()):
            newDa.InsertTuple1(i, dataArray.GetValue(i) + 1)

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(Surface)
        polyDataNew.GetPointData().SetScalars(newDa)
        polyDataNew.Update()

        return polyDataNew
    def prepareModel(self,polydata):

        if polydata == None:
            return -1
        
        # skip nonmanifold

        surfaceCleaner = slicer.vtkCleanPolyData()
        surfaceCleaner.SetInput(polydata)
        surfaceCleaner.Update()

        surfaceTriangulator = slicer.vtkTriangleFilter()
        surfaceTriangulator.SetInput(surfaceCleaner.GetOutput())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        # new steps for preparation to avoid problems because of slim models (f.e. at stenosis)
        subdiv = slicer.vtkLinearSubdivisionFilter()
        subdiv.SetInput(surfaceTriangulator.GetOutput())
        subdiv.SetNumberOfSubdivisions(1)
        subdiv.Update()

        smooth = slicer.vtkWindowedSincPolyDataFilter()
        smooth.SetInput(subdiv.GetOutput())
        smooth.SetNumberOfIterations(20)
        smooth.SetPassBand(0.1)
        smooth.SetBoundarySmoothing(1)
        smooth.NormalizeCoordinatesOn()
        smooth.Update()

        normals = slicer.vtkPolyDataNormals()
        normals.SetInput(smooth.GetOutput())
        normals.SetAutoOrientNormals(1)
        normals.SetFlipNormals(0)
        normals.SetConsistency(1)
        normals.SplittingOff()
        normals.Update()

        surfaceCapper = slicer.vtkvmtkCapPolyData()
        surfaceCapper.SetInput(normals.GetOutput())
        surfaceCapper.SetDisplacement(self._capDisplacement)
        surfaceCapper.SetInPlaneDisplacement(self._capDisplacement)
        surfaceCapper.Update()

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(surfaceCapper.GetOutput())
        polyDataNew.Update()

        return polyDataNew
예제 #14
0
    def prepareModel(self, polydata):

        if polydata == None:
            return -1

        # skip nonmanifold

        surfaceCleaner = slicer.vtkCleanPolyData()
        surfaceCleaner.SetInput(polydata)
        surfaceCleaner.Update()

        surfaceTriangulator = slicer.vtkTriangleFilter()
        surfaceTriangulator.SetInput(surfaceCleaner.GetOutput())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        # new steps for preparation to avoid problems because of slim models (f.e. at stenosis)
        subdiv = slicer.vtkLinearSubdivisionFilter()
        subdiv.SetInput(surfaceTriangulator.GetOutput())
        subdiv.SetNumberOfSubdivisions(1)
        subdiv.Update()

        smooth = slicer.vtkWindowedSincPolyDataFilter()
        smooth.SetInput(subdiv.GetOutput())
        smooth.SetNumberOfIterations(20)
        smooth.SetPassBand(0.1)
        smooth.SetBoundarySmoothing(1)
        smooth.NormalizeCoordinatesOn()
        smooth.Update()

        normals = slicer.vtkPolyDataNormals()
        normals.SetInput(smooth.GetOutput())
        normals.SetAutoOrientNormals(1)
        normals.SetFlipNormals(0)
        normals.SetConsistency(1)
        normals.SplittingOff()
        normals.Update()

        surfaceCapper = slicer.vtkvmtkCapPolyData()
        surfaceCapper.SetInput(normals.GetOutput())
        surfaceCapper.SetDisplacement(self._capDisplacement)
        surfaceCapper.SetInPlaneDisplacement(self._capDisplacement)
        surfaceCapper.Update()

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(surfaceCapper.GetOutput())
        polyDataNew.Update()

        return polyDataNew
예제 #15
0
    def computeCenterlines(self, polydata, inletSeedIds, outletSeedIds):

        centerlineFilter = slicer.vtkvmtkPolyDataCenterlines()
        centerlineFilter.SetInput(polydata)
        centerlineFilter.SetSourceSeedIds(inletSeedIds)
        centerlineFilter.SetTargetSeedIds(outletSeedIds)
        centerlineFilter.SetRadiusArrayName(self._radiusArrayName)
        centerlineFilter.SetCostFunction(self._costFunction)
        centerlineFilter.SetFlipNormals(self._flipNormals)
        centerlineFilter.SetAppendEndPointsToCenterlines(self._appendEndPoints)
        centerlineFilter.SetSimplifyVoronoi(self._simplifyVoronoi)
        centerlineFilter.SetCenterlineResampling(self._resampling)
        centerlineFilter.SetResamplingStepLength(self._resamplingStepLength)
        centerlineFilter.Update()

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(centerlineFilter.GetOutput())
        polyDataNew.Update()

        self._vd = slicer.vtkPolyData()
        self._vd.DeepCopy(centerlineFilter.GetVoronoiDiagram())
        self._vd.Update()

        return polyDataNew
예제 #16
0
    def GenerateModel(self, volumeNode, color):

        if color == 'red':
            r = 0.8
            g = 0.0
            b = 0.0
            name = "VMTK Initialization Model"
            registerModel = 1
        elif color == 'blue':
            r = 1.0
            g = 1.0
            b = 0.0
            name = "VMTK Evolution Model"
            registerModel = 0

        matrix = slicer.vtkMatrix4x4()

        image = volumeNode.GetImageData()
        volumeNode.GetIJKToRASMatrix(matrix)

        polyData = slicer.vtkPolyData()

        if image.GetPointData().GetScalars():
            # marching Cubes, only if image has content
            polyData.DeepCopy(self._parentClass.GetMyLogic().MarchingCubes(
                image, matrix, 0.0))
        scene = self._parentClass.GetLogic().GetMRMLScene()

        newModel = slicer.vtkMRMLModelNode()
        newModel.SetName(name)
        newModel.SetScene(scene)
        newModel.SetAndObservePolyData(polyData)
        scene.AddNode(newModel)

        newModelDisplay = slicer.vtkMRMLModelDisplayNode()
        newModelDisplay.SetPolyData(newModel.GetPolyData())
        newModelDisplay.SetColor(r, g, b)
        newModelDisplay.SetBackfaceCulling(0)
        newModelDisplay.SetSliceIntersectionVisibility(1)
        newModelDisplay.SetVisibility(1)
        newModelDisplay.SetOpacity(1.0)
        scene.AddNode(newModelDisplay)

        newModel.SetAndObserveDisplayNodeID(newModelDisplay.GetID())

        if registerModel:
            self._parentClass.SetOutInitModelDisplay(newModelDisplay)
    def GenerateModel(self, volumeNode, color):

        if color == "red":
            r = 0.8
            g = 0.0
            b = 0.0
            name = "VMTK Initialization Model"
            registerModel = 1
        elif color == "blue":
            r = 1.0
            g = 1.0
            b = 0.0
            name = "VMTK Evolution Model"
            registerModel = 0

        matrix = slicer.vtkMatrix4x4()

        image = volumeNode.GetImageData()
        volumeNode.GetIJKToRASMatrix(matrix)

        polyData = slicer.vtkPolyData()

        if image.GetPointData().GetScalars():
            # marching Cubes, only if image has content
            polyData.DeepCopy(self._parentClass.GetMyLogic().MarchingCubes(image, matrix, 0.0))
        scene = self._parentClass.GetLogic().GetMRMLScene()

        newModel = slicer.vtkMRMLModelNode()
        newModel.SetName(name)
        newModel.SetScene(scene)
        newModel.SetAndObservePolyData(polyData)
        scene.AddNode(newModel)

        newModelDisplay = slicer.vtkMRMLModelDisplayNode()
        newModelDisplay.SetPolyData(newModel.GetPolyData())
        newModelDisplay.SetColor(r, g, b)
        newModelDisplay.SetBackfaceCulling(0)
        newModelDisplay.SetSliceIntersectionVisibility(1)
        newModelDisplay.SetVisibility(1)
        newModelDisplay.SetOpacity(1.0)
        scene.AddNode(newModelDisplay)

        newModel.SetAndObserveDisplayNodeID(newModelDisplay.GetID())

        if registerModel:
            self._parentClass.SetOutInitModelDisplay(newModelDisplay)
예제 #18
0
    def Splitting(self):
        inCeLine = self._inCenterLineSelector.GetSelected()
        inModel = self._inModelSelector.GetSelected()
        outModel = self._outModelSelector.GetSelected()
        split = self._checkButton.GetSelectedState()

        vmtkFound = self.CheckForVmtkLibrary()

        if inCeLine and inModel and outModel and vmtkFound:

            result = slicer.vtkPolyData()
            r = self._logic.branchSplitting(inCeLine.GetPolyData(),
                                            inModel.GetPolyData())
            result.DeepCopy(r)
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(1, 0, 0)
            displayNode.SetScalarVisibility(1)
            displayNode.SetActiveScalarName(self._logic._GroupIdsArrayName)
            displayNode.SetAndObserveColorNodeID(
                self.GetLogic().GetMRMLScene().GetNodesByName(
                    "Labels").GetItemAsObject(0).GetID())
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())

            dNode = inModel.GetModelDisplayNode()
            dNode.SetOpacity(0.0)
            inModel.SetAndObserveDisplayNodeID(dNode.GetID())

            if split == 1:
                ctr = 0
                newPdList = self._logic.splitModels(result)
                for i in newPdList:
                    if i.GetNumberOfCells() == 0:
                        continue

                    self._helper.debug("Number of Cells are: " +
                                       str(i.GetNumberOfCells()))

                    ctr += 1
                    scene = self.GetLogic().GetMRMLScene()

                    newNode = slicer.vtkMRMLModelNode()
                    newNode.SetName("VMTKBranchSplittingOut_Branch" + str(ctr))
                    newNode.SetScene(scene)
                    newNode.SetAndObservePolyData(i)
                    scene.AddNode(newNode)

                    dn = slicer.vtkMRMLModelDisplayNode()
                    dn.SetPolyData(newNode.GetPolyData())
                    dn.SetColor(random.random(), random.random(),
                                random.random())
                    dn.SetBackfaceCulling(0)
                    dn.SetSliceIntersectionVisibility(1)
                    dn.SetVisibility(1)
                    dn.SetOpacity(1.0)
                    scene.AddNode(dn)

                    newNode.SetAndObserveDisplayNodeID(dn.GetName())
    def Import(self):
        outModel = self._importModelSelector.GetSelected()
        outputFileName = self._loadButton.GetFileName()

        if outModel and outputFileName:

            self._helper.debug("Start import..")

            points = slicer.vtkPoints()
            conn = slicer.vtkCellArray()
            polyData = slicer.vtkPolyData()

            f=open(outputFileName)
            lines = f.readlines()
            i = 0
            lastId = None
            for line in lines:

                if self._importHeaders.GetSelectedState()==1 and i==0:
                    self._helper.debug("Ignore first line..")
                else:
                    # now parse the rest
                    splitted = line.split()

                    x = float(splitted[0])
                    y = float(splitted[1])
                    z = float(splitted[2])

                    if self._importNifti.GetSelectedState()==1:
                        x = x*(-1)
                        y = y*(-1)

                    #self._helper.debug("Found point: "+str(x)+","+str(y)+","+str(z))

                    id = points.InsertNextPoint(x,y,z)
                    #self._helper.debug(id)

                    if lastId:
                        curLine = slicer.vtkLine()
                        curLine.GetPointIds().SetId(0,lastId)
                        curLine.GetPointIds().SetId(1,id)

                        conn.InsertNextCell(curLine)
                        #conn.InsertCellPoint(id)

                    lastId = id

                i = i+1

            f.close()

            result = slicer.vtkPolyData()
            result.SetPoints(points)
            result.SetLines(conn)
            result.Update()

            self._helper.debug(result)
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0.8, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
    def Centerlines(self):
        inModel = self._outModelPrepSelector.GetSelected()
        outModel = self._outModelSelector.GetSelected()
        vModel = self._outVSelector.GetSelected()

        seeds = self._seedsSelector.GetSelected()
        targetSeeds = self._targetSeedsSelector.GetSelected()

        vmtkFound = self.CheckForVmtkLibrary()

        if inModel and outModel and seeds and targetSeeds and vModel and vmtkFound:

            sourceSeedIds = slicer.vtkIdList()
            targetSeedIds = slicer.vtkIdList()

            pointLocator = slicer.vtkPointLocator()
            pointLocator.SetDataSet(inModel.GetPolyData())
            pointLocator.BuildLocator()

            for i in range(seeds.GetNumberOfFiducials()):
                rasPt = seeds.GetNthFiducialXYZ(i)
                id = pointLocator.FindClosestPoint(int(rasPt[0]),int(rasPt[1]),int(rasPt[2]))
                sourceSeedIds.InsertNextId(id)

            for i in range(targetSeeds.GetNumberOfFiducials()):
                rasPt = targetSeeds.GetNthFiducialXYZ(i)
                id = pointLocator.FindClosestPoint(int(rasPt[0]),int(rasPt[1]),int(rasPt[2]))
                targetSeedIds.InsertNextId(id)

            result = slicer.vtkPolyData()
            result.DeepCopy(self._logic.computeCenterlines(inModel.GetPolyData(),sourceSeedIds,targetSeedIds))
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())

            vd = slicer.vtkPolyData()
            vd.DeepCopy(self._logic.GetVoronoiDiagram())
            vd.Update()
            vModel.SetAndObservePolyData(vd)
            vModel.SetModifiedSinceRead(1)
            dNode = vModel.GetModelDisplayNode()
            if not dNode:
                dNode = slicer.vtkMRMLModelDisplayNode()
            dNode.SetPolyData(vModel.GetPolyData())
            dNode.SetScalarVisibility(1)
            dNode.SetBackfaceCulling(0)
            dNode.SetActiveScalarName("MaximumInscribedSphereRadius")
            dNode.SetAndObserveColorNodeID(self.GetLogic().GetMRMLScene().GetNodesByName("Labels").GetItemAsObject(0).GetID())
            dNode.SetVisibility(1)
            dNode.SetOpacity(0.5)
            self.GetLogic().GetMRMLScene().AddNode(dNode)

            vModel.SetAndObserveDisplayNodeID(dNode.GetID())
예제 #21
0
def Execute(dwi_node, seeds_node, mask_node, ff_node, \
            record_fa = False, record_state = False, record_cov = False, \
            model="two-tensor", FA_min=.15, GA_min=.10,
            seeds=1, labels=[1],
            Qm=.0030, Ql=100, Rs=.015, theta_max=45):
    for i in xrange(10):
        print ''

    is_2t = (model == "two-tensor")

    print 'HACK hardcode 2T'
    is_2t = True
    follow = iff(is_2t, follow2t, follow1t)

    state_dim = iff(is_2t, 10, 5)  # dimension of state space

    theta_min = 5  # angle which triggers branch
    param = dict({
        'FA_min': FA_min,  # fractional anisotropy stopping threshold
        'GA_min': GA_min,  # generalized anisotropy stopping threshold
        'dt': .2,  # forward Euler step size (path integration)
        'max_len': 250,  # stop if fiber gets this long
        'min_radius': .87,  # stop if fiber curves this much
        'seeds': seeds,  # number of seeds in each voxel
        'theta_min':
        np.cos(theta_min * np.pi / 180),  # angle which triggers branch
        'theta_max':
        np.cos(theta_max * np.pi / 180),  # angle which triggers branch
        'min_radius': .87,  # stop if fiber curves this much
        'record_fa': record_fa,
        'record_st': record_state,
        'record_co': record_cov,
        # Kalman filter parameters
        'Qm': Qm,  # injected angular noise
        'Ql': Ql,  # injected eigenvalue noise
        'Rs': Rs,  # dependent on latent noise in your data
        'P0': 0.01 * np.eye(state_dim)
    })  # initial covariance

    from Slicer import slicer

    #     foo = slicer.vtkFloatArray()
    #     foo.SetNumberOfComponents(1)
    #     foo.SetName('foo')

    #     foo.InsertNextValue(234)          # Success
    #     foo.InsertNextValue(23.4)         # Success
    #     foo.InsertNextValue(255 * np.random.rand())       # Success
    #     foo.InsertNextValue(np.empty(1,dtype='float32'))  # FAIL
    #     foo.InsertNextValue(np.empty(1,dtype='float64'))  # FAIL
    #     asdf

    scene = slicer.MRMLScene
    dwi_node = scene.GetNodeByID(dwi_node)
    seeds_node = scene.GetNodeByID(seeds_node)
    mask_node = scene.GetNodeByID(mask_node)
    ff_node = scene.GetNodeByID(ff_node)

    # ensure normalized signal
    bb = dwi_node.GetBValues().ToArray()
    if np.any(bb.sum(1) == 0):
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "Use the \'Normalize Signal\' module to prepare the DWI data"'
        )
        return
    b = bb.mean()
    S = dwi_node.GetImageData().ToArray()
    u = dwi_node.GetDiffusionGradients().ToArray()
    i2r = vtk2mat(dwi_node.GetIJKToRASMatrix, slicer)
    r2i = vtk2mat(dwi_node.GetRASToIJKMatrix, slicer)
    mf = vtk2mat(dwi_node.GetMeasurementFrameMatrix, slicer)
    voxel = np.mat(dwi_node.GetSpacing()).reshape(3, 1)
    voxel = voxel[::-1]  # HACK Numpy has [z y x]

    # generalized loading...
    R = r2i[0:3, 0:3] / voxel.T  # normalize each column
    M = mf[0:3, 0:3]

    # transform gradients
    u = dwi_node.GetDiffusionGradients().ToArray()
    u = u * (np.linalg.inv(R) * M).T
    u = u / np.sqrt(np.power(u, 2).sum(1))
    u = np.vstack((u, -u))  # duplicate signal

    param['voxel'] = voxel
    mask = mask_node.GetImageData().ToArray().astype('uint16')

    # pull all seeds
    seeds_ = seeds_node.GetImageData().ToArray()
    seeds = np.zeros(seeds_.shape, dtype='bool')
    for lbl in labels:
        seeds |= (seeds_ == lbl)
    seeds = zip(*seeds.nonzero())

    # ensure seeds
    if len(seeds) == 0:
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "No seeds found for this label"')
        return

    # double check branching
    if 0 < theta_max and theta_max < 5:
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "Nonzero branching angle must be greater than 5 degrees"'
        )
        return
    is_branching = is_2t and param['theta_max'] < 1

    # tractography...
    ff1 = init(S, seeds, u, b, param, is_2t)
    ff2, ff_fa, ff_st, ff_co = [], [], [], []
    t1 = time.time()
    for i in xrange(0, len(ff1)):
        print '[%3.0f%%] (%7d - %7d)' % (100.0 * i / len(ff1), i, len(ff1))
        ff1[i], next, extra = follow(S, u, b, mask, ff1[i], param,
                                     is_branching)
        ff2.extend(next)
        # store extras
        if record_fa: ff_fa.append(extra[0])
        if record_state: ff_st.append(extra[1])
        if record_cov: ff_co.append(extra[2])

    t2 = time.time()
    print 'Time: ', t2 - t1, 'sec'

    if is_branching:
        for i in xrange(0, len(ff2)):
            print '[%3.0f%%] (%7d - %7d)' % (100.0 * i / len(ff2), i, len(ff2))
            f, _ = follow(S, u, b, mask, ff2[i], param, False)
            ff1.append(f)
        print 'Time: ', time.time() - t2, 'sec'

    # build polydata
    ss_x = slicer.vtkPoints()
    lines = slicer.vtkCellArray()
    if record_fa:
        ss_fa = slicer.vtkFloatArray()
        ss_fa.SetNumberOfComponents(1)
        ss_fa.SetName('FA')
    if record_state:
        ss_st = slicer.vtkFloatArray()
        ss_st.SetNumberOfComponents(state_dim)
        ss_st.SetName('state')
    if record_cov:
        ss_co = slicer.vtkFloatArray()
        ss_co.SetNumberOfComponents(state_dim**2)
        ss_co.SetName('covariance')
    cell_id = 0

    for i in xrange(0, len(ff1)):
        f = ff1[i]
        lines.InsertNextCell(len(f))
        if record_fa: f_fa = ff_fa[i]
        if record_state: f_st = ff_st[i]
        if record_cov: f_co = ff_co[i]
        for j in xrange(0, len(f)):
            lines.InsertCellPoint(cell_id)
            cell_id += 1
            x = f[j]
            x = x[::-1]  # HACK
            x_ = np.array(transform(i2r, x)).ravel()  # HACK
            ss_x.InsertNextPoint(x_[0], x_[1], x_[2])
            if record_fa:
                ss_fa.InsertNextValue(255 * f_fa[j])  # FIXME numpy type
            if record_state: ss_st.InsertNextValue(f_fa[j])  # FIXME tuples?
            if record_cov: ss_co.InsertNextValue(f_fa[j])  # FIXME tuples?

    # setup output fibers
    dnode = ff_node.GetDisplayNode()
    if not dnode:
        dnode = slicer.vtkMRMLModelDisplayNode()
        ff_node.GetScene().AddNodeNoNotify(dnode)
        ff_node.SetAndObserveDisplayNodeID(dnode.GetID())
    pd = ff_node.GetPolyData()
    if not pd:
        pd = slicer.vtkPolyData()  # create if necessary
        ff_node.SetAndObservePolyData(pd)
    pd.SetPoints(ss_x)
    if record_fa: pd.GetPointData().SetScalars(ss_fa)
    pd.SetLines(lines)
    pd.Update()
    ff_node.Modified()

    asdf  # HACK flush stdio
예제 #22
0
    def Centerlines(self):
        inModel = self._outModelPrepSelector.GetSelected()
        outModel = self._outModelSelector.GetSelected()
        vModel = self._outVSelector.GetSelected()

        seeds = self._seedsSelector.GetSelected()
        targetSeeds = self._targetSeedsSelector.GetSelected()

        vmtkFound = self.CheckForVmtkLibrary()

        if inModel and outModel and seeds and targetSeeds and vModel and vmtkFound:

            sourceSeedIds = slicer.vtkIdList()
            targetSeedIds = slicer.vtkIdList()

            pointLocator = slicer.vtkPointLocator()
            pointLocator.SetDataSet(inModel.GetPolyData())
            pointLocator.BuildLocator()

            for i in range(seeds.GetNumberOfFiducials()):
                rasPt = seeds.GetNthFiducialXYZ(i)
                id = pointLocator.FindClosestPoint(int(rasPt[0]),
                                                   int(rasPt[1]),
                                                   int(rasPt[2]))
                sourceSeedIds.InsertNextId(id)

            for i in range(targetSeeds.GetNumberOfFiducials()):
                rasPt = targetSeeds.GetNthFiducialXYZ(i)
                id = pointLocator.FindClosestPoint(int(rasPt[0]),
                                                   int(rasPt[1]),
                                                   int(rasPt[2]))
                targetSeedIds.InsertNextId(id)

            result = slicer.vtkPolyData()
            result.DeepCopy(
                self._logic.computeCenterlines(inModel.GetPolyData(),
                                               sourceSeedIds, targetSeedIds))
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())

            vd = slicer.vtkPolyData()
            vd.DeepCopy(self._logic.GetVoronoiDiagram())
            vd.Update()
            vModel.SetAndObservePolyData(vd)
            vModel.SetModifiedSinceRead(1)
            dNode = vModel.GetModelDisplayNode()
            if not dNode:
                dNode = slicer.vtkMRMLModelDisplayNode()
            dNode.SetPolyData(vModel.GetPolyData())
            dNode.SetScalarVisibility(1)
            dNode.SetBackfaceCulling(0)
            dNode.SetActiveScalarName("MaximumInscribedSphereRadius")
            dNode.SetAndObserveColorNodeID(
                self.GetLogic().GetMRMLScene().GetNodesByName(
                    "Labels").GetItemAsObject(0).GetID())
            dNode.SetVisibility(1)
            dNode.SetOpacity(0.5)
            self.GetLogic().GetMRMLScene().AddNode(dNode)

            vModel.SetAndObserveDisplayNodeID(dNode.GetID())
예제 #23
0
def Execute(dwi_node, seeds_node, mask_node, ff_node, \
            record_fa = False, record_state = False, record_cov = False, \
            model="two-tensor", FA_min=.15, GA_min=.10,
            seeds=1, labels=[1],
            Qm=.0030, Ql=100, Rs=.015, theta_max=45):
    for i in xrange(10) : print ''

    is_2t = (model == "two-tensor")

    print 'HACK hardcode 2T'; is_2t = True
    follow = iff(is_2t, follow2t, follow1t)

    state_dim = iff(is_2t, 10, 5)  # dimension of state space

    theta_min = 5  # angle which triggers branch
    param = dict({'FA_min': FA_min, # fractional anisotropy stopping threshold
                  'GA_min': GA_min, # generalized anisotropy stopping threshold
                  'dt': .2,     # forward Euler step size (path integration)
                  'max_len': 250, # stop if fiber gets this long
                  'min_radius': .87,  # stop if fiber curves this much
                  'seeds' : seeds,  # number of seeds in each voxel
                  'theta_min': np.cos(theta_min * np.pi/180),  # angle which triggers branch
                  'theta_max': np.cos(theta_max * np.pi/180),  # angle which triggers branch
                  'min_radius': .87,  # stop if fiber curves this much
                  'record_fa' : record_fa,
                  'record_st' : record_state,
                  'record_co' : record_cov,
                  # Kalman filter parameters
                  'Qm': Qm, # injected angular noise
                  'Ql': Ql, # injected eigenvalue noise
                  'Rs': Rs, # dependent on latent noise in your data
                  'P0': 0.01 * np.eye(state_dim)}) # initial covariance

    from Slicer import slicer

#     foo = slicer.vtkFloatArray()
#     foo.SetNumberOfComponents(1)
#     foo.SetName('foo')

#     foo.InsertNextValue(234)          # Success
#     foo.InsertNextValue(23.4)         # Success
#     foo.InsertNextValue(255 * np.random.rand())       # Success
#     foo.InsertNextValue(np.empty(1,dtype='float32'))  # FAIL
#     foo.InsertNextValue(np.empty(1,dtype='float64'))  # FAIL
#     asdf

    scene = slicer.MRMLScene
    dwi_node = scene.GetNodeByID(dwi_node)
    seeds_node = scene.GetNodeByID(seeds_node)
    mask_node = scene.GetNodeByID(mask_node)
    ff_node = scene.GetNodeByID(ff_node)

    # ensure normalized signal
    bb = dwi_node.GetBValues().ToArray()
    if np.any(bb.sum(1) == 0):
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "Use the \'Normalize Signal\' module to prepare the DWI data"')
        return
    b = bb.mean()
    S = dwi_node.GetImageData().ToArray()
    u = dwi_node.GetDiffusionGradients().ToArray()
    i2r = vtk2mat(dwi_node.GetIJKToRASMatrix,         slicer)
    r2i = vtk2mat(dwi_node.GetRASToIJKMatrix,         slicer)
    mf  = vtk2mat(dwi_node.GetMeasurementFrameMatrix, slicer)
    voxel = np.mat(dwi_node.GetSpacing()).reshape(3,1)
    voxel = voxel[::-1]  # HACK Numpy has [z y x]

    # generalized loading...
    R = r2i[0:3,0:3] / voxel.T  # normalize each column
    M = mf[0:3,0:3]

    # transform gradients
    u = dwi_node.GetDiffusionGradients().ToArray()
    u = u * (np.linalg.inv(R) * M).T
    u = u / np.sqrt(np.power(u,2).sum(1))
    u = np.vstack((u,-u)) # duplicate signal

    param['voxel'] = voxel
    mask  = mask_node.GetImageData().ToArray().astype('uint16')

    # pull all seeds
    seeds_ = seeds_node.GetImageData().ToArray()
    seeds = np.zeros(seeds_.shape, dtype='bool')
    for lbl in labels:
        seeds |= (seeds_ == lbl)
    seeds = zip(*seeds.nonzero())

    # ensure seeds
    if len(seeds) == 0:
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "No seeds found for this label"')
        return

    # double check branching
    if 0 < theta_max and theta_max < 5:
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "Nonzero branching angle must be greater than 5 degrees"')
        return
    is_branching = is_2t and param['theta_max'] < 1

    # tractography...
    ff1 = init(S, seeds, u, b, param, is_2t)
    ff2,ff_fa,ff_st,ff_co = [],[],[],[]
    t1 = time.time()
    for i in xrange(0,len(ff1)):
        print '[%3.0f%%] (%7d - %7d)' % (100.0*i/len(ff1), i, len(ff1))
        ff1[i],next,extra = follow(S,u,b,mask,ff1[i],param,is_branching)
        ff2.extend(next)
        # store extras
        if record_fa:    ff_fa.append(extra[0])
        if record_state: ff_st.append(extra[1])
        if record_cov:   ff_co.append(extra[2])

    t2 = time.time()
    print 'Time: ', t2 - t1, 'sec'

    if is_branching:
        for i in xrange(0,len(ff2)):
            print '[%3.0f%%] (%7d - %7d)' % (100.0*i/len(ff2), i, len(ff2))
            f,_ = follow(S,u,b,mask,ff2[i],param,False)
            ff1.append(f)
        print 'Time: ', time.time() - t2, 'sec'

    # build polydata
    ss_x = slicer.vtkPoints()
    lines = slicer.vtkCellArray()
    if record_fa:    ss_fa = slicer.vtkFloatArray(); ss_fa.SetNumberOfComponents(1);            ss_fa.SetName('FA');
    if record_state: ss_st = slicer.vtkFloatArray(); ss_st.SetNumberOfComponents(state_dim);    ss_st.SetName('state');
    if record_cov:   ss_co = slicer.vtkFloatArray(); ss_co.SetNumberOfComponents(state_dim**2); ss_co.SetName('covariance');
    cell_id = 0

    for i in xrange(0,len(ff1)):
        f = ff1[i]
        lines.InsertNextCell(len(f))
        if record_fa:    f_fa = ff_fa[i]
        if record_state: f_st = ff_st[i]
        if record_cov:   f_co = ff_co[i]
        for j in xrange(0,len(f)):
            lines.InsertCellPoint(cell_id)
            cell_id += 1
            x = f[j]
            x = x[::-1] # HACK
            x_ = np.array(transform(i2r, x)).ravel() # HACK
            ss_x.InsertNextPoint(x_[0],x_[1],x_[2])
            if record_fa    : ss_fa.InsertNextValue(255 * f_fa[j]) # FIXME numpy type
            if record_state : ss_st.InsertNextValue(f_fa[j])  # FIXME tuples?
            if record_cov   : ss_co.InsertNextValue(f_fa[j])  # FIXME tuples?
 

    # setup output fibers
    dnode = ff_node.GetDisplayNode()
    if not dnode:
        dnode = slicer.vtkMRMLModelDisplayNode()
        ff_node.GetScene().AddNodeNoNotify(dnode)
        ff_node.SetAndObserveDisplayNodeID(dnode.GetID())
    pd = ff_node.GetPolyData()
    if not pd:
        pd = slicer.vtkPolyData() # create if necessary
        ff_node.SetAndObservePolyData(pd)
    pd.SetPoints(ss_x)
    if record_fa : pd.GetPointData().SetScalars(ss_fa)
    pd.SetLines(lines)
    pd.Update()
    ff_node.Modified()

    asdf # HACK flush stdio
    def Splitting(self):
        inCeLine = self._inCenterLineSelector.GetSelected()
        inModel = self._inModelSelector.GetSelected()
        outModel = self._outModelSelector.GetSelected()
        split = self._checkButton.GetSelectedState()

        vmtkFound=self.CheckForVmtkLibrary()

        if inCeLine and inModel and outModel and vmtkFound:

            result = slicer.vtkPolyData()
            r=self._logic.branchSplitting(inCeLine.GetPolyData(),inModel.GetPolyData())
            result.DeepCopy(r)
            result.Update()
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(1, 0, 0)
            displayNode.SetScalarVisibility(1)
            displayNode.SetActiveScalarName(self._logic._GroupIdsArrayName)
            displayNode.SetAndObserveColorNodeID(self.GetLogic().GetMRMLScene().GetNodesByName("Labels").GetItemAsObject(0).GetID())
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())

            dNode = inModel.GetModelDisplayNode()
            dNode.SetOpacity(0.0)
            inModel.SetAndObserveDisplayNodeID(dNode.GetID())

            if split == 1:
              ctr=0
              newPdList=self._logic.splitModels(result)
              for i in newPdList:		
                if i.GetNumberOfCells() == 0:
                  continue

                self._helper.debug("Number of Cells are: "+str(i.GetNumberOfCells()))

                ctr+=1
                scene=self.GetLogic().GetMRMLScene()

                newNode=slicer.vtkMRMLModelNode()
                newNode.SetName("VMTKBranchSplittingOut_Branch"+str(ctr))
                newNode.SetScene(scene)
                newNode.SetAndObservePolyData(i)
                scene.AddNode(newNode)

                dn=slicer.vtkMRMLModelDisplayNode()
                dn.SetPolyData(newNode.GetPolyData())
                dn.SetColor(random.random() ,random.random() ,random.random() )		    
                dn.SetBackfaceCulling(0)
                dn.SetSliceIntersectionVisibility(1)
                dn.SetVisibility(1)
                dn.SetOpacity(1.0)
                scene.AddNode(dn)
                
                newNode.SetAndObserveDisplayNodeID(dn.GetName())
예제 #25
0
    def Import(self):
        outModel = self._importModelSelector.GetSelected()
        outputFileName = self._loadButton.GetFileName()

        if outModel and outputFileName:

            self._helper.debug("Start import..")

            points = slicer.vtkPoints()
            conn = slicer.vtkCellArray()
            polyData = slicer.vtkPolyData()

            f = open(outputFileName)
            lines = f.readlines()
            i = 0
            lastId = None
            for line in lines:

                if self._importHeaders.GetSelectedState() == 1 and i == 0:
                    self._helper.debug("Ignore first line..")
                else:
                    # now parse the rest
                    splitted = line.split()

                    x = float(splitted[0])
                    y = float(splitted[1])
                    z = float(splitted[2])

                    if self._importNifti.GetSelectedState() == 1:
                        x = x * (-1)
                        y = y * (-1)

                    #self._helper.debug("Found point: "+str(x)+","+str(y)+","+str(z))

                    id = points.InsertNextPoint(x, y, z)
                    #self._helper.debug(id)

                    if lastId:
                        curLine = slicer.vtkLine()
                        curLine.GetPointIds().SetId(0, lastId)
                        curLine.GetPointIds().SetId(1, id)

                        conn.InsertNextCell(curLine)
                        #conn.InsertCellPoint(id)

                    lastId = id

                i = i + 1

            f.close()

            result = slicer.vtkPolyData()
            result.SetPoints(points)
            result.SetLines(conn)
            result.Update()

            self._helper.debug(result)
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0.8, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
예제 #26
0
    def extractNetwork(self,polydata,seed):

        surfaceTriangulator = slicer.vtkTriangleFilter()
        surfaceTriangulator.SetInput(polydata)
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        # new steps for preparation to avoid problems because of slim models (f.e. at stenosis)
        subdiv = slicer.vtkLinearSubdivisionFilter()
        subdiv.SetInput(surfaceTriangulator.GetOutput())
        subdiv.SetNumberOfSubdivisions(1)
        subdiv.Update()

        # now close the surface
        surfaceCapper = slicer.vtkvmtkCapPolyData()                                                                                                                  
        surfaceCapper.SetInput(subdiv.GetOutput())                                                                                                                  
        surfaceCapper.SetDisplacement(0.0)                                                                                                         
        surfaceCapper.SetInPlaneDisplacement(0.0)                                                                                                  
        surfaceCapper.Update() 

        # re-open it where the seed is placed
        someradius = 1.0

        surface=surfaceCapper.GetOutput()

        pointLocator = slicer.vtkPointLocator()                                                                                                                  
        pointLocator.SetDataSet(surface)                                                                                                           
        pointLocator.BuildLocator() 

        id=pointLocator.FindClosestPoint(int(seed[0]),int(seed[1]),int(seed[2]))

        seed = surface.GetPoint(id)

        sphere = slicer.vtkSphere()
        sphere.SetCenter(seed[0],seed[1],seed[2])
        sphere.SetRadius(someradius)

        clip = slicer.vtkClipPolyData()
        clip.SetInput(surface)
        clip.SetClipFunction(sphere)
        clip.Update()

        opensurface = clip.GetOutput()

        networkExtraction = slicer.vtkvmtkPolyDataNetworkExtraction()                                                                    
        networkExtraction.SetInput(opensurface)                                                                                          
        networkExtraction.SetAdvancementRatio(self._advancementRatio)                                                                      
        networkExtraction.SetRadiusArrayName(self._radiusArrayName)                                                                        
        networkExtraction.SetTopologyArrayName(self._topologyArrayName)                                                                    
        networkExtraction.SetMarksArrayName(self._marksArrayName)                                                                          
        networkExtraction.Update()

        self._parentClass._helper.debug(self._topologyArrayName)

        network=networkExtraction.GetOutput()
        arrayNames = []
        celldata = network.GetCellData()

        for i in range(celldata.GetNumberOfArrays()):                                                                                                      
            array = celldata.GetArray(i)                                                                                                                   
            arrayName = array.GetName()                                                                                                                      
            if arrayName == None:                                                                                                                            
                continue                                                                                                                                     
            if (arrayName[-1]=='_'):                                                                                                                         
                continue                                                                                                                                     
            arrayNames.append(arrayName)

        numberOfPoints = network.GetNumberOfPoints()

        for i in range(numberOfPoints):

            point = network.GetPoint(numberOfPoints - i - 1)

            line = str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2])
            for arrayName in arrayNames:                                                                                                                     
                array = celldata.GetArray(arrayName)                                                                                                       
                for j in range(array.GetNumberOfComponents()):                                                                                               
                    line = line + ' ' + arrayName + ": " + str(array.GetComponent(numberOfPoints - i,j))                                                                         

            self._parentClass._helper.debug(line)

        polyDataNew = slicer.vtkPolyData()
        polyDataNew.DeepCopy(network)
        polyDataNew.Update()

        return polyDataNew