Example #1
0
 def checkAndSetLUT(self):
   # Default to module color table
   self.resourcesPath = os.path.join(slicer.modules.slicerpathology.path.replace(self.moduleName+".py",""), 'Resources')
   self.colorFile = os.path.join(self.resourcesPath, "Colors/SlicerPathology.csv")
   self.customLUTLabel.setText('Using Default LUT')
   try:
       self.editorWidget.helper.structureListWidget.merge = None
   except AttributeError:
       pass
   # setup the color table, make sure SlicerPathology LUT is a singleton
   allColorTableNodes = slicer.util.getNodes('vtkMRMLColorTableNode*').values()
   for ctn in allColorTableNodes:
       #print "color: "+ctn.GetName()
       if ctn.GetName() == 'SlicerPathologyColor':
           slicer.mrmlScene.RemoveNode(ctn)
           break
   self.SlicerPathologyColorNode = slicer.vtkMRMLColorTableNode()
   colorNode = self.SlicerPathologyColorNode
   colorNode.SetName('SlicerPathologyColor')
   slicer.mrmlScene.AddNode(colorNode)
   colorNode.SetTypeToUser()
   with open(self.colorFile) as f:
       n = sum(1 for line in f)
   colorNode.SetNumberOfColors(n-1)
   colorNode.NamesInitialisedOn()
   import csv
   self.structureNames = []
   with open(self.colorFile, 'rb') as csvfile:
       reader = csv.DictReader(csvfile, delimiter=',')
       for index,row in enumerate(reader):
           success = colorNode.SetColor(index ,row['Label'],float(row['R'])/255,float(row['G'])/255,float(row['B'])/255,float(row['A']))
           if not success:
               print "color %s could not be set" % row['Label']
           self.structureNames.append(row['Label'])
Example #2
0
    def fit(self, atlasName='DevelopmentalAtlas', range=[0, 5]):
        """
    Create a volume of the slope across the range of years.

    least squares notation from:
    http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html
    """
        ijkToRAS = vtk.vtkMatrix4x4()
        atlasVolume = slicer.util.getNode(atlasName)
        atlasVolume.GetIJKToRASMatrix(ijkToRAS)
        fitVolume = slicer.vtkMRMLScalarVolumeNode()
        fitVolume.SetIJKToRASMatrix(ijkToRAS)
        ageRange = str(range).replace('[', '(').replace(']', ')')
        fitName = 'Slope_' + ageRange + '_' + atlasName
        fitVolume.SetName(fitName)

        colorNode = slicer.vtkMRMLColorTableNode()
        colorNode.SetTypeToGrey()
        slicer.mrmlScene.AddNode(colorNode)

        fitDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        fitDisplayNode.SetAutoWindowLevel(False)
        fitDisplayNode.SetWindow(10)
        fitDisplayNode.SetLevel(45)
        slicer.mrmlScene.AddNode(fitDisplayNode)
        fitDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())

        fitImage = vtk.vtkImageData()
        fitImage.ShallowCopy(atlasVolume.GetImageData())
        fitImage.AllocateScalars(vtk.VTK_FLOAT, 1)
        fitVolume.SetAndObserveImageData(fitImage)

        slicer.mrmlScene.AddNode(fitVolume)
        fitVolume.SetAndObserveDisplayNodeID(fitDisplayNode.GetID())

        fitArray = slicer.util.array(fitName)
        atlasArray = slicer.util.array(atlasName)

        # make a regression against a scale more or less like the multivolume plot
        timePoints = self.agesInYears[range[0]:range[1]]
        timePoints = map(lambda x: x * 1000., timePoints)
        A = numpy.vstack([timePoints, numpy.ones(len(timePoints))]).T

        slices, rows, columns, frames = atlasArray.shape
        for slice in xrange(slices):
            for row in xrange(rows):
                for column in xrange(columns):
                    if atlasArray[slice, row, column, 0] == 0:
                        fit = 0
                    else:
                        series = atlasArray[slice, row,
                                            column][range[0]:range[1]]
                        slope, intercept = numpy.linalg.lstsq(A, series)[0]
                        fit = -1. * numpy.degrees(numpy.arctan(slope))
                    fitArray[slice, row, column] = fit

        return fitVolume
Example #3
0
  def fit(self,atlasName='DevelopmentalAtlas', range=[0,5]):
    """
    Create a volume of the slope across the range of years.

    least squares notation from:
    http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html
    """
    ijkToRAS = vtk.vtkMatrix4x4()
    atlasVolume = slicer.util.getNode(atlasName)
    atlasVolume.GetIJKToRASMatrix(ijkToRAS)
    fitVolume = slicer.vtkMRMLScalarVolumeNode()
    fitVolume.SetIJKToRASMatrix(ijkToRAS)
    ageRange = str(range).replace('[','(').replace(']',')')
    fitName = 'Slope_'+ageRange+'_'+atlasName
    fitVolume.SetName(fitName)

    colorNode = slicer.vtkMRMLColorTableNode()
    colorNode.SetTypeToGrey()
    slicer.mrmlScene.AddNode(colorNode)

    fitDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
    fitDisplayNode.SetAutoWindowLevel(False)
    fitDisplayNode.SetWindow(10)
    fitDisplayNode.SetLevel(45)
    slicer.mrmlScene.AddNode(fitDisplayNode)
    fitDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())

    fitImage = vtk.vtkImageData()
    fitImage.ShallowCopy(atlasVolume.GetImageData())
    fitImage.AllocateScalars(vtk.VTK_FLOAT, 1)
    fitVolume.SetAndObserveImageData(fitImage)

    slicer.mrmlScene.AddNode(fitVolume)
    fitVolume.SetAndObserveDisplayNodeID(fitDisplayNode.GetID())

    fitArray = slicer.util.array(fitName)
    atlasArray = slicer.util.array(atlasName)

    # make a regression against a scale more or less like the multivolume plot
    timePoints = self.agesInYears[range[0]:range[1]]
    timePoints = map(lambda x : x * 1000., timePoints)
    A = numpy.vstack([timePoints, numpy.ones(len(timePoints))]).T

    slices, rows, columns, frames = atlasArray.shape
    for slice in xrange(slices):
      for row in xrange(rows):
        for column in xrange(columns):
          if atlasArray[slice, row, column, 0] == 0:
            fit = 0
          else:
            series = atlasArray[slice, row, column][range[0]:range[1]]
            slope, intercept = numpy.linalg.lstsq(A, series)[0]
            fit = -1. * numpy.degrees(numpy.arctan(slope))
          fitArray[slice, row, column] = fit

    return fitVolume
  def createFociVisualizationColorMap(self, minimumValue, maximumValue):
    if (minimumValue < 0):  
      numberOfCoolColors = -(minimumValue)
    else:
      numberOfCoolColors = 0
    if (maximumValue > 0):  
      numberOfHotColors = maximumValue + 1  # includes zero
    else:
      numberOfHotColors = 0  
      
    #print "number of cool colors = " + str(numberOfCoolColors)  
    #print "number of hot colors (including zero) = " + str(numberOfHotColors)
    
    colorNode = slicer.util.getNode(self.FOCI_DETECTION_COLORMAP_NAME)
    if colorNode is None:
      colorNode = slicer.vtkMRMLColorTableNode() 
      slicer.mrmlScene.AddNode(colorNode)
      colorNode.SetName(self.FOCI_DETECTION_COLORMAP_NAME)
      
    colorNode.SetTypeToUser()   
    colorNode.SetNumberOfColors(numberOfCoolColors + numberOfHotColors);
    # colorNode.SetColor(0, "zero", 0.0, 0.0, 0.0, 1.0);
    # colorNode.SetColor(1, "one", 1.0, 0.0, 0.0, 1.0);
    # colorNode.SetColor(2, "two", 0.0, 1.0, 0.0, 1.0);
    colorNode.SetNamesFromColors()
    
    
    ''' cool color map in Matlab     
    r = (0:m-1)'/max(m-1,1);
    c = [r 1-r ones(m,1)]; 
    '''
    for colorIndex in xrange(0, numberOfCoolColors):
      r = np.double(numberOfCoolColors - 1 - colorIndex) / (numberOfCoolColors)  
      colorNode.SetColor(colorIndex, r, 1 - r, 1, 1.0);  
      #print "cool color index = " + str(colorIndex)
   
    
    
    '''   hot color table in Matlab
     r = [(1:n)'/n; ones(m-n,1)];
     g = [zeros(n,1); (1:n)'/n; ones(m-2*n,1)];
     b = [zeros(2*n,1); (1:m-2*n)'/(m-2*n)]; 
    '''  
    n = 3 * numberOfHotColors / 8  # fix
    '''   hot color table in Python  '''
    r = np.concatenate((np.double(range(1, n + 1)) / n , np.ones(numberOfHotColors - n)))
    g = np.concatenate((np.zeros(n), np.double(range(1, n + 1)) / n, np.ones(numberOfHotColors - 2 * n)))
    b = np.concatenate((np.zeros(2 * n), np.double(range(1, numberOfHotColors - 2 * n + 1)) / (numberOfHotColors - 2 * n)))
    
    for colorIndex in xrange(0, numberOfHotColors):
      colorNode.SetColor(numberOfCoolColors + colorIndex, r[colorIndex], g[colorIndex], b[colorIndex], 1.0); 
      #print "hot color index = " + str(numberOfCoolColors + colorIndex)
    colorNode.SetOpacity(numberOfCoolColors, 0);  

    '''
Example #5
0
 def createColorTable(self):
     """ """
     self.logging.debug("call")
     self.colorTableNode = slicer.vtkMRMLColorTableNode()
     self.colorTableNode.SetFileName(os.path.join(__slicer_module__, 'Resources', 'ColorFile', self.colorTable))
     self.colorTableNode.SetName(self.colorTable[:-4])
     storage = self.colorTableNode.CreateDefaultStorageNode()
     slicer.mrmlScene.AddNode(storage)
     self.colorTableNode.AddAndObserveStorageNodeID(storage.GetID())
     slicer.mrmlScene.AddNode(self.colorTableNode)
     storage.SetFileName(self.colorTableNode.GetFileName())
     storage.SetReadState(True)
     storage.ReadData(self.colorTableNode, True)
Example #6
0
 def createColorTable(self):
     """
     """
     self.colorTableNode = slicer.vtkMRMLColorTableNode()
     self.colorTableNode.SetFileName(
         os.path.join(__slicer_module__, 'Resources', 'ColorFile',
                      self.colorTable))
     self.colorTableNode.SetName(self.colorTable[:-4])
     storage = self.colorTableNode.CreateDefaultStorageNode()
     slicer.mrmlScene.AddNode(storage)
     self.colorTableNode.AddAndObserveStorageNodeID(storage.GetID())
     slicer.mrmlScene.AddNode(self.colorTableNode)
     storage.SetFileName(self.colorTableNode.GetFileName())
     storage.SetReadState(True)
     storage.ReadData(self.colorTableNode, True)
  def __init__(self, parent = None):
    QCLib.genericPanel.__init__(self,parent)

    self.coln=slicer.mrmlScene.GetNodesByClassByName('vtkMRMLColorNode','GMBColorTable').GetItemAsObject(0)

    if not self.coln:
      self.coln=slicer.vtkMRMLColorTableNode()
      self.coln.SetName("GMBColorTable")
      self.coln.SetTypeToUser()
      self.coln.HideFromEditorsOff()
      self.coln.SetNumberOfColors(2)
      self.coln.SetColor(0,'bg',0,0,0)
      self.coln.SetColor(1,'fg',1,0,0)
      self.coln.SetOpacity(0,0)
      self.coln.SetOpacity(1,1)
      slicer.mrmlScene.AddNode(self.coln)

    if not parent:
      self.setup()
      self.parent.show()
    def generateLUT(self):
        self.deleteNodeByName('ShapeDistanceAnalyzer Distance Color Table')
        colorlow = (0.1, 0.1, 1)
        colormid = (1, 1, 1)
        colorhigh = (1, 0.1, 0.1)

        #should be an odd number
        total_number_of_colors = 512

        colorTableNode = slicer.vtkMRMLColorTableNode()
        colorTableNode.SetName('ShapeDistanceAnalyzer Color Table')
        colorTableNode.SetTypeToUser()
        colorTableNode.HideFromEditorsOff()
        colorTableNode.SaveWithSceneOff()
        colorTableNode.SetNumberOfColors(total_number_of_colors)
        colorTableNode.GetLookupTable().SetTableRange(
            0, total_number_of_colors - 1)

        number_of_colors = total_number_of_colors / 2

        #from colorlow to colormid
        for i in range(number_of_colors):
            alpha = float(i) / (number_of_colors - 1)
            r = colorlow[0] * (1 - alpha) + colormid[0] * alpha
            g = colorlow[1] * (1 - alpha) + colormid[1] * alpha
            b = colorlow[2] * (1 - alpha) + colormid[2] * alpha

            colorTableNode.AddColor(str(i), r, g, b, 1)

        #from colormid to colorhigh
        for i in range(number_of_colors):
            alpha = float(i) / (number_of_colors - 1)
            r = colormid[0] * (1 - alpha) + colorhigh[0] * alpha
            g = colormid[1] * (1 - alpha) + colorhigh[1] * alpha
            b = colormid[2] * (1 - alpha) + colorhigh[2] * alpha

            colorTableNode.AddColor(str(number_of_colors + i), r, g, b, 1)

        colorTableNode.SetName('ShapeDistanceAnalyzer Distance Color Table')
        slicer.mrmlScene.AddNode(colorTableNode)
Example #9
0
    def createColorTable(self, outputVolumeNodeName):
        """ Creates a colour table with the names of the fiducials

        :param str outputVolumeNodeName:
        """
        # Need to use and reset WASP label if already their
        if slicer.util.getNode("WASP_labels"):
            color = slicer.util.getNode("WASP_labels")
            color.Reset()
        else:
            # Setup a new colour table
            color = slicer.vtkMRMLColorTableNode()
            color.SetNumberOfColors(3)
            color.SetName("WASP_labels")
            color.SetTypeToLabels()

        # Go through the self.final_dict instance attribute and set a new colour map using those names
        for name in self.final_dict:
            color.SetColorName(self.final_dict[name], name)

        # add to scene
        slicer.mrmlScene.AddNode(color)

        # print for check
        colorID = color.GetID()
        print outputVolumeNodeName
        print "colour", colorID

        # Setup the layers
        outputVolumeNode = slicer.util.getNode(str(outputVolumeNodeName))
        outputVolumeNode.SetDisplayVisibility(1)

        # Set to the output to show. Otherwise a volumeDisplayNode wont
        slicer.app.applicationLogic().GetSelectionNode().SetReferenceActiveVolumeID(outputVolumeNode.GetID())
        slicer.app.applicationLogic().PropagateVolumeSelection(0)

        display = outputVolumeNode.GetVolumeDisplayNode()
        display.SetAndObserveColorNodeID(str(colorID))
  def onSelectMaster(self):
    self.master = self.masterSelector.currentNode()
    merge=None

    self.overrideROI.enabled=False
    self.sliceslider.enabled=False
    self.autothr.enabled=False
    self.autothreshold()

    self.dgp.enabled=False
    self.chartButton.enabled=False
    self.sides=None
    self.diagonals=None
    for n in range(8):
      self.items[n+2].setText("")

    #-----mergeVolume()
    if self.master:
      self.overrideROI.enabled=True
      self.autothr.enabled=True
      self.autothreshold()

      masterName = self.master.GetName()
      mergeName = masterName+self.suffixMergeName

      # if we already have a merge and the master hasn't changed, use it
      if self.merge and self.master == self.masterWhenMergeWasSet:
        mergeNode = slicer.mrmlScene.GetNodeByID(self.merge.GetID())
        if mergeNode and mergeNode !="":
          merge=self.merge

      if not merge:
        self.masterWhenMergeWasSemasterWhenMergeWasSet = None

        # otherwise pick the merge based on the master name
        # - either return the merge volume or empty string
        merge = self.getNodeByName(mergeName)
        self.merge=merge
        #-----

      if merge:
        if merge.GetClassName() != "vtkMRMLLabelMapVolumeNode":
          self.errorDialog("Error: selected merge label volume is not a label volume " + merge.GetClassName())
        else:
          warnings = self.checkForVolumeWarnings(self.master,self.merge)
          if warnings != "":
            self.errorDialog( "Warning: %s" % warnings )
          else:
            # make the source node the active background, and the label node the active label
            applicationLogic = slicer.app.applicationLogic()
            selectionNode = applicationLogic.GetSelectionNode()
            selectionNode.SetReferenceActiveVolumeID(self.master.GetID())
            selectionNode.SetReferenceActiveLabelVolumeID(merge.GetID())
            applicationLogic.PropagateVolumeSelection(0)
            self.merge = merge

            sn=self.qu.getSliceNode()
            if sn:
              self.sliceslider.setMRMLSliceNode(sn)
              self.sliceslider.enabled=True
            else:
              self.sliceslider.enabled=False
      else:
        # the master exists, but there is no merge volume yet
        volumesLogic = slicer.modules.volumes.logic()
        merge = volumesLogic.CreateAndAddLabelVolume(slicer.mrmlScene, self.master, mergeName)
        coln=slicer.vtkMRMLColorTableNode()
        coln.SetTypeToRandom()
        slicer.mrmlScene.AddNode(coln)
        merge.GetDisplayNode().SetAndObserveColorNodeID(coln.GetID())
        #cl=slicer.vtkMRMLColorLogic()
        #cl.SetMRMLScene(slicer.mrmlScene)
        #merge.GetDisplayNode().SetAndObserveColorNodeID(cl.GetFileColorNodeID("GenericColors.txt"))
        self.merge = merge
        self.masterWhenMergeWasSet = self.master
        #self.labelSelector.setCurrentNode(self.merge)
        self.onSelectMaster()
Example #11
0
 def __init__(self):  
   # Member variables
   self.outputLabels = None    
   self.recordedDataBuffer = []   
   self.record = False
   self.reset = False
   self.outputObserverTag = -1
   self.rigidBodyToTrackerTransformNode = None
   self.measurementToMeasurerTransformNode = None
   self.parametersToMeasurerTransformNode = None
   self.plus = None
   self.m = vtk.vtkMatrix4x4()
   self.direction = -1
   self.ras = [0, 0, 0, 1]
   self.d = 0.0
   self.snr = 0
   self.total = 0
   self.LABEL_UPDATE_RATE = 10  
   self.labelUpdateCount = 0
   self.snrThreshold = 40       
   self.distanceMaximumValue = 1000.0       
   self.distanceMinimumValue = 0.0 
   self.lensMaxDistance = 0.0
   self.lensMinDistance = 0.0
   self.normalizingConstant = 0.0
   self.min = -1000.0
   self.addColours = True
   import Viewpoint # Viewpoint
   self.viewpointLogic = Viewpoint.ViewpointLogic()
   self.stopWatch = None # StopWatch        
   # Create style sheets        
   self.errorStyleSheet = "QLabel { color : #FF0000; \
                               font: bold 14px}"
   self.defaultStyleSheet = "QLabel { color : #000000; \
                                 font: bold 14px}"        
   # Create rainbow colour table                                      
   self.colorTable=slicer.vtkMRMLColorTableNode()
   self.colorTable.SetTypeToRainbow ()                                    
   # Add MeasurementPoint
   self.measurementPointMarkupsFiducialNode = slicer.util.getNode('MeasurementPoint')
   if not self.measurementPointMarkupsFiducialNode:
     self.measurementPointMarkupsFiducialNode = slicer.vtkMRMLMarkupsFiducialNode()  
     self.measurementPointMarkupsFiducialNode.SetName('MeasurementPoint')
     self.measurementPointMarkupsFiducialNode.AddFiducial(0, 0, 0)
     self.measurementPointMarkupsFiducialNode.SetNthFiducialLabel(0, '')
     slicer.mrmlScene.AddNode(self.measurementPointMarkupsFiducialNode)
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphScale(2.0)
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphType(13) # Sphere3D
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetSelectedColor(1, 0, 0)     
   # Add RecordedModel
   self.recordedModelNode = slicer.util.getNode('RecordedModel')
   if not self.recordedModelNode:
     recordedPoints = vtk.vtkPoints()
     recordedVertices = vtk.vtkCellArray()               
     recordedPolyData = vtk.vtkPolyData()
     recordedPolyData.SetPoints(recordedPoints)
     recordedPolyData.SetVerts(recordedVertices)
     self.recordedModelNode = self.addModelToScene(recordedPolyData, "RecordedModel")    
     self.recordedModelNode.GetModelDisplayNode().SetPointSize(3)
     # Set up coloured scalars  
     colorArray = vtk.vtkDoubleArray()
     colorArray.SetNumberOfComponents(4)
     colorArray.SetName('Colors')
     self.recordedModelNode.GetPolyData().GetPointData().SetScalars(colorArray)          
   # Create share directory
   self.pathToCreatedSaveDir = self.createShareDirectory()    
   # Post-Processing default (for undo)
   self.recordedDataBufferDefault = []
  def onSelectMaster(self):
    self.master = self.masterSelector.currentNode()
    merge=None

    #-----mergeVolume()
    if self.master:
      masterName = self.master.GetName()
      mergeName = masterName+self.suffixMergeName

      # if we already have a merge and the master hasn't changed, use it
      if self.merge and self.master == self.masterWhenMergeWasSet:
        mergeNode = slicer.mrmlScene.GetNodeByID(self.merge.GetID())
        if mergeNode and mergeNode !="":
          merge=self.merge

      if not merge:
        self.masterWhenMergeWasSemasterWhenMergeWasSet = None

        # otherwise pick the merge based on the master name
        # - either return the merge volume or empty string
        merge = self.getNodeByName(mergeName)
        self.merge=merge
        #-----

      if merge:
        if merge.GetClassName() != "vtkMRMLLabelMapVolumeNode":
          self.errorDialog("Error: selected merge label volume is not a label volume " + merge.GetClassName())
        else:
          warnings = self.checkForVolumeWarnings(self.master,self.merge)
          if warnings != "":
            self.errorDialog( "Warning: %s" % warnings )
          else:
            # make the source node the active background, and the label node the active label
            applicationLogic = slicer.app.applicationLogic()
            selectionNode = applicationLogic.GetSelectionNode()
            selectionNode.SetReferenceActiveVolumeID(self.master.GetID())
            selectionNode.SetReferenceActiveLabelVolumeID(merge.GetID())
            applicationLogic.PropagateVolumeSelection(0)
            self.merge = merge
      else:
        # the master exists, but there is no merge volume yet
        volumesLogic = slicer.modules.volumes.logic()
        merge = volumesLogic.CreateAndAddLabelVolume(slicer.mrmlScene, self.master, mergeName)
        coln=slicer.vtkMRMLColorTableNode()
        coln.SetTypeToUser()
        coln.SetNumberOfColors(9)
        coln.SetColor(0,'bg',0,0,0)
        coln.SetColor(1,'n',1,0,0)
        coln.SetColor(2,'ne',0,1,0)
        coln.SetColor(3,'nw',0,0,1)
        coln.SetColor(4,'e',1,1,0)
        coln.SetColor(5,'w',1,0,1)
        coln.SetColor(6,'s',0,1,1)
        coln.SetColor(7,'se',1,1,1)
        coln.SetColor(8,'sw',1,0.5,0)
        coln.SetOpacity(0,0)
        for n in range(1,9):
          coln.SetOpacity(n,1)
        slicer.mrmlScene.AddNode(coln)
        merge.GetDisplayNode().SetAndObserveColorNodeID(coln.GetID())
        self.merge = merge
        self.masterWhenMergeWasSet = self.master
        self.onSelectMaster()