Example #1
0
def createVolume(name,n_row,n_col,n_slice):
        imageSize = [n_row, n_col, n_slice]
        imageSpacing = [1.0, 1.0, 1.0]
        voxelType = vtk.VTK_FLOAT
        
        # Create an empty image volume
        imageData = vtk.vtkImageData()
        imageData.SetDimensions(imageSize)
        imageData.AllocateScalars(voxelType, 1)
        thresholder = vtk.vtkImageThreshold()
        thresholder.SetInputData(imageData)
        thresholder.SetInValue(0)
        thresholder.SetOutValue(0)
        
        # Create volume node
        volumeNode = slicer.vtkMRMLScalarVolumeNode()
        volumeNode.SetSpacing(imageSpacing)
        volumeNode.SetImageDataConnection(thresholder.GetOutputPort())
        
        # Add volume to scene
        slicer.mrmlScene.AddNode(volumeNode)
        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        colorNode = slicer.util.getNode('Grey')
        displayNode.SetAndObserveColorNodeID(colorNode.GetID())
        volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.CreateDefaultStorageNode()
        volumeNode.SetName(name)
        
        return volumeNode
Example #2
0
 def createDummyVolume(self):
   imageData = vtk.vtkImageData()
   imageData.SetDimensions(10,10,10)
   imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
   volumeNode = slicer.vtkMRMLScalarVolumeNode()
   volumeNode.SetAndObserveImageData(imageData)
   displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
   slicer.mrmlScene.AddNode(volumeNode)
   slicer.mrmlScene.AddNode(displayNode)
   volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
   displayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeGrey')
   return volumeNode
  def onSelectROI(self):
    merge=self.outputSelector.currentNode()
    master=self.masterSelector.currentNode()

    if master:
      if merge:
        if not merge.GetImageData():
          self.newROI=True
          imd=vtk.vtkImageData()
          
          mim=master.GetImageData()
          imd.SetDimensions(mim.GetDimensions())
          imd.SetSpacing(mim.GetSpacing())
          imd.SetOrigin(mim.GetOrigin())
          #imd.SetScalarType(vtk.VTK_SHORT)
          imd.AllocateScalars(vtk.VTK_SHORT,1)
          
          masterIJKToRAS = vtk.vtkMatrix4x4()
          master.GetIJKToRASMatrix(masterIJKToRAS)
          merge.SetIJKToRASMatrix(masterIJKToRAS)
          
          nd=slicer.vtkMRMLScalarVolumeDisplayNode()
          slicer.mrmlScene.AddNode(nd)

          merge.AddAndObserveDisplayNodeID(nd.GetID())
          merge.SetAndObserveImageData(imd)

          #workaround to display ROI in Slicer??????
          parameters={}
          parameters["InputVolume"]=merge.GetID()
          parameters["OutputVolume"]=merge.GetID()
          parameters["Type"]="Short"
          castIM=slicer.modules.castscalarvolume
          slicer.cli.run(castIM,None,parameters)
          
          
          coln=slicer.vtkMRMLColorTableNode()
          coln.SetTypeToUser()
          coln.SetNumberOfColors(2)
          coln.SetColor(0,'bg',0,0,0)
          coln.SetColor(1,'fg',1,0,0)
          coln.SetOpacity(0,0)
          coln.SetOpacity(1,1)
          slicer.mrmlScene.AddNode(coln)
          merge.GetDisplayNode().SetAndObserveColorNodeID(coln.GetID())
        else:
          self.newROI=False

        warnings = self.checkForVolumeWarnings(master,merge)
        if warnings != "":
          self.errorDialog( "Warning: %s" % warnings )
          self.outputSelector.setCurrentNode(None)
Example #4
0
    def onGradientInNewVolBtnClicked(self):
        # Result is not right!
        volumeNode = slicer.util.getNode("MRHead")
        ijkToRas = vtk.vtkMatrix4x4()
        volumeNode.GetIJKToRASMatrix(ijkToRas)
        imageData = volumeNode.GetImageData()
        extent = imageData.GetExtent()

        imageSize = imageData.GetDimensions()
        imageSpacing = imageData.GetSpacing()
        voxelType = vtk.VTK_FLOAT

        # Create empty image volume
        imageData_2 = vtk.vtkImageData()
        imageData_2.SetDimensions(imageSize[0] / 2, imageSize[1] / 2, imageSize[2] / 2)
        imageData_2.SetSpacing(imageSpacing)
        imageData_2.AllocateScalars(voxelType, 0)

        thresholder = vtk.vtkImageThreshold()
        thresholder.SetInputData(imageData_2)
        thresholder.SetInValue(0)
        thresholder.SetOutValue(0)

        volumeNode_2 = slicer.vtkMRMLScalarVolumeNode()
        volumeNode_2.SetSpacing(imageSpacing)
        volumeNode_2.SetImageDataConnection(thresholder.GetOutputPort())

        # Add volume to scene
        scene = slicer.mrmlScene
        scene.AddNode(volumeNode_2)
        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        scene.AddNode(displayNode)
        colorNode = slicer.util.getNode("Grey")
        displayNode.SetAndObserveColorNodeID(colorNode.GetID())
        volumeNode_2.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode_2.CreateDefaultStorageNode()

        # npData = slicer.util.array('MRHead')
        impVol = vtk.vtkImplicitVolume()
        impVol.SetVolume(imageData)

        for k in xrange(extent[4], extent[5] / 2 + 1):
            for j in xrange(extent[2], extent[3] / 2 + 1):
                for i in xrange(extent[0], extent[1] / 2 + 1):
                    g = impVol.FunctionGradient(i, j, k)
                    gradient = math.sqrt(g[0] ** 2 + g[1] ** 2 + g[2] ** 2)
                    imageData_2.SetScalarComponentFromFloat(i, j, k, 0, gradient)

        imageData_2.Modified()
    def AddVolumeNode(self):
        # Create empty volume node
        volumeNode = slicer.mrmlScene.GetNthNodeByClass(1, 'vtkMRMLScalarVolumeNode')
        if volumeNode == None:
            volumeNode = slicer.vtkMRMLScalarVolumeNode()
            slicer.mrmlScene.AddNode(volumeNode)

        displayNode = slicer.mrmlScene.GetNthNodeByClass(1,'vtkMRMLScalarVolumeDisplayNode')
        if displayNode == None:
            displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        colorNode = slicer.util.getNode('Grey')
        displayNode.SetAndObserveColorNodeID(colorNode.GetID())
        volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.CreateDefaultStorageNode()
        volumeNode.SetName("Volume Node")
    def AddSegmentNode(self, modelNode, volumeLabel):
        #This function creates a segmentation from the output model (ie cropped breast models)
        # and computed the volume of the segmentation, this is done to ensure the volume is computed correctly

        segmentationNode = slicer.vtkMRMLSegmentationNode()
        slicer.mrmlScene.AddNode(segmentationNode)

        displayNode = slicer.mrmlScene.GetNthNodeByClass(1, 'vtkMRMLScalarVolumeDisplayNode')
        if displayNode == None:
            displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()

        segmentationNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        segmentationNode.SetName("Model Segmentation Node")

        slicer.modules.segmentations.logic().ImportModelToSegmentationNode(modelNode, segmentationNode)
        segment = segmentationNode.GetSegmentation().GetNthSegment(0)
        segBinaryLabelName = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()
        segmentLabelmap = segment.GetRepresentation(segBinaryLabelName)
        # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value
        labelValue = 1
        backgroundValue = 0
        thresh = vtk.vtkImageThreshold()
        thresh.SetInputData(segmentLabelmap)
        thresh.ThresholdByLower(0)
        thresh.SetInValue(backgroundValue)
        thresh.SetOutValue(labelValue)
        thresh.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR)
        thresh.Update()

        #  Use binary labelmap as a stencil
        stencil = vtk.vtkImageToImageStencil()
        stencil.SetInputData(thresh.GetOutput())
        stencil.ThresholdByUpper(labelValue)
        stencil.Update()

        stat = vtk.vtkImageAccumulate()
        stat.SetInputData(thresh.GetOutput())
        stat.SetStencilData(stencil.GetOutput())
        stat.Update()

        # Add data to statistics list
        cubicMMPerVoxel = reduce(lambda x, y: x * y, segmentLabelmap.GetSpacing())
        ccPerCubicMM = 0.001
        stats = {}
        volume = round(stat.GetVoxelCount() * cubicMMPerVoxel * ccPerCubicMM, 0)
        volumeLabel.setText(volume)
        slicer.mrmlScene.RemoveNode(segmentationNode)
        return volume
def update_visualisation_settings(volumeNode,array):
    """
    Updates the window, level and colormap for the volumeNode based on values in the array
    :param volumeNode: Volume node to be updated
    :param array: Array to derive optimal visualisation values
    :return:
    """
    displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
    displayNode.SetAutoWindowLevel(0)
    max_val = array.max()
    min_val = array.min()
    displayNode.SetWindowLevel(max_val - min_val, (max_val - min_val) / 2)
    slicer.mrmlScene.AddNode(displayNode)
    colorNode = slicer.util.getNode('Viridis')
    displayNode.SetAndObserveColorNodeID(colorNode.GetID())
    volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
Example #8
0
    def onNewVolBtnClicked(self):
        imageSize = [128] * 3
        imageSpacing = [1.0] * 3
        voxelType = vtk.VTK_UNSIGNED_CHAR

        # Create an empty image volume
        imageData = vtk.vtkImageData()
        imageData.SetDimensions(imageSize)
        imageData.AllocateScalars(voxelType, 64)

        thresholder = vtk.vtkImageThreshold()
        thresholder.SetInputData(imageData)
        thresholder.SetInValue(0)
        thresholder.SetOutValue(0)

        # Create volume node
        volumeNode = slicer.vtkMRMLScalarVolumeNode()
        volumeNode.SetSpacing(imageSpacing)
        volumeNode.SetImageDataConnection(thresholder.GetOutputPort())

        # Add volume to scene
        scene = slicer.mrmlScene
        scene.AddNode(volumeNode)
        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        scene.AddNode(displayNode)
        colorNode = slicer.util.getNode("Grey")
        displayNode.SetAndObserveColorNodeID(colorNode.GetID())
        volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.CreateDefaultStorageNode()

        # Show the new volume in the Slice view
        applicationLogic = slicer.app.applicationLogic()
        selectionNode = applicationLogic.GetSelectionNode()
        selectionNode.SetSecondaryVolumeID(volumeNode.GetID())
        applicationLogic.PropagateForegroundVolumeSelection(0)

        # Center the 3D View on the scene
        # It works only after showing the 3D scene
        layoutManager = slicer.app.layoutManager()
        threeDWidget = layoutManager.threeDWidget(0)
        threeDView = threeDWidget.threeDView()
        threeDView.resetFocalPoint()
Example #9
0
  def clipVolumeWithModel(self, inputVolume, clippingModel, clipOutsideSurface, fillValue, outputVolume):
    """
    Fill voxels of the input volume inside/outside the clipping model with the provided fill value
    """
    
    # Determine the transform between the box and the image IJK coordinate systems
    
    rasToModel = vtk.vtkMatrix4x4()    
    if clippingModel.GetTransformNodeID() != None:
      modelTransformNode = slicer.mrmlScene.GetNodeByID(clippingModel.GetTransformNodeID())
      boxToRas = vtk.vtkMatrix4x4()
      modelTransformNode.GetMatrixTransformToWorld(boxToRas)
      rasToModel.DeepCopy(boxToRas)
      rasToModel.Invert()
      
    ijkToRas = vtk.vtkMatrix4x4()
    inputVolume.GetIJKToRASMatrix( ijkToRas )

    ijkToModel = vtk.vtkMatrix4x4()
    vtk.vtkMatrix4x4.Multiply4x4(rasToModel,ijkToRas,ijkToModel)
    modelToIjkTransform = vtk.vtkTransform()
    modelToIjkTransform.SetMatrix(ijkToModel)
    modelToIjkTransform.Inverse()
    
    transformModelToIjk=vtk.vtkTransformPolyDataFilter()
    transformModelToIjk.SetTransform(modelToIjkTransform)
    transformModelToIjk.SetInputConnection(clippingModel.GetPolyDataConnection())

    # Use the stencil to fill the volume
    
    # Convert model to stencil
    polyToStencil = vtk.vtkPolyDataToImageStencil()
    polyToStencil.SetInputConnection(transformModelToIjk.GetOutputPort())
    polyToStencil.SetOutputSpacing(inputVolume.GetImageData().GetSpacing())
    polyToStencil.SetOutputOrigin(inputVolume.GetImageData().GetOrigin())
    polyToStencil.SetOutputWholeExtent(inputVolume.GetImageData().GetExtent())
    
    # Apply the stencil to the volume
    stencilToImage=vtk.vtkImageStencil()
    stencilToImage.SetInputConnection(inputVolume.GetImageDataConnection())
    stencilToImage.SetStencilConnection(polyToStencil.GetOutputPort())
    if clipOutsideSurface:
      stencilToImage.ReverseStencilOff()
    else:
      stencilToImage.ReverseStencilOn()
    stencilToImage.SetBackgroundValue(fillValue)
    stencilToImage.Update()

    # Update the volume with the stencil operation result
    outputImageData = vtk.vtkImageData()
    outputImageData.DeepCopy(stencilToImage.GetOutput())
    
    outputVolume.SetAndObserveImageData(outputImageData);
    outputVolume.SetIJKToRASMatrix(ijkToRas)

    # Add a default display node to output volume node if it does not exist yet
    if not outputVolume.GetDisplayNode:
      displayNode=slicer.vtkMRMLScalarVolumeDisplayNode()
      displayNode.SetAndObserveColorNodeID("vtkMRMLColorTableNodeGrey")
      slicer.mrmlScene.AddNode(displayNode)
      outputVolume.SetAndObserveDisplayNodeID(displayNode.GetID())

    return True
Example #10
0
    def run(self,
            inputVolume,
            outputVolume,
            imageThreshold,
            enableScreenshots=0):

        #Pr1 = [-19.8, 1.6, 62.7]
        #Pr2 = [-31.5, 10.8, 62.7]
        Pr2 = [-8.5, 4.1, 4.3]
        Pr1 = [-8.6, 11.8, 0.7]
        Uretra = [89, 79, 13, 1]

        UretraMatrix = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe1 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe2 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe3 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])

        fidList = slicer.util.getNode('urethra')
        numFids = fidList.GetNumberOfFiducials()
        print(numFids)
        for i in range(numFids):
            ras = [0, 0, 0]
            fidList.GetNthFiducialPosition(i, ras)
            UretraMatrix[i, ] = ras

        fidList2 = slicer.util.getNode("probe1")
        numFids2 = fidList2.GetNumberOfFiducials()
        for i in range(numFids2):
            ras = [0, 0, 0]
            fidList2.GetNthFiducialPosition(i, ras)
            probe1[i, ] = ras
            probe1[i, 2] = probe1[i, 2] - 10.0

        fidList3 = slicer.util.getNode('probe2')
        numFids3 = fidList2.GetNumberOfFiducials()
        for i in range(numFids3):
            ras = [0, 0, 0]
            fidList3.GetNthFiducialPosition(i, ras)
            probe2[i, ] = ras
            probe2[i, 2] = probe2[i, 2] - 10.0

        nofProbes = 2
        try:
            fidList4 = slicer.util.getNode('probe3')
            numFids4 = fidList2.GetNumberOfFiducials()
            for i in range(numFids4):
                ras = [0, 0, 0]
                fidList4.GetNthFiducialPosition(i, ras)
                probe3[i, ] = ras
                probe3[i, 2] = probe3[i, 2] - 10.0
            nofProbes = 3
        except:
            nofProbes = 2

        probes = numpy.concatenate((probe1[0, ], probe2[0, ]), axis=0)
        print(probes)
        print('====Files loaded====')

        resultFileName = "Table-FullImage-1y"
        resultFilePath = '/Users/pedro/Projects/MLCryo/Cases' + '/' + resultFileName
        resultFile = open(resultFilePath, 'a')

        resultFile.write(
            "value; PosX; PosY ; PosZ; pr1X; Pr1Y ; Pr1Z; pr2X; Pr2Y ; Pr2Z ; Urx ; Ury ; Urz \n"
        )

        IjkToRasMatrix = vtk.vtkMatrix4x4()
        inputVolume.GetIJKToRASMatrix(IjkToRasMatrix)

        #Be careful voxel array changes x for z
        voxelArray = slicer.util.arrayFromVolume(inputVolume)

        nOfSlices = 17

        imageData = vtk.vtkImageData()
        imageData.SetDimensions(192, 168, nOfSlices)
        print(inputVolume.GetSpacing())
        imageData.SetSpacing(0.9, 0.9, 3.6)
        imageData.SetOrigin(72, 83, 26)
        imageData.AllocateScalars(vtk.VTK_FLOAT, 1)

        img3 = numpy.zeros([nOfSlices, 168, 192])
        img4 = numpy.zeros([nOfSlices, 168, 192])
        img2 = numpy.zeros([nOfSlices, 168, 192])
        probs = numpy.zeros([7000000, 1, 1])

        rasToijkMatrix = vtk.vtkMatrix4x4()
        inputVolume.GetRASToIJKMatrix(rasToijkMatrix)
        lim = self.getLimits(probes, rasToijkMatrix)

        imageData.SetDimensions(192, 168, nOfSlices)
        imageData.SetSpacing(1, 1, 1)
        imageData.AllocateScalars(vtk.VTK_FLOAT, 1)

        f = 0
        for i in range(lim[0], lim[1]):
            for j in range(lim[2], lim[3]):
                for k in range(lim[4], lim[5]):
                    p = IjkToRasMatrix.MultiplyDoublePoint([i, j, k, 1])
                    resultFile.write(
                        "%02d; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f; %02f ; %02f ; %02f\n"
                        % (voxelArray[k, j, i], p[0], p[1], p[2], probe1[0, 0],
                           probe1[0, 1], probe1[0, 2], probe2[0, 0],
                           probe2[0, 1], probe2[0, 2], UretraMatrix[k, 0],
                           UretraMatrix[k, 1], UretraMatrix[k, 2]))
                    Pr1 = [probe1[0, 0], probe1[0, 1], probe1[0, 2]]
                    Pr2 = [probe2[0, 0], probe2[0, 1], probe2[0, 2]]
                    Pr3 = [probe3[0, 0], probe3[0, 1], probe3[0, 2]]
                    Uretra = [
                        UretraMatrix[k, 0], UretraMatrix[k, 1], UretraMatrix[k,
                                                                             2]
                    ]
                    if nofProbes == 3:
                        prob = self.GetDistances3(Pr1, Pr2, Pr3, p, Uretra)
                    else:
                        prob = self.GetDistances(Pr1, Pr2, p, Uretra)
                    imageData.SetScalarComponentFromFloat(
                        k, j, i, 0, 1.0 * prob)
                    img2[k, j, i] = 1.0 * prob
                    img4[k, j, i] = voxelArray[k, j, i]
                    probs[f, 0, 0] = prob
                    f = f + 1
                    if prob > 0.4:
                        #imageData.SetScalarComponentFromFloat(i, j, k, 0, 1.0)
                        img3[k, j, i] = 1.0

        #scipy.misc.imsave('/Users/pedro/Projects/MLCryo/Test.jpg',img2[12,:,:])
        print("limites")
        print(lim)

        volumeNode = slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNode, img3)

        volumeNode2 = slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNode2, img2)
        volumeNode2.SetSpacing(0.3, 0.3, 3.6)
        volumeNode2.SetIJKToRASMatrix(IjkToRasMatrix)
        slicer.mrmlScene.AddNode(volumeNode2)

        volumeNodeImage = slicer.vtkMRMLScalarVolumeNode(
        )  #slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNodeImage, img2)

        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()

        volumeNodeImage.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.SetSpacing(0.3, 0.3, 3.6)
        #    volumeNodeImage.SetOrigin(72, 83, 26)
        volumeNodeImage.SetIJKToRASMatrix(IjkToRasMatrix)
        volumeNode.SetIJKToRASMatrix(IjkToRasMatrix)
        slicer.mrmlScene.AddNode(volumeNodeImage)
        slicer.mrmlScene.AddNode(volumeNode)
        slicer.mrmlScene.AddNode(displayNode)
        displayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeGrey')

        if not self.isValidInputOutputData(inputVolume, outputVolume):
            slicer.util.errorDisplay(
                'Input volume is the same as output volume. Choose a different output volume.'
            )
            return False

        logging.info('Processing started')

        # Compute the thresholded output volume using the Threshold Scalar Volume CLI module
        cliParams = {
            'InputVolume': inputVolume.GetID(),
            'OutputVolume': outputVolume.GetID(),
            'ThresholdValue': imageThreshold,
            'ThresholdType': 'Above'
        }
        cliNode = slicer.cli.run(slicer.modules.thresholdscalarvolume,
                                 None,
                                 cliParams,
                                 wait_for_completion=True)

        # Capture screenshot
        if enableScreenshots:
            self.takeScreenshot('CryoTest-Start', 'MyScreenshot', -1)

        logging.info('Processing completed')

        return True
Example #11
0
    def run(self,
            inputVolume,
            outputVolume,
            imageThreshold,
            enableScreenshots=0):

        #Pr1 = [-19.8, 1.6, 62.7]
        #Pr2 = [-31.5, 10.8, 62.7]
        Pr2 = [-8.5, 4.1, 4.3]
        Pr1 = [-8.6, 11.8, 0.7]
        Uretra = [89, 79, 13, 1]

        UretraMatrix = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
                                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe1 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe2 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
        probe3 = numpy.matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])

        fidList = slicer.util.getNode('urethra')
        numFids = fidList.GetNumberOfFiducials()
        print(numFids)
        for i in range(numFids):
            ras = [0, 0, 0]
            fidList.GetNthFiducialPosition(i, ras)
            UretraMatrix[i, ] = ras

        fidList2 = slicer.util.getNode("probe1")
        numFids2 = fidList2.GetNumberOfFiducials()
        for i in range(numFids2):
            ras = [0, 0, 0]
            fidList2.GetNthFiducialPosition(i, ras)
            probe1[i, ] = ras
            probe1[i, 2] = probe1[i, 2] - 10.0

        fidList3 = slicer.util.getNode('probe2')
        numFids3 = fidList2.GetNumberOfFiducials()
        for i in range(numFids3):
            ras = [0, 0, 0]
            fidList3.GetNthFiducialPosition(i, ras)
            probe2[i, ] = ras
            probe2[i, 2] = probe2[i, 2] - 10.0

        nofProbes = 2
        try:
            fidList4 = slicer.util.getNode('probe3')
            numFids4 = fidList2.GetNumberOfFiducials()
            for i in range(numFids4):
                ras = [0, 0, 0]
                fidList4.GetNthFiducialPosition(i, ras)
                probe3[i, ] = ras
                probe3[i, 2] = probe3[i, 2] - 10.0
            nofProbes = 3
        except:
            nofProbes = 2

        probes = numpy.concatenate((probe1[0, ], probe2[0, ]), axis=0)
        print(probes)
        print('====Files loaded====')
        print(nofProbes)

        resultFileName = "Table-FullImage-1y"
        resultFilePath = '/Users/pedro/Projects/MLCryo/Cases' + '/' + resultFileName
        #resultFile = open(resultFilePath, 'a')

        #resultFile.write("value; PosX; PosY ; PosZ; pr1X; Pr1Y ; Pr1Z; pr2X; Pr2Y ; Pr2Z ; Urx ; Ury ; Urz \n")

        IjkToRasMatrix = vtk.vtkMatrix4x4()
        inputVolume.GetIJKToRASMatrix(IjkToRasMatrix)

        #Be careful voxel array changes x for z
        voxelArray = slicer.util.arrayFromVolume(inputVolume)

        nOfSlices = NOFSLICES - 1

        imageData = vtk.vtkImageData()
        imageData.SetDimensions(X, Y, nOfSlices)
        print(inputVolume.GetSpacing())
        imageData.SetSpacing(0.9, 0.9, 3.6)
        imageData.SetOrigin(72, 83, 26)
        imageData.AllocateScalars(vtk.VTK_FLOAT, 1)

        img3 = numpy.zeros([nOfSlices, Y, X])
        img4 = numpy.zeros([nOfSlices, Y, X])
        img2 = numpy.zeros([nOfSlices, Y, X])
        probs = numpy.zeros([7000000, 1, 1])

        rasToijkMatrix = vtk.vtkMatrix4x4()
        inputVolume.GetRASToIJKMatrix(rasToijkMatrix)
        lim = self.getLimits(probes, rasToijkMatrix)

        rgb = numpy.zeros((Y, X, 3), dtype=numpy.uint8)
        f = 0
        for k in range(0, nOfSlices):
            for i in range(lim[0], lim[1]):
                for j in range(lim[2], lim[3]):
                    p = IjkToRasMatrix.MultiplyDoublePoint([i, j, k, 1])
                    #resultFile.write("%02d; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f ; %02f; %02f ; %02f ; %02f\n" % (voxelArray[k,j,i],p[0],p[1],p[2],probe1[0,0],probe1[0,1],probe1[0,2],probe2[0,0],probe2[0,1],probe2[0,2],UretraMatrix[k,0],UretraMatrix[k,1],UretraMatrix[k,2]))
                    Pr1 = [probe1[0, 0], probe1[0, 1], probe1[0, 2]]
                    Pr2 = [probe2[0, 0], probe2[0, 1], probe2[0, 2]]
                    Pr3 = [probe3[0, 0], probe3[0, 1], probe3[0, 2]]
                    Uretra = [
                        UretraMatrix[k, 0], UretraMatrix[k, 1], UretraMatrix[k,
                                                                             2]
                    ]
                    if nofProbes == 3:
                        prob = self.GetDistances3(Pr1, Pr2, Pr3, p, Uretra)
                    else:
                        prob = self.GetDistances(Pr1, Pr2, p, Uretra)
                    imageData.SetScalarComponentFromFloat(
                        k, j, i, 0, 1.0 * prob)
                    img2[k, j, i] = 1.0 * prob
                    img4[k, j, i] = voxelArray[k, j, i]
                    probs[f, 0, 0] = prob
                    f = f + 1

                    temp = (p[0] - probe1[0, 0]) * (p[0] - probe1[0, 0]) + (
                        p[1] - probe1[0, 1]) * (p[1] - probe1[0, 1]) + (
                            p[2] - probe1[0, 2]) * (p[2] - probe1[0, 2])
                    temp2 = (p[0] - probe2[0, 0]) * (p[0] - probe2[0, 0]) + (
                        p[1] - probe2[0, 1]) * (p[1] - probe2[0, 1]) + (
                            p[2] - probe2[0, 2]) * (p[2] - probe2[0, 2])
                    tempZ = (p[2] - probe1[0, 2]) * (p[2] - probe1[0, 2]) + (
                        p[2] - probe2[0, 2]) * (p[2] - probe2[0, 2])
                    temp3 = (p[0] - Uretra[0]) * (p[0] - Uretra[0]) + (
                        p[1] - Uretra[1]) * (p[1] - Uretra[1])
                    rgb[j, i, 2] = 40 * (numpy.log(numpy.sqrt(temp)))
                    rgb[j, i, 1] = 40 * (numpy.log(numpy.sqrt(temp2)))

                    if (numpy.abs(tempZ) < 1.0):
                        tempZ = 1
                    rgb[j, i, 0] = 215 - 20 * numpy.log(
                        numpy.abs(tempZ))  #255/numpy.sqrt(temp3)
                    if (temp3 < 5):
                        rgb[j, i, 0] = 255
                        rgb[j, i, 1] = 255
                        rgb[j, i, 2] = 255

            print(rgb[100, 100, 0])
            Case = CASE
            filename = '/Users/pedro/Dropbox (Partners HealthCare)/DeepLearningCryo/New' + '/' + Case + '/' + str(
                k) + '.png'
            imageio.imwrite(filename, rgb)
            img1 = 255 * voxelArray[k, 0:Y - 1, 0:X - 1]
            filename2 = '/Users/pedro/Dropbox (Partners HealthCare)/DeepLearningCryo/New' + '/' + Case + '/LabeL_' + str(
                k) + '.png'
            imageio.imwrite(filename2, img1)

        print("limites")

        volumeNode = slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNode, img3)

        volumeNode2 = slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNode2, img2)
        volumeNode2.SetSpacing(0.3, 0.3, 3.6)
        volumeNode2.SetIJKToRASMatrix(IjkToRasMatrix)
        volumeNode2.SetName("ProbMap")
        slicer.mrmlScene.AddNode(volumeNode2)

        volumeNodeImage = slicer.vtkMRMLScalarVolumeNode(
        )  #slicer.vtkMRMLLabelMapVolumeNode()
        slicer.util.updateVolumeFromArray(volumeNodeImage, img2)

        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()

        volumeNodeImage.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.SetSpacing(0.3, 0.3, 3.6)
        #    volumeNodeImage.SetOrigin(72, 83, 26)
        volumeNodeImage.SetIJKToRASMatrix(IjkToRasMatrix)
        volumeNode.SetIJKToRASMatrix(IjkToRasMatrix)
        slicer.mrmlScene.AddNode(volumeNodeImage)
        slicer.mrmlScene.AddNode(volumeNode)
        slicer.mrmlScene.AddNode(displayNode)
        displayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeGrey')

        if not self.isValidInputOutputData(inputVolume, outputVolume):
            slicer.util.errorDisplay(
                'Input volume is the same as output volume. Choose a different output volume.'
            )
            return False

        logging.info('Processing started')

        # Compute the thresholded output volume using the Threshold Scalar Volume CLI module
        cliParams = {
            'InputVolume': inputVolume.GetID(),
            'OutputVolume': outputVolume.GetID(),
            'ThresholdValue': imageThreshold,
            'ThresholdType': 'Above'
        }
        cliNode = slicer.cli.run(slicer.modules.thresholdscalarvolume,
                                 None,
                                 cliParams,
                                 wait_for_completion=True)

        # Capture screenshot
        if enableScreenshots:
            self.takeScreenshot('CryoTest-Start', 'MyScreenshot', -1)

        logging.info('Processing completed')

        return True