Esempio n. 1
0
def mhd_getRatios(fname):
  """
  Get relative axis ratios from MHD file defined by fname
  """
  if not os.path.exists(fname):
    print "imageStackLoader.mhd_getRatios can not find %s" % fname
    return
    
  try:
    #Attempt to use the vtk module to read the element spacing
    imp.find_module('vtk')
    import vtk
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(fname)
    imr.Update()
 
    im = imr.GetOutput()
    spacing = im.GetSpacing()    
  except ImportError:
    #If the vtk module fails, we try to read the spacing using the built-in reader
    info = mhd_read_header_file(fname)
    if info.has_key('elementspacing'):
      spacing = info['elementspacing']
    else:
      print "Failed to find spacing info in MHA file. Using default axis length values"      
      return lasHelp.readPreference('defaultAxisRatios') #defaults


  if len(spacing)==0: 
    print "Failed to find spacing valid spacing info in MHA file. Using default axis length values"      
    return lasHelp.readPreference('defaultAxisRatios') #defaults
  
  return spacingToRatio(spacing)  
Esempio n. 2
0
    def __init__(self, parent=None, data=None, fnameAbsPath="", enable=True, objectName=""):
        super(lines, self).__init__(parent, data, fnameAbsPath, enable, objectName, pgObject="PlotCurveItem")

        # Choose symbols from preferences file.
        # TODO: read symbols from GUI
        self.symbol = lasHelp.readPreference("symbolOrder")[0]
        self.symbolSize = int(self.parent.markerSize_spinBox.value())
        self.alpha = int(self.parent.markerAlpha_spinBox.value())
        self.lineWidth = int(self.parent.lineWidth_spinBox.value())

        # Add to the imageStackLayers_model which is associated with the points QTreeView
        name = QtGui.QStandardItem(objectName)
        name.setEditable(False)

        # Add checkbox
        thing = QtGui.QStandardItem()
        thing.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable)
        thing.setCheckState(QtCore.Qt.Checked)

        # self.modelItems=(name,thing) #Remove this for now because I have NO CLUE how to get access to the checkbox state
        self.modelItems = name
        self.model = self.parent.points_Model

        self.addToList()

        # Set the colour of the object based on how many items are already present
        number_of_colors = 6
        thisNumber = (self.parent.points_Model.rowCount() - 1) % number_of_colors
        cm_subsection = linspace(0, 1, number_of_colors)
        colors = [cm.jet(x) for x in cm_subsection]
        color = colors[thisNumber]
        self.color = [color[0] * 255, color[1] * 255, color[2] * 255]
Esempio n. 3
0
    def showLoadDialog(self):
        """
        This slot brings up the load dialog and retrieves the file name.
        If the file name is valid, it loads the base stack using the load method.
        """
        
        fname = self.lasagna.showFileLoadDialog(fileFilter="LSM (*.lsm)")
        if fname is None:
            return

        colorOrder = lasHelp.readPreference('colorOrder')
        if os.path.isfile(fname): 
            im=tifffile.imread(str(fname)) 
            print("Found LSM stack with dimensions:")
            print(im.shape)
            for ii in range(im.shape[2]):
                stack=im[0,:,ii,:,:]

                objName="layer_%d" % (ii+1)
                self.lasagna.addIngredient(objectName=objName, 
                           kind='imagestack', 
                           data=stack, 
                           fname=fname
                           )
                self.lasagna.returnIngredientByName(objName).addToPlots() #Add item to all three 2D plots                

                print("Adding '%s' layer" % colorOrder[ii])
                self.lasagna.returnIngredientByName(objName).lut=colorOrder[ii]


            self.lasagna.initialiseAxes()

        else:
            self.lasagna.statusBar.showMessage("Unable to find " + str(fname))
Esempio n. 4
0
    def __init__(self, parent=None, data=None, fnameAbsPath='', enable=True, objectName=''):
        super(sparsepoints,self).__init__(parent, data, fnameAbsPath, enable, objectName,
                                        pgObject='ScatterPlotItem'
                                        )


        #Choose symbols from preferences file. TODO: in future could increment through so successive ingredients have different symbols and colors
        self.symbol = lasHelp.readPreference('symbolOrder')[0]
        self.symbolSize =  int(self.parent.markerSize_spinBox.value())
        self.alpha = int(self.parent.markerAlpha_spinBox.value())
        self.lineWidth = None #Not used right now

        #Add to the imageStackLayers_model which is associated with the points QTreeView
        name = QtGui.QStandardItem(objectName)
        name.setEditable(False)

        #Add checkbox
        thing = QtGui.QStandardItem()
        thing.setFlags(QtCore.Qt.ItemIsEnabled  | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable)
        thing.setCheckState(QtCore.Qt.Checked)

        #self.modelItems=(name,thing) #Remove this for now because I have NO CLUE how to get the checkbox state bacl
        self.modelItems=name
        self.model = self.parent.points_Model

        self.addToList()

        #Set the colour of the object based on how many items are already present
        number_of_colors = 6
        thisNumber = (self.parent.points_Model.rowCount()-1)%number_of_colors
        cm_subsection = linspace(0, 1, number_of_colors)
        colors = [ cm.jet(x) for x in cm_subsection ]
        color = colors[thisNumber]
        self.color = [color[0]*255, color[1]*255, color[2]*255]
Esempio n. 5
0
    def showLoadDialog(self):
        """
        This slot brings up the load dialog and retrieves the file name.
        If the file name is valid, it loads the base stack using the load method.
        """
        
        fname = self.lasagna.showFileLoadDialog(fileFilter="LSM (*.lsm)")
        if fname is None:
            return

        colorOrder = lasHelp.readPreference('colorOrder')
        if os.path.isfile(fname): 
            im=tifffile.imread(str(fname)) 
            print "Found LSM stack with dimensions:"
            print im.shape
            for ii in range(im.shape[2]):
                stack=im[0,:,ii,:,:]

                objName="layer_%d" % (ii+1)
                self.lasagna.addIngredient(objectName=objName, 
                           kind='imagestack', 
                           data=stack, 
                           fname=fname
                           )
                self.lasagna.returnIngredientByName(objName).addToPlots() #Add item to all three 2D plots                

                print "Adding '%s' layer" % colorOrder[ii]
                self.lasagna.returnIngredientByName(objName).lut=colorOrder[ii]


            self.lasagna.initialiseAxes()

        else:
            self.lasagna.statusBar.showMessage("Unable to find " + str(fname))
Esempio n. 6
0
    def __init__(self,
                 thisPlotWidget,
                 lasagna,
                 axisName='',
                 minMax=(0, 1500),
                 axisRatio=1,
                 axisToPlot=0):
        """
        thisPlotWidget - the PlotWidget to which we will add the axes
        minMax - the minimum and maximum values of the plotted image. 
        axisRatio - the voxel size ratio along the x and y axes. 1 means square voxels.
        axisToPlot - the dimension along which we are slicing the data.
        """

        #Create properties
        self.axisToPlot = axisToPlot  #the axis in 3D space that this view correponds to
        self.axisName = axisName
        #We can link this projection to two others
        self.linkedXprojection = None
        self.linkedYprojection = None

        print("Creating axis at " + str(thisPlotWidget.objectName()))
        self.view = thisPlotWidget  #This should target the axes to a particular plot widget

        if lasHelp.readPreference('hideZoomResetButtonOnImageAxes') == True:
            self.view.hideButtons()

        if lasHelp.readPreference('hideAxes') == True:
            self.view.hideAxis('left')
            self.view.hideAxis('bottom')

        self.view.setAspectLocked(True, axisRatio)

        #Loop through the ingredients list and add them to the ViewBox
        self.lasagna = lasagna
        self.items = [
        ]  #a list of added plot items TODO: check if we really need this
        self.addItemsToPlotWidget(self.lasagna.ingredientList)

        #The currently plotted slice
        self.currentSlice = None

        #Link the progressLayer signal to a slot that will move through image layers as the wheel is turned
        self.view.getViewBox().progressLayer.connect(self.wheel_layer_slot)
Esempio n. 7
0
def getVoxelSpacing(fname,fallBackMode=False):
  """
  Attempts to get the voxel spacing in all three dimensions. This allows us to set the axis
  ratios automatically. TODO: Currently this will only work for MHD files, but we may be able 
  to swing something for TIFFs (e.g. by creating Icy-like metadata files)
  """

  if fname.lower().endswith('.mhd'):
    return mhd_getRatios(fname)
  if fname.lower().endswith('.nrrd') or fname.lower().endswith('.nrd'):  
    return nrrd_getRatios(fname)
  else:
    return lasHelp.readPreference('defaultAxisRatios') #defaults
Esempio n. 8
0
    def __init__(self, thisPlotWidget, lasagna, axisName='', minMax=(0,1500), axisRatio=1, axisToPlot=0):
        """
        thisPlotWidget - the PlotWidget to which we will add the axes
        minMax - the minimum and maximum values of the plotted image. 
        axisRatio - the voxel size ratio along the x and y axes. 1 means square voxels.
        axisToPlot - the dimension along which we are slicing the data.
        """

        #Create properties
        self.axisToPlot = axisToPlot #the axis in 3D space that this view correponds to
        self.axisName = axisName
        #We can link this projection to two others
        self.linkedXprojection=None
        self.linkedYprojection=None


        print "Creating axis at " + str(thisPlotWidget.objectName())
        self.view = thisPlotWidget #This should target the axes to a particular plot widget

        if lasHelp.readPreference('hideZoomResetButtonOnImageAxes')==True:
            self.view.hideButtons()

        if lasHelp.readPreference('hideAxes')==True:
            self.view.hideAxis('left')
            self.view.hideAxis('bottom')               

        self.view.setAspectLocked(True,axisRatio)

        #Loop through the ingredients list and add them to the ViewBox
        self.lasagna = lasagna
        self.items=[] #a list of added plot items TODO: check if we really need this
        self.addItemsToPlotWidget(self.lasagna.ingredientList)

        #The currently plotted slice
        self.currentSlice=None

        #Link the progressLayer signal to a slot that will move through image layers as the wheel is turned
        self.view.getViewBox().progressLayer.connect(self.wheel_layer_slot)
    def loadOther_pushButton_slot(self,fnameToLoad=False):
        """
        Load a user-selected atlas file but use the labels from the ARA in the drop-down box.
        Can optionally load a specific file name (used for de-bugging)
        """
        if fnameToLoad==False:       
            fileFilter="Images (*.mhd *.mha *.tiff *.tif *.nrrd)"
            fnameToLoad = QtGui.QFileDialog.getOpenFileName(self, 'Open file', lasHelp.readPreference('lastLoadDir'), fileFilter)
            fnameToLoad = str(fnameToLoad)

        #re-load labels        
        selectedName = str(self.araName_comboBox.itemText(self.araName_comboBox.currentIndex()))
        paths = self.paths[selectedName]
        self.data['labels'] = self.loadLabels(paths['labels'])

        #load the selected atlas (without displaying it)
        self.data['atlas'] = imageStackLoader.loadStack(fnameToLoad)

        self.data['currentlyLoadedAtlasName'] =  fnameToLoad.split(os.path.sep)[-1]
Esempio n. 10
0
    def chooseStack_slot(self, fnameToChoose=False):
        """
        Choose the stack to transform
        can optionally load a specific file name (used for de-bugging)
        """
        if fnameToChoose==False:         
            fileFilter="Images (*.mhd *.mha)"
            fnameToChoose = QtGui.QFileDialog.getOpenFileName(self, 'Choose stack', lasHelp.readPreference('lastLoadDir'), fileFilter)
            fnameToChoose = str(fnameToChoose)


        if os.path.exists(fnameToChoose):
            self.inputImagePath = fnameToChoose
        else:
            self.inputImagePath = ''
            #TODO: make an alert box for this case
            print "that file does not exits"
        
        self.checkIfReadyToRun()
        lasHelp.preferenceWriter('lastLoadDir', lasHelp.stripTrailingFileFromPath(fnameToChoose))
        self.stackName_label.setText(fnameToChoose.split(os.path.sep)[-1])
Esempio n. 11
0
    def chooseTransform_slot(self, fnameToChoose=False):
        """
        Choose the transform file to use
        can optionally load a specific file name (used for de-bugging)
        """
        if fnameToChoose == False:
            fileFilter = "Images (*.txt)"
            fnameToChoose = QtGui.QFileDialog.getOpenFileName(
                self, 'Choose transform',
                lasHelp.readPreference('lastLoadDir'), fileFilter)
            fnameToChoose = str(fnameToChoose)

        if os.path.exists(fnameToChoose):
            self.transformPath = fnameToChoose
        else:
            self.transformPath = ''
            #TODO: make an alert box for this case
            print("that file does not exits")

        self.checkIfReadyToRun()
        lasHelp.preferenceWriter(
            'lastLoadDir', lasHelp.stripTrailingFileFromPath(fnameToChoose))
        self.transformName_label.setText(fnameToChoose.split(os.path.sep)[-1])
Esempio n. 12
0
    def loadOther_pushButton_slot(self, fnameToLoad=False):
        """
        Load a user-selected atlas file but use the labels from the ARA in the drop-down box.
        Can optionally load a specific file name (used for de-bugging)
        """
        if fnameToLoad == False:
            fileFilter = "Images (*.mhd *.mha *.tiff *.tif *.nrrd)"
            fnameToLoad = QtGui.QFileDialog.getOpenFileName(
                self, 'Open file', lasHelp.readPreference('lastLoadDir'),
                fileFilter)
            fnameToLoad = str(fnameToLoad)

        #re-load labels
        selectedName = str(
            self.araName_comboBox.itemText(
                self.araName_comboBox.currentIndex()))
        paths = self.paths[selectedName]
        self.data['labels'] = self.loadLabels(paths['labels'])

        #load the selected atlas (without displaying it)
        self.data['atlas'] = imageStackLoader.loadStack(fnameToLoad)

        self.data['currentlyLoadedAtlasName'] = fnameToLoad.split(
            os.path.sep)[-1]