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())
Beispiel #2
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())
Beispiel #3
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())
Beispiel #4
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)
Beispiel #5
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)
    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 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
Beispiel #9
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())
Beispiel #12
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())
Beispiel #13
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())
    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 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