예제 #1
0
    def PopulateTableStats(self):
        """ Creates the Qt table with the statistics"""

        NewOrderKeys = [
            'Segment', 'Scalar Volume', 'Mean', 'Standard Deviation',
            'Minimum', 'Maximum', 'Median', 'Number of voxels [voxels]',
            'Surface area [mm2]', 'Volume [mm3]', 'Volume [mm3]'
        ]
        self.items = []
        self.model = qt.QStandardItemModel()
        self.table.setModel(self.model)
        self.table.verticalHeader().visible = False
        segmentationNode = self.segmentationSelector.currentNode()
        row = 0
        NofSegments = len(self.statistics['SegmentIDs'])
        I = np.concatenate((np.arange(NofSegments), np.arange(NofSegments)))

        for i in range(len(list(self.stats.values())[0])):
            col = 0
            color = qt.QColor()
            segment = segmentationNode.GetSegmentation().GetSegment(
                self.statistics['SegmentIDs'][I[i]])
            rgb = segment.GetColor()
            color.setRgb(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255)
            item = qt.QStandardItem()
            item.setData(color, qt.Qt.DecorationRole)
            item.setEditable(False)
            self.model.setItem(row, col, item)
            self.items.append(item)
            col += 1
            for k in NewOrderKeys:
                item = qt.QStandardItem()
                item.setData(self.stats[k][i], qt.Qt.DisplayRole)
                item.setEditable(False)
                self.model.setItem(row, col, item)
                self.items.append(item)
                col += 1
            row += 1

        col = 0
        self.table.setColumnWidth(0, 30)
        self.model.setHeaderData(0, 1, " ")
        col += 1

        for k in NewOrderKeys:
            self.table.setColumnWidth(col, 16 * len(k))
            self.model.setHeaderData(col, 1, k)
            col += 1
예제 #2
0
    def addLabel(self, row, rgb, values):
        #print "add row", row, rgb
        self.selectLabels.setRowCount(row+1)

        item0 = qt.QTableWidgetItem('')
        item0.setFlags(qt.Qt.ItemIsUserCheckable | qt.Qt.ItemIsEnabled)
        item0.setCheckState(qt.Qt.Unchecked)
        self.selectLabels.setItem(row,0,item0)

        for ii,val in enumerate(values):
          item1 = qt.QTableWidgetItem('')
          color=qt.QColor()
          color.setRgbF(rgb[0],rgb[1],rgb[2])
          item1.setData(qt.Qt.BackgroundRole,color)
          item1.setText("%.02f"%val)
          self.selectLabels.setItem(row,1+ii,item1)
예제 #3
0
 def getBackgroundOrToolTipData(self, index, role):
     if role not in [qt.Qt.BackgroundRole, qt.Qt.ToolTipRole]:
         return None
     if self.currentGuidanceComputation is None:
         return None
     backgroundRequested = role == qt.Qt.BackgroundRole
     row = index.row()
     col = index.column()
     outOfRangeText = "" if self.currentGuidanceComputation.getZFrameDepthInRange(
         row) else "Current depth: out of range"
     if self.coverProstateTargetList and not self.coverProstateTargetList is self.targetList:
         if col in [3, 4]:
             coverProstateGuidance = self.getOrCreateNewGuidanceComputation(
                 self.coverProstateTargetList)
             if col == 3:
                 coverProstateHole = coverProstateGuidance.getZFrameHole(
                     row)
                 if self.currentGuidanceComputation.getZFrameHole(
                         row) == coverProstateHole:
                     return qt.QColor(
                         qt.Qt.green) if backgroundRequested else ""
                 else:
                     return qt.QColor(
                         qt.Qt.red
                     ) if backgroundRequested else "{} hole: {}".format(
                         self.PLANNING_IMAGE_NAME, coverProstateHole)
             elif col == 4:
                 currentDepth = self.currentGuidanceComputation.getZFrameDepth(
                     row, asString=False)
                 coverProstateDepth = coverProstateGuidance.getZFrameDepth(
                     row, asString=False)
                 if abs(currentDepth - coverProstateDepth) <= max(
                         1e-9 *
                         max(abs(currentDepth), abs(coverProstateDepth)),
                         0.5):
                     if backgroundRequested:
                         return qt.QColor(qt.Qt.red) if len(
                             outOfRangeText) else qt.QColor(qt.Qt.green)
                     return "%s depth: '%.1f' %s" % (
                         self.PLANNING_IMAGE_NAME, coverProstateDepth,
                         "\n" + outOfRangeText)
                 else:
                     if backgroundRequested:
                         return qt.QColor(qt.Qt.red)
                     return "%s depth: '%.1f' %s" % (
                         self.PLANNING_IMAGE_NAME, coverProstateDepth,
                         "\n" + outOfRangeText)
     elif self.coverProstateTargetList is self.targetList and col == 4:
         if backgroundRequested and len(outOfRangeText):
             return qt.QColor(qt.Qt.red)
         elif len(outOfRangeText):
             return outOfRangeText
     return None
예제 #4
0
    def __init__(self,
                 parent=None,
                 width=400,
                 height=400,
                 showWidget=False,
                 scale=False):
        super(LayerReveal, self).__init__()
        self.width = width
        self.height = height
        self.showWidget = showWidget
        self.scale = scale
        self.renderer = None

        # utility Qt instances for use in methods
        self.gray = qt.QColor()
        self.gray.setRedF(0.5)
        self.gray.setGreenF(0.5)
        self.gray.setBlueF(0.5)
        # a painter to use for various jobs
        self.painter = qt.QPainter()

        # make a qwidget display
        if self.showWidget:
            self.frame = qt.QFrame(parent)
            mw = slicer.util.mainWindow()
            self.frame.setGeometry(mw.x, mw.y, self.width, self.height)
            self.frameLayout = qt.QVBoxLayout(self.frame)
            self.label = qt.QLabel()
            self.frameLayout.addWidget(self.label)
            self.frame.show()

        # make an image actor in the slice view
        self.vtkImage = vtk.vtkImageData()

        self.mrmlUtils = slicer.qMRMLUtils()
        self.imageMapper = vtk.vtkImageMapper()
        self.imageMapper.SetColorLevel(128)
        self.imageMapper.SetColorWindow(255)
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.imageMapper.SetInput(self.vtkImage)
        else:
            self.imageMapper.SetInputData(self.vtkImage)
        self.actor2D = vtk.vtkActor2D()
        self.actor2D.SetMapper(self.imageMapper)
예제 #5
0
    def selectColor(self):
        """ selectColor() -> show the color dialog and emit a color selection

        """
        args = ()
        acolor = qt.QColor(self.color)
        if kdecore.KApplication.kApplication():
            result = kdeui.KColorDialog.getColor(acolor, self)
            if result == kdeui.KColorDialog.Accepted:
                self.color = acolor
                args = (self.key, self.color, )
        else:
            result = qt.QColorDialog.getColor(acolor, self)
            if result and result.isValid():
                self.color = result
                args = (self.key, self.color, )
        if args:
            self.setColorPixmap()
            self.emit(plotControlColorSelected, args)
예제 #6
0
    def populateStats(self):
        if not self.logic:
            return
        displayNode = self.labelNode.GetDisplayNode()
        colorNode = displayNode.GetColorNode()
        lut = colorNode.GetLookupTable()
        self.items = []
        self.model = qt.QStandardItemModel()
        self.view.setModel(self.model)
        self.view.verticalHeader().visible = False
        row = 0

        for regionTag, regionValue in zip(self.logic.regionTags,
                                          self.logic.regionValues):
            color = qt.QColor()
            rgb = lut.GetTableValue(regionValue[0])
            color.setRgb(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255)
            item = qt.QStandardItem()
            item.setData(color, 1)
            item.setText(str(regionTag))
            item.setData(regionTag, 1)
            item.setToolTip(regionTag)
            item.setTextAlignment(1)
            self.model.setItem(row, 0, item)
            self.items.append(item)
            col = 1
            for k in self.logic.keys:
                item = qt.QStandardItem()
                item.setText("%.3f" % self.logic.labelStats[k, regionTag])
                item.setTextAlignment(4)
                self.view.setColumnWidth(col, 15 * len(item.text()))
                self.model.setItem(row, col, item)
                self.items.append(item)
                col += 1
            row += 1

        self.view.setColumnWidth(0, 15 * len('Region'))
        self.model.setHeaderData(0, 1, "Region")
        col = 1
        for k in self.logic.keys:
            # self.view.setColumnWidth(col,15*len(k))
            self.model.setHeaderData(col, 1, k)
            col += 1
예제 #7
0
    def __init__(self):
        super(StatusDisplayWidget, self).__init__(None)

        self.setMinimumHeight(200)
        self.setStyleSheet("background-color:black;")

        self.margin_x = 10
        self.margin_y = 10
        self.inner_margin_x = 5
        self.inner_margin_y = 5
        self.font_h = 12
        self.font_w = 8
        self.led_r_h = 10
        self.led_r_w = 10
        self.led_intv_x = 32
        self.name_w = 160

        self.color_fg_base = qt.QColor(140, 140, 140)
        self.color_fg_high = qt.QColor(240, 240, 240)
        self.color_fg_low = qt.QColor(100, 100, 100)
        self.color_fg_act = qt.QColor(50, 255, 50)
        self.color_fg_war = qt.QColor(255, 255, 50)
        self.color_fg_err = qt.QColor(255, 50, 50)

        self.pen_fg_base_frame = qt.QPen(self.color_fg_base, 2)
        self.pen_fg_base = qt.QPen(self.color_fg_base, 2)
        self.pen_fg_high = qt.QPen(self.color_fg_high, 2)
        self.pen_fg_act = qt.QPen(self.color_fg_act, 2)
        self.pen_fg_on = qt.QPen(self.color_fg_high, 2)
        self.pen_fg_off = qt.QPen(self.color_fg_low, 2)

        self.pen_led_on = qt.QPen(self.color_fg_high, 2)
        self.pen_led_off = qt.QPen(self.color_fg_low, 1)
        self.pen_led_rcv = qt.QPen(self.color_fg_act, 2)
        self.pen_led_war = qt.QPen(self.color_fg_war, 2)
        self.pen_led_err = qt.QPen(self.color_fg_err, 2)

        self.connector_box_h = self.font_h + self.inner_margin_y * 2
        self.connector0_text_x = self.margin_x + self.inner_margin_x * 2 + self.name_w
        self.connector1_text_x = self.inner_margin_x * 3 + self.name_w
        self.connector_text_y = self.margin_y + self.inner_margin_y + self.font_h
        self.catheter_base_x = self.margin_x + self.inner_margin_x + self.name_w + self.inner_margin_x
        self.catheter_base_y = self.margin_y + self.font_h + self.inner_margin_y * 4
        self.catheter_row_h = self.led_r_h * 2 + self.inner_margin_y

        self.repaintTimer = qt.QTimer()

        # MRTrackingIGTLConnector
        self.connectors = []
        self.catheters = None
예제 #8
0
    def drawShape(self, painter):
        self.__painter = painter
        rect = self.rect()

        self.__num_cells = 0
        num_rows = (rect.bottom() - rect.top()) / self.__cell_height
        num_colls = (rect.right() - rect.left()) / self.__cell_width

        for i in range(0, num_rows + 1):
            offset = i * self.__cell_height
            self.__height = offset
            painter.drawLine(rect.left(),
                             rect.top() + offset, rect.right(),
                             rect.top() + offset)

        for i in range(0, num_colls + 1):
            offset = i * self.__cell_width
            self.__width = offset
            painter.drawLine(rect.left() + offset, rect.top(),
                             rect.left() + offset, rect.bottom())

        for i in range(0, num_rows):
            row_offset = i * self.__cell_height
            for k in range(0, num_colls):
                coll_offset = k * self.__cell_width
                self.__num_cells += 1
                if not self.__has_data:
                    self.__grid_data[self.__num_cells] = (self.__num_cells,
                                                          (0, 0, 255))

                color = self.__grid_data[self.__num_cells][1]

                painter.setBrush(
                    qt.QBrush(qt.QColor(*color), qt.Qt.Dense4Pattern))
                painter.drawEllipse(rect.left() + coll_offset,
                                    rect.top() + row_offset, self.__beam_width,
                                    self.__beam_height)

                tr = qt.QRect(rect.left() + coll_offset,
                              rect.top() + row_offset, self.__cell_width,
                              self.__cell_height)
                painter.drawText(tr, qt.Qt.AlignCenter, str(self.__num_cells))
예제 #9
0
    def __init__(self, canvas, parent =None, name ="PrintCanvas", fl =0):
        """
        """
        qtcanvas.QCanvasView.__init__(self, canvas, parent, name, fl)

        self.setAcceptDrops(1)

        self.canvas().setBackgroundColor(qt.QColor(qt.Qt.lightGray))
        self.marginSize = (0, 0)
        self.marginItem = qtcanvas.QCanvasRectangle(0, 0, 0, 0, self.canvas())
        self.marginItem.setBrush(qt.QBrush(qt.Qt.white, qt.Qt.SolidPattern))
        self.marginItem.show()

        self.viewScale = 1

        self.activePen = qt.QPen(qt.Qt.red, 1)

        self.__active_item = None
        self.__moving_start = None
        self.__moving_scale = 0
예제 #10
0
  def show_deer_db_table(self):
    if self._parameterNode is None or self._updatingGUIFromParameterNode:
      return

    wasModified = self._parameterNode.StartModify()

    sids = []   

    if self.ui.cbShowControl.checked:
      sids.extend([sid for sid in self.logic.deers.keys() if self.logic.deers[sid].group == "c"])
    if self.ui.cbShowNonControl.checked:
      sids.extend([sid for sid in self.logic.deers.keys() if self.logic.deers[sid].group == "p"])
    sids = sorted(sids)

    tbl = self.ui.tblDeers
    tbl.clear()
    tbl.clearContents()

    db_info_filter = ["sid","spieces","group","count","abnorm","done"]
    
    tbl.setColumnCount(len(db_info_filter))
    tbl.setRowCount(len(sids))
    
    for i in range(len(sids)):
      deer = self.logic.deers[sids[i]]
      deer.update_done(self.logic.dbTable)
      for j in range(len(db_info_filter)):
        tbl.setItem(i,j,qt.QTableWidgetItem(deer.db_info.get(db_info_filter[j])))
        if j!=(len(db_info_filter)-1):
          #tbl.item(i,j).setFlags(qt.Qt.ItemIsEnabled)
          pass

      if deer.db_info.get("done") == str(1):
        for j in range(self.ui.tblDeers.columnCount):
          tbl.item(i,j).setBackground(qt.QColor(0,127,0))


    tbl.setHorizontalHeaderLabels(db_info_filter)
    tbl.resizeColumnsToContents()
    self._parameterNode.EndModify(wasModified) 
예제 #11
0
    def selectWidget(self, w):
        if callable(self.__putBackColors):
            self.__putBackColors()

        orig_bkgd_color = w.paletteBackgroundColor()
        r = orig_bkgd_color.red()
        g = orig_bkgd_color.green()
        b = orig_bkgd_color.blue()
        bkgd_color = w.palette().active().highlight()
        bkgd_color2 = qt.QColor()
        #bkgd_color2.setRgb(255,0,0)
        bkgd_color2.setRgb(
            qt.qRgba(bkgd_color.red(), bkgd_color.green(), bkgd_color.blue(),
                     127))
        w.setPaletteBackgroundColor(bkgd_color2)

        def putBackColors(wref=weakref.ref(w), bkgd_color=(r, g, b)):
            #print 'should put back colors', wref
            w = wref()
            if w is not None:
                w.setPaletteBackgroundColor(qt.QColor(*bkgd_color))

        self.__putBackColors = putBackColors
예제 #12
0
 def valueChanged(self, value):
     # Here a workaround in case of SPEC associative array use
     # in that case, a dictionnary is returned with a unique key
     #L.claustre 01-08-2007
     val = value
     # mo longer needed, Matias has change the framework to
     # to manage associative array, from the xml file use the
     # syntax MYARRAY/avalue to access the SPEC variable MYARRAY["avalue"].
     #if type(value) is  types.DictionaryType:
     #    val = value[value.keys()[0]]
     #    if type(val) is  types.DictionaryType:
     #        val = val[val.keys()[0]]
     if self.varType in ["motor", "float"]:
         strval = "%.4f"%float(val)
     if self.varType == "integer":
         strval = "%d"%int(val)
     if self.varType == "string":
         strval = val
     if self.varType == "onoff":
         if val == '1':
             strval = "Off"
         else:
             strval = "On"
     if self.varType == "offon":
         if val == '1':
             strval = "On"
         else:
             strval = "Off"
     
     if self.displayWidget is not None:
         self.displayWidget.setValue(strval)
         
     if self.varType in ["onoff", "offon"]:
         qcolor = qt.QColor(SpecValueBrick.colorState[strval])
         if self.displayWidget is not None:
             self.displayWidget.setValueBackgroundColor(qcolor)
예제 #13
0
    def setup(self):
        ScriptedLoadableModuleWidget.setup(self)

        try:
            import vtkvmtkSegmentationPython as vtkvmtkSegmentation
        except ImportError:
            self.layout.addWidget(qt.QLabel("Failed to load VMTK libraries"))
            return

        #
        # the I/O panel
        #

        ioCollapsibleButton = ctk.ctkCollapsibleButton()
        ioCollapsibleButton.text = "Input/Output"
        self.layout.addWidget(ioCollapsibleButton)
        ioFormLayout = qt.QFormLayout(ioCollapsibleButton)

        # inputVolume selector
        self.inputVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.inputVolumeNodeSelector.objectName = 'inputVolumeNodeSelector'
        self.inputVolumeNodeSelector.toolTip = "Select the input volume."
        self.inputVolumeNodeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.inputVolumeNodeSelector.noneEnabled = False
        self.inputVolumeNodeSelector.addEnabled = False
        self.inputVolumeNodeSelector.removeEnabled = False
        ioFormLayout.addRow("Input Volume:", self.inputVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.inputVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        # seed selector
        self.seedFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
        self.seedFiducialsNodeSelector.objectName = 'seedFiducialsNodeSelector'
        self.seedFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
        self.seedFiducialsNodeSelector.objectName = 'seedFiducialsNodeSelector'
        self.seedFiducialsNodeSelector.toolTip = "Select a point in the largest vessel. Preview will be shown around this point. This is point is also used for determining maximum vessel diameter if automatic filtering parameters computation is enabled."
        self.seedFiducialsNodeSelector.setNodeBaseName("DiameterSeed")
        self.seedFiducialsNodeSelector.tableWidget().hide()
        self.seedFiducialsNodeSelector.defaultNodeColor = qt.QColor(255, 0,
                                                                    0)  # red
        self.seedFiducialsNodeSelector.markupsSelectorComboBox(
        ).noneEnabled = False
        self.seedFiducialsNodeSelector.markupsPlaceWidget(
        ).placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceSingleMarkup
        ioFormLayout.addRow("Seed point:", self.seedFiducialsNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.seedFiducialsNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        # outputVolume selector
        self.outputVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.outputVolumeNodeSelector.toolTip = "Select the output labelmap."
        self.outputVolumeNodeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.outputVolumeNodeSelector.baseName = "VesselnessFiltered"
        self.outputVolumeNodeSelector.noneEnabled = True
        self.outputVolumeNodeSelector.noneDisplay = "Create new volume"
        self.outputVolumeNodeSelector.addEnabled = True
        self.outputVolumeNodeSelector.selectNodeUponCreation = True
        self.outputVolumeNodeSelector.removeEnabled = True
        ioFormLayout.addRow("Output Volume:", self.outputVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.outputVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        #
        # Advanced area
        #

        self.advancedCollapsibleButton = ctk.ctkCollapsibleButton()
        self.advancedCollapsibleButton.text = "Advanced"
        self.advancedCollapsibleButton.collapsed = True
        self.layout.addWidget(self.advancedCollapsibleButton)
        advancedFormLayout = qt.QFormLayout(self.advancedCollapsibleButton)

        # previewVolume selector
        self.previewVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.previewVolumeNodeSelector.toolTip = "Select the preview volume."
        self.previewVolumeNodeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.previewVolumeNodeSelector.baseName = "VesselnessPreview"
        self.previewVolumeNodeSelector.noneEnabled = True
        self.previewVolumeNodeSelector.noneDisplay = "Create new volume"
        self.previewVolumeNodeSelector.addEnabled = True
        self.previewVolumeNodeSelector.selectNodeUponCreation = True
        self.previewVolumeNodeSelector.removeEnabled = True
        advancedFormLayout.addRow("Preview volume:",
                                  self.previewVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.previewVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        self.displayThresholdSlider = ctk.ctkSliderWidget()
        self.displayThresholdSlider.decimals = 2
        self.displayThresholdSlider.minimum = 0
        self.displayThresholdSlider.maximum = 1.0
        self.displayThresholdSlider.singleStep = 0.01
        self.displayThresholdSlider.toolTip = "Voxels below this vesselness value will be hidden. It does not change the voxel values, only how the vesselness volume is displayed."
        advancedFormLayout.addRow("Display threshold:",
                                  self.displayThresholdSlider)
        self.displayThresholdSlider.connect('valueChanged(double)',
                                            self.onDisplayThresholdChanged)

        self.previewVolumeDiameterVoxelSlider = ctk.ctkSliderWidget()
        self.previewVolumeDiameterVoxelSlider.decimals = 0
        self.previewVolumeDiameterVoxelSlider.minimum = 10
        self.previewVolumeDiameterVoxelSlider.maximum = 200
        self.previewVolumeDiameterVoxelSlider.singleStep = 5
        self.previewVolumeDiameterVoxelSlider.suffix = " voxels"
        self.previewVolumeDiameterVoxelSlider.toolTip = "Diameter of the preview area in voxels."
        advancedFormLayout.addRow("Preview volume size:",
                                  self.previewVolumeDiameterVoxelSlider)

        # detect filterint parameters
        self.detectPushButton = qt.QPushButton()
        self.detectPushButton.text = "Compute vessel diameters and contrast from seed point"
        self.detectPushButton.checkable = True
        self.detectPushButton.checked = True
        advancedFormLayout.addRow(self.detectPushButton)
        self.detectPushButton.connect("clicked()", self.onNodeSelectionChanged)

        self.minimumDiameterSpinBox = qt.QSpinBox()
        self.minimumDiameterSpinBox.minimum = 1
        self.minimumDiameterSpinBox.maximum = 1000
        self.minimumDiameterSpinBox.singleStep = 1
        self.minimumDiameterSpinBox.suffix = " voxels"
        self.minimumDiameterSpinBox.enabled = False
        self.minimumDiameterSpinBox.toolTip = "Tubular structures that have minimum this diameter will be enhanced."
        advancedFormLayout.addRow("Minimum vessel diameter:",
                                  self.minimumDiameterSpinBox)
        self.detectPushButton.connect("toggled(bool)",
                                      self.minimumDiameterSpinBox.setDisabled)

        self.maximumDiameterSpinBox = qt.QSpinBox()
        self.maximumDiameterSpinBox.minimum = 0
        self.maximumDiameterSpinBox.maximum = 1000
        self.maximumDiameterSpinBox.singleStep = 1
        self.maximumDiameterSpinBox.suffix = " voxels"
        self.maximumDiameterSpinBox.enabled = False
        self.maximumDiameterSpinBox.toolTip = "Tubular structures that have maximum this diameter will be enhanced."
        advancedFormLayout.addRow("Maximum vessel diameter:",
                                  self.maximumDiameterSpinBox)
        self.detectPushButton.connect("toggled(bool)",
                                      self.maximumDiameterSpinBox.setDisabled)

        self.contrastSlider = ctk.ctkSliderWidget()
        self.contrastSlider.decimals = 0
        self.contrastSlider.minimum = 0
        self.contrastSlider.maximum = 500
        self.contrastSlider.singleStep = 10
        self.contrastSlider.enabled = False
        self.contrastSlider.toolTip = "If the intensity contrast in the input image between vessel and background is high, choose a high value else choose a low value."
        advancedFormLayout.addRow("Vessel contrast:", self.contrastSlider)
        self.detectPushButton.connect("toggled(bool)",
                                      self.contrastSlider.setDisabled)

        self.suppressPlatesSlider = ctk.ctkSliderWidget()
        self.suppressPlatesSlider.decimals = 0
        self.suppressPlatesSlider.minimum = 0
        self.suppressPlatesSlider.maximum = 100
        self.suppressPlatesSlider.singleStep = 1
        self.suppressPlatesSlider.suffix = " %"
        self.suppressPlatesSlider.toolTip = "A higher value filters out more plate-like structures."
        advancedFormLayout.addRow("Suppress plates:",
                                  self.suppressPlatesSlider)

        self.suppressBlobsSlider = ctk.ctkSliderWidget()
        self.suppressBlobsSlider.decimals = 0
        self.suppressBlobsSlider.minimum = 0
        self.suppressBlobsSlider.maximum = 100
        self.suppressBlobsSlider.singleStep = 1
        self.suppressBlobsSlider.suffix = " %"
        self.suppressBlobsSlider.toolTip = "A higher value filters out more blob-like structures."
        advancedFormLayout.addRow("Suppress blobs:", self.suppressBlobsSlider)

        #
        # Reset, preview and apply buttons
        #

        self.buttonBox = qt.QDialogButtonBox()
        self.resetButton = self.buttonBox.addButton(
            self.buttonBox.RestoreDefaults)
        self.resetButton.toolTip = "Click to reset all input elements to default."
        self.previewButton = self.buttonBox.addButton(self.buttonBox.Discard)
        self.previewButton.setIcon(qt.QIcon())
        self.previewButton.text = "Preview"
        self.startButton = self.buttonBox.addButton(self.buttonBox.Apply)
        self.startButton.setIcon(qt.QIcon())
        self.startButton.text = "Start"
        self.startButton.enabled = False
        self.layout.addWidget(self.buttonBox)
        self.resetButton.connect("clicked()", self.restoreDefaults)
        self.previewButton.connect("clicked()", self.onPreviewButtonClicked)
        self.startButton.connect("clicked()", self.onStartButtonClicked)

        self.inputVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.seedFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.outputVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.previewVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)

        self.inputVolumeNodeSelector.connect(
            "currentNodeChanged(vtkMRMLNode*)", self.onNodeSelectionChanged)
        self.seedFiducialsNodeSelector.markupsSelectorComboBox().connect(
            "currentNodeChanged(vtkMRMLNode*)", self.onNodeSelectionChanged)
        self.seedFiducialsNodeSelector.connect("updateFinished()",
                                               self.onNodeSelectionChanged)

        # set default values
        self.restoreDefaults()

        self.onNodeSelectionChanged()

        # compress the layout
        self.layout.addStretch(1)
예제 #14
0
    def revealPixmap(self, xy):
        """fill a pixmap with an image that has a reveal pattern
    at xy with the fg drawn over the bg"""

        # Get QImages for the two layers
        bgVTKImage = self.layerLogics['B'].GetImageData()
        fgVTKImage = self.layerLogics['F'].GetImageData()
        bgQImage = qt.QImage()
        fgQImage = qt.QImage()
        slicer.qMRMLUtils().vtkImageDataToQImage(bgVTKImage, bgQImage)
        slicer.qMRMLUtils().vtkImageDataToQImage(fgVTKImage, fgQImage)

        # get the geometry of the focal point (xy) and images
        # noting that vtk has the origin at the bottom left and qt has
        # it at the top left.  yy is the flipped version of y
        imageWidth = bgQImage.width()
        imageHeight = bgQImage.height()
        x, y = xy
        yy = imageHeight - y

        #
        # make a generally transparent image,
        # then fill quadrants with the fg image
        #
        overlayImage = qt.QImage(imageWidth, imageHeight,
                                 qt.QImage().Format_ARGB32)
        overlayImage.fill(0)

        halfWidth = imageWidth // 2
        halfHeight = imageHeight // 2
        topLeft = qt.QRect(0, 0, x, yy)
        bottomRight = qt.QRect(x, yy, imageWidth - x - 1, imageHeight - yy - 1)

        self.painter.begin(overlayImage)
        self.painter.drawImage(topLeft, fgQImage, topLeft)
        self.painter.drawImage(bottomRight, fgQImage, bottomRight)
        self.painter.end()

        # draw the bg and fg on top of gray background
        compositePixmap = qt.QPixmap(self.width, self.height)
        compositePixmap.fill(self.gray)
        self.painter.begin(compositePixmap)
        self.painter.drawImage(-1 * (x - self.width // 2),
                               -1 * (yy - self.height // 2), bgQImage)
        self.painter.drawImage(-1 * (x - self.width // 2),
                               -1 * (yy - self.height // 2), overlayImage)
        self.painter.end()

        if self.scale:
            compositePixmap = self.scalePixmap(compositePixmap)

        # draw a border around the pixmap
        self.painter.begin(compositePixmap)
        self.pen = qt.QPen()
        self.color = qt.QColor("#FF0")
        self.color.setAlphaF(0.3)
        self.pen.setColor(self.color)
        self.pen.setWidth(5)
        self.pen.setStyle(3)  # dotted line (Qt::DotLine)
        self.painter.setPen(self.pen)
        rect = qt.QRect(1, 1, self.width - 2, self.height - 2)
        self.painter.drawRect(rect)
        self.painter.end()

        return compositePixmap
예제 #15
0
    def onListSelected(self):
        item = self.list.selectedItem()
        pixmap = None

        if item is None:
            pass
        elif item == self.root:
            pass
        else:
            element = self.device.getComponentByAddress(item.text(0))
            if element is not None:
                if element.isLeaf():
                    img_str = element.fetchImage()
                    if img_str is not None:
                        pixmap = qt.QPixmap()
                        pixmap.loadFromData(img_str)
                        if self.inversed_image:
                            m = qt.QWMatrix()
                            m.scale(1.0, -1.0)
                            pixmap = pixmap.xForm(m)

                        x = element.getImageX()
                        y = element.getImageY()
                        if (x is not None) and (y is not None):
                            # Overlays
                            p = qt.QPainter()
                            p.begin(pixmap)

                            p.setPen(qt.QPen(qt.QColor(0xE0, 0xE0, 0), 2))
                            size = 8

                            center = qt.QPoint(
                                int(x / 100.0 * pixmap.width()),
                                int(y / 100.0 * pixmap.height()),
                            )
                            if self.inversed_image:
                                center.setY(
                                    int((100.0 - y) / 100.0 * pixmap.height()))
                            p.drawLine(
                                qt.QPoint(center.x(),
                                          center.y() - size),
                                qt.QPoint(center.x(),
                                          center.y() + size),
                            )
                            p.drawLine(
                                qt.QPoint(center.x() - size, center.y()),
                                qt.QPoint(center.x() + size, center.y()),
                            )

                            p.setPen(qt.QPen(qt.QColor(0, 0xC0, 0), 2))
                            size = 20
                            center = qt.QPoint(
                                int(x / 100.0 * pixmap.width()),
                                int(y / 100.0 * pixmap.height()),
                            )
                            if self.inversed_image:
                                center.setY(
                                    int((100.0 - y) / 100.0 * pixmap.height()))
                            p.drawLine(
                                qt.QPoint(center.x(),
                                          center.y() - size),
                                qt.QPoint(center.x(),
                                          center.y() + size),
                            )
                            p.drawLine(
                                qt.QPoint(center.x() - size, center.y()),
                                qt.QPoint(center.x() + size, center.y()),
                            )
                            p.end()

                        self.widget.lbImage.setPixmap(pixmap)

        # This check because don't know how to clear QLabel but assigniong an empty pixmap, what prints a warning message
        # if pixmap!=self._empty_image_pixmap or self.widget.lbImage.pixmap() is None or self.widget.lbImage.pixmap().width()>0:
        #    self.widget.lbImage.setPixmap(pixmap)
        # self.widget.lbImage.setVisible(pixmap != self._empty_image_pixmap)
        if pixmap is not None:
            self.widget.lbImage.setPixmap(pixmap)
            self.widget.lbImage.show()
        else:
            self.widget.lbImage.clear()
            self.widget.lbImage.hide()
예제 #16
0
 def newNotification(self, change):
     button = self._status_bar_widgets["notifications"]
     button.setText(str(int(button.text()) + 1))
     button.setPaletteBackgroundColor(qt.QColor(180, 0, 0))
     self._notifications.append(change)
예제 #17
0
    def setup(self):
        """
    Called when the user opens the module the first time and the widget is initialized.
    """
        ScriptedLoadableModuleWidget.setup(self)

        # Load widget from .ui file (created by Qt Designer).
        # Additional widgets can be instantiated manually and added to self.layout.
        uiWidget = slicer.util.loadUI(self.resourcePath('UI/QReads.ui'))
        self.layout.addWidget(uiWidget)
        self.ui = slicer.util.childWidgetVariables(uiWidget)
        self.slabModeButtonGroup = qt.QButtonGroup()
        self.slabModeButtonGroup.addButton(self.ui.SlabModeMaxRadioButton,
                                           vtk.VTK_IMAGE_SLAB_MAX)
        self.slabModeButtonGroup.addButton(self.ui.SlabModeMeanRadioButton,
                                           vtk.VTK_IMAGE_SLAB_MEAN)
        self.slabModeButtonGroup.addButton(self.ui.SlabModeMinRadioButton,
                                           vtk.VTK_IMAGE_SLAB_MIN)
        self.ui.ZoomComboBox.addItems(self.ZOOM_ACTIONS)

        # Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
        # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
        # "setMRMLScene(vtkMRMLScene*)" slot.
        #uiWidget.setMRMLScene(slicer.mrmlScene)

        # Create logic class. Logic implements all computations that should be possible to run
        # in batch mode, without a graphical user interface.
        self.logic = QReadsLogic()

        # Connections

        # These connections ensure that we update parameter node when scene is closed
        self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent,
                         self.onSceneStartClose)
        self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent,
                         self.onSceneEndClose)
        self.addObserver(slicer.mrmlScene, slicer.mrmlScene.NodeAddedEvent,
                         self.onNodeAdded)

        # These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
        # (in the selected parameter node).
        self.ui.ShowReferenceMarkersButton.connect(
            "clicked()", self.updateParameterNodeFromGUI)
        self.ui.ResetReferenceMarkersButton.connect(
            "clicked()", QReadsLogic.resetReferenceMarkers)
        self.ui.SlabButton.connect("clicked()",
                                   self.updateParameterNodeFromGUI)
        self.slabModeButtonGroup.connect("buttonClicked(int)",
                                         self.updateParameterNodeFromGUI)
        self.ui.SlabThicknessSliderWidget.connect(
            "valueChanged(double)", self.updateParameterNodeFromGUI)
        self.ui.InverseGrayButton.connect("clicked(bool)",
                                          self.updateParameterNodeFromGUI)

        # Increasing the level will make the image darker, whereas decreasing the level value will make the image brighter
        self.ui.BrightnessUpButton.connect(
            "clicked()",
            lambda step=-self.BRIGHTNESS_STEP: QReadsLogic.updateWindowLevel(
                levelStep=step))
        self.ui.BrightnessDownButton.connect(
            "clicked()",
            lambda step=self.BRIGHTNESS_STEP: QReadsLogic.updateWindowLevel(
                levelStep=step))

        # Increasing window will reduce display contrast, whereas decreasing the window increases the brightness
        self.ui.ContrastUpButton.connect(
            "clicked()",
            lambda step=-self.CONTRAST_STEP: QReadsLogic.updateWindowLevel(
                windowStep=step))
        self.ui.ContrastDownButton.connect(
            "clicked()",
            lambda step=self.CONTRAST_STEP: QReadsLogic.updateWindowLevel(
                windowStep=step))

        self.ui.CTBodySoftTissueWLPresetButton.connect(
            "clicked()",
            lambda presetName="CT-BodySoftTissue": self.logic.
            setWindowLevelPreset(presetName))
        self.ui.CTBoneWLPresetButton.connect(
            "clicked()",
            lambda presetName="CT-Bone": self.logic.setWindowLevelPreset(
                presetName))
        self.ui.CTBrainWLPresetButton.connect(
            "clicked()",
            lambda presetName="CT-Head": self.logic.setWindowLevelPreset(
                presetName))
        self.ui.CTLungWLPresetButton.connect(
            "clicked()",
            lambda presetName="CT-Lung": self.logic.setWindowLevelPreset(
                presetName))

        self.ui.ZoomComboBox.connect("currentTextChanged(QString)",
                                     self.updateParameterNodeFromGUI)

        self.ui.CloseApplicationPushButton.connect("clicked()",
                                                   slicer.util.quit)

        # Make sure parameter node is initialized (needed for module reload)
        self.initializeParameterNode()

        # Hide main window components
        slicer.util.setApplicationLogoVisible(False)
        slicer.util.setMenuBarsVisible(False)
        slicer.util.setModuleHelpSectionVisible(False)
        slicer.util.setModulePanelTitleVisible(False)
        slicer.util.setToolbarsVisible(False)

        # Layout
        slicer.app.layoutManager().setLayout(self.logic.registerCustomLayout())

        for viewName, viewColor in QReadsLogic.SLICEVIEW_BACKGROUND_COLORS.items(
        ):
            sliceWidget = slicer.app.layoutManager().sliceWidget(viewName)
            sliceWidget.sliceView().setBackgroundColor(qt.QColor(viewColor))
            sliceNode = sliceWidget.mrmlSliceNode()
            sliceNode.SetOrientationMarkerType(
                slicer.vtkMRMLAbstractViewNode.OrientationMarkerTypeAxes)
            sliceNode.SetSliceVisible(True)

        for viewName, viewColor in QReadsLogic.THREEDVIEW_BACKGROUND_COLORS.items(
        ):
            with NodeModify(slicer.util.getNode("vtkMRMLViewNode%s" %
                                                viewName)) as viewNode:
                viewNode.SetBackgroundColor(0., 0., 0.)
                viewNode.SetBackgroundColor2(0., 0., 0.)
                viewNode.SetBoxVisible(False)
                viewNode.SetAxisLabelsVisible(False)
                viewNode.SetOrientationMarkerType(
                    slicer.vtkMRMLAbstractViewNode.OrientationMarkerTypeAxes)
  def setup(self):
    ScriptedLoadableModuleWidget.setup(self)

    #
    # Inputs
    #

    inputsCollapsibleButton = ctk.ctkCollapsibleButton()
    inputsCollapsibleButton.text = "Inputs"
    self.layout.addWidget(inputsCollapsibleButton)
    inputsFormLayout = qt.QFormLayout(inputsCollapsibleButton)

    # inputVolume selector
    self.inputModelNodeSelector = slicer.qMRMLNodeComboBox()
    self.inputModelNodeSelector.objectName = 'inputModelNodeSelector'
    self.inputModelNodeSelector.toolTip = "Select the input model."
    self.inputModelNodeSelector.nodeTypes = ['vtkMRMLModelNode']
    self.inputModelNodeSelector.hideChildNodeTypes = ['vtkMRMLAnnotationNode']  # hide all annotation nodes
    self.inputModelNodeSelector.noneEnabled = False
    self.inputModelNodeSelector.addEnabled = False
    self.inputModelNodeSelector.removeEnabled = False
    inputsFormLayout.addRow("Vessel tree model:", self.inputModelNodeSelector)
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                        self.inputModelNodeSelector, 'setMRMLScene(vtkMRMLScene*)')

    # seed selector
    self.seedFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
    self.seedFiducialsNodeSelector.objectName = 'seedFiducialsNodeSelector'
    self.seedFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
    self.seedFiducialsNodeSelector.objectName = 'seedFiducialsNodeSelector'
    self.seedFiducialsNodeSelector.toolTip = "Select a fiducial to use as the origin of the Centerline."
    self.seedFiducialsNodeSelector.setNodeBaseName("OriginSeed")
    self.seedFiducialsNodeSelector.defaultNodeColor = qt.QColor(0,255,0)
    self.seedFiducialsNodeSelector.tableWidget().hide()
    self.seedFiducialsNodeSelector.markupsSelectorComboBox().noneEnabled = False
    self.seedFiducialsNodeSelector.markupsPlaceWidget().placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceSingleMarkup
    inputsFormLayout.addRow("Start point:", self.seedFiducialsNodeSelector)
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                        self.seedFiducialsNodeSelector, 'setMRMLScene(vtkMRMLScene*)')

    #
    # Outputs
    #

    outputsCollapsibleButton = ctk.ctkCollapsibleButton()
    outputsCollapsibleButton.text = "Outputs"
    self.layout.addWidget(outputsCollapsibleButton)
    outputsFormLayout = qt.QFormLayout(outputsCollapsibleButton)
                        
    # outputModel selector
    self.outputModelNodeSelector = slicer.qMRMLNodeComboBox()
    self.outputModelNodeSelector.objectName = 'outputModelNodeSelector'
    self.outputModelNodeSelector.toolTip = "Select the output model for the Centerlines."
    self.outputModelNodeSelector.nodeTypes = ['vtkMRMLModelNode']
    self.outputModelNodeSelector.baseName = "CenterlineComputationModel"
    self.outputModelNodeSelector.hideChildNodeTypes = ['vtkMRMLAnnotationNode']  # hide all annotation nodes
    self.outputModelNodeSelector.noneEnabled = True
    self.outputModelNodeSelector.noneDisplay = "Create new model"
    self.outputModelNodeSelector.addEnabled = True
    self.outputModelNodeSelector.selectNodeUponCreation = True
    self.outputModelNodeSelector.removeEnabled = True
    outputsFormLayout.addRow("Centerline model:", self.outputModelNodeSelector)
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                        self.outputModelNodeSelector, 'setMRMLScene(vtkMRMLScene*)')

    self.outputEndPointsNodeSelector = slicer.qMRMLNodeComboBox()
    self.outputEndPointsNodeSelector.objectName = 'outputEndPointsNodeSelector'
    self.outputEndPointsNodeSelector.toolTip = "Select the output model for the Centerlines."
    self.outputEndPointsNodeSelector.nodeTypes = ['vtkMRMLMarkupsFiducialNode']
    self.outputEndPointsNodeSelector.baseName = "Centerline endpoints"
    self.outputEndPointsNodeSelector.noneEnabled = True
    self.outputEndPointsNodeSelector.noneDisplay = "Create new markups fiducial"
    self.outputEndPointsNodeSelector.addEnabled = True
    self.outputEndPointsNodeSelector.selectNodeUponCreation = True
    self.outputEndPointsNodeSelector.removeEnabled = True
    outputsFormLayout.addRow("Centerline endpoints:", self.outputEndPointsNodeSelector)
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                        self.outputEndPointsNodeSelector, 'setMRMLScene(vtkMRMLScene*)')
                        
    # voronoiModel selector
    self.voronoiModelNodeSelector = slicer.qMRMLNodeComboBox()
    self.voronoiModelNodeSelector.objectName = 'voronoiModelNodeSelector'
    self.voronoiModelNodeSelector.toolTip = "Select the output model for the Voronoi Diagram."
    self.voronoiModelNodeSelector.nodeTypes = ['vtkMRMLModelNode']
    self.voronoiModelNodeSelector.baseName = "VoronoiModel"
    self.voronoiModelNodeSelector.hideChildNodeTypes = ['vtkMRMLAnnotationNode']  # hide all annotation nodes
    self.voronoiModelNodeSelector.noneEnabled = True
    self.voronoiModelNodeSelector.addEnabled = True
    self.voronoiModelNodeSelector.selectNodeUponCreation = True
    self.voronoiModelNodeSelector.removeEnabled = True
    outputsFormLayout.addRow("Voronoi Model:", self.voronoiModelNodeSelector)
    self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                        self.voronoiModelNodeSelector, 'setMRMLScene(vtkMRMLScene*)')

    #
    # Reset, preview and apply buttons
    #

    self.buttonBox = qt.QDialogButtonBox()
    self.previewButton = self.buttonBox.addButton(self.buttonBox.Discard)
    self.previewButton.setIcon(qt.QIcon())
    self.previewButton.text = "Preview"
    self.previewButton.toolTip = "Click to refresh the preview."
    self.startButton = self.buttonBox.addButton(self.buttonBox.Apply)
    self.startButton.setIcon(qt.QIcon())
    self.startButton.text = "Start"
    self.startButton.enabled = False
    self.startButton.toolTip = "Click to start the filtering."
    self.layout.addWidget(self.buttonBox)
    self.previewButton.connect("clicked()", self.onPreviewButtonClicked)
    self.startButton.connect("clicked()", self.onStartButtonClicked)

    self.inputModelNodeSelector.setMRMLScene(slicer.mrmlScene)
    self.seedFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)
    self.outputModelNodeSelector.setMRMLScene(slicer.mrmlScene)
    self.outputEndPointsNodeSelector.setMRMLScene(slicer.mrmlScene)
    self.voronoiModelNodeSelector.setMRMLScene(slicer.mrmlScene)

    # compress the layout
    self.layout.addStretch(1)
예제 #19
0
 def splashMessage(self, message):
     self._splash_screen.message(message,
                                 qt.Qt.AlignLeft | qt.Qt.AlignBottom,
                                 qt.QColor(180, 0, 0))
    def setup(self):
        ScriptedLoadableModuleWidget.setup(self)

        # Instantiate and connect widgets ...

        #clear scene
        # slicer.mrmlScene.Clear(0)

        #Define Widgets layout
        lm = slicer.app.layoutManager()
        lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutThreeOverThreeView)
        lm.sliceWidget('Red').setSliceOrientation('Axial')
        lm.sliceWidget('Red+').setSliceOrientation('Axial')
        lm.sliceWidget('Yellow').setSliceOrientation('Axial')
        lm.sliceWidget('Yellow+').setSliceOrientation('Axial')
        lm.sliceWidget('Green').setSliceOrientation('Axial')
        lm.sliceWidget('Green+').setSliceOrientation('Axial')

        #
        # Parameters Area
        #
        parametersCollapsibleButton = ctk.ctkCollapsibleButton()
        parametersCollapsibleButton.text = "Parameters"
        self.layout.addWidget(parametersCollapsibleButton)

        # Layout within the dummy collapsible button
        parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)

        #
        # input volume selector
        #
        self.inputSelector = slicer.qMRMLNodeComboBox()
        self.inputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"]
        self.inputSelector.selectNodeUponCreation = True
        self.inputSelector.addEnabled = False
        self.inputSelector.removeEnabled = False
        self.inputSelector.noneEnabled = False
        self.inputSelector.showHidden = False
        self.inputSelector.showChildNodeTypes = False
        self.inputSelector.setMRMLScene(slicer.mrmlScene)
        self.inputSelector.setToolTip("Pick the input to the algorithm.")
        #parametersFormLayout.addRow("Input Volume: ", self.inputSelector)  Por ahora no lo mostramos.

        #
        # output volume selector
        #
        self.outputSelector = slicer.qMRMLNodeComboBox()
        self.outputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"]
        self.outputSelector.selectNodeUponCreation = True
        self.outputSelector.addEnabled = True
        self.outputSelector.removeEnabled = True
        self.outputSelector.noneEnabled = True
        self.outputSelector.showHidden = False
        self.outputSelector.showChildNodeTypes = False
        self.outputSelector.setMRMLScene(slicer.mrmlScene)
        self.outputSelector.setToolTip("Pick the output to the algorithm.")
        parametersFormLayout.addRow("Volume: ", self.outputSelector)

        #
        # Take Working Image Button
        #
        self.takeImageButton = qt.QPushButton("Take working image")
        self.takeImageButton.toolTip = "Take working image"
        self.takeImageButton.enabled = True
        parametersFormLayout.addRow(self.takeImageButton)

        #
        # Processing selector
        #
        self.processingSelector = qt.QComboBox()
        self.processingSelector.addItem("original")
        self.processingSelector.addItem("image smoothing")
        self.processingSelector.addItem("image segmentation")
        self.processingSelector.addItem("image segmentation + no holes")
        self.processingSelector.addItem("contouring")
        parametersFormLayout.addRow("Processing: ", self.processingSelector)

        #
        #  SpinBoxes : numerical inputs
        #
        self.segmentationGroupBox = qt.QGroupBox("Segmentation Data")
        self.segmentationVBoxLayout = qt.QVBoxLayout()

        self.tempGroupBox = qt.QGroupBox("Temperature")
        self.tempHBoxLayout = qt.QHBoxLayout()

        self.qlabelMin = QLabel('Min:')
        self.doubleMinTemp = ctk.ctkSliderWidget()
        self.doubleMinTemp.setSizePolicy(QSizePolicy.Ignored,
                                         QSizePolicy.Preferred)
        self.doubleMinTemp.setDecimals(2)
        self.doubleMinTemp.setValue(27.0)
        self.tempHBoxLayout.addWidget(self.qlabelMin)
        self.tempHBoxLayout.addWidget(self.doubleMinTemp)

        self.labelMax = qt.QLabel("Max:  ")
        self.doubleMaxTemp = ctk.ctkSliderWidget()
        self.doubleMaxTemp.setValue(35.0)
        self.tempHBoxLayout.addWidget(self.labelMax)
        self.tempHBoxLayout.addWidget(self.doubleMaxTemp)

        self.tempGroupBox.setLayout(self.tempHBoxLayout)
        self.segmentationVBoxLayout.addWidget(self.tempGroupBox)

        #
        # Button to get foot seed
        #
        self.seedBoxesGroup = qt.QGroupBox("Seed")

        frameControlHBox = qt.QVBoxLayout()

        self.seedCoords = {}

        # Seed Left selector
        self.seedLeftFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget(
        )
        self.seedLeftFiducialsNodeSelector.objectName = 'seedLeftFiducialsNodeSelector'
        self.seedLeftFiducialsNodeSelector.toolTip = "Select a fiducial to use as the origin of the left segments."
        self.seedLeftFiducialsNodeSelector.setNodeBaseName("Left")
        self.seedLeftFiducialsNodeSelector.defaultNodeColor = qt.QColor(
            0, 255, 0)
        self.seedLeftFiducialsNodeSelector.tableWidget().hide()
        self.seedLeftFiducialsNodeSelector.markupsSelectorComboBox(
        ).noneEnabled = False
        self.seedLeftFiducialsNodeSelector.markupsPlaceWidget(
        ).placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceSingleMarkup
        self.seedLeftFiducialsNodeSelector.markupsPlaceWidget(
        ).buttonsVisible = False
        self.seedLeftFiducialsNodeSelector.markupsPlaceWidget().placeButton(
        ).show()
        self.seedLeftFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)

        self.seedFiducialsBox = qt.QHBoxLayout()
        self.seedLabelWidget = qt.QLabel("Choose left seed node:")
        self.seedFiducialsBox.addWidget(self.seedLabelWidget)
        self.seedFiducialsBox.addWidget(self.seedLeftFiducialsNodeSelector)
        self.leftFiducial = qt.QGroupBox("Left: ")
        self.leftFiducial.setLayout(self.seedFiducialsBox)

        # Seed Right selector
        self.seedRightFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget(
        )
        self.seedRightFiducialsNodeSelector.objectName = 'seedRightFiducialsNodeSelector'
        self.seedRightFiducialsNodeSelector.toolTip = "Select a fiducial to use as the origin of the left segments."
        self.seedRightFiducialsNodeSelector.setNodeBaseName("Right")
        self.seedRightFiducialsNodeSelector.defaultNodeColor = qt.QColor(
            0, 255, 0)
        self.seedRightFiducialsNodeSelector.tableWidget().hide()
        self.seedRightFiducialsNodeSelector.markupsSelectorComboBox(
        ).noneEnabled = False
        self.seedRightFiducialsNodeSelector.markupsPlaceWidget(
        ).placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceSingleMarkup
        self.seedRightFiducialsNodeSelector.markupsPlaceWidget(
        ).buttonsVisible = False
        self.seedRightFiducialsNodeSelector.markupsPlaceWidget().placeButton(
        ).show()
        self.seedRightFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)
        seedRightFiducialsNodeSelector = self.seedRightFiducialsNodeSelector

        self.seedRightFiducialsBox = qt.QHBoxLayout()
        self.seedRightLabelWidget = qt.QLabel("Choose right seed node:")
        self.seedRightFiducialsBox.addWidget(self.seedRightLabelWidget)
        self.seedRightFiducialsBox.addWidget(
            self.seedRightFiducialsNodeSelector)
        self.rightFiducial = qt.QGroupBox("Right: ")
        self.rightFiducial.setLayout(self.seedRightFiducialsBox)

        frameControlHBox.addWidget(self.leftFiducial)
        frameControlHBox.addWidget(self.rightFiducial)

        self.seedBoxesGroup.setLayout(frameControlHBox)
        self.segmentationVBoxLayout.addWidget(self.seedBoxesGroup)

        # #Set Group
        self.segmentationGroupBox.setLayout(self.segmentationVBoxLayout)

        parametersFormLayout.addRow(self.segmentationGroupBox)

        #
        # Processing Button
        #
        self.extractButton = qt.QPushButton("Apply Segmentation")
        self.extractButton.toolTip = "Run the algorithm."
        # self.extractButton.enabled = False
        parametersFormLayout.addRow(self.extractButton)

        # connections
        self.extractButton.connect('clicked(bool)', self.onExtractButton)
        self.takeImageButton.connect('clicked(bool)', self.onTakeImageButton)
        self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)",
                                    self.onSelectWorkingImage)
        self.processingSelector.connect('currentIndexChanged(QString)',
                                        self.onProcessing)

        # self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)', self.seedFiducialsNodeSelector, 'setMRMLScene(vtkMRMLScene*)')

        # Add vertical spacer
        self.layout.addStretch(1)
예제 #21
0
 def setActive(self):
     """
     """
     self.__pen = self.pen()
     self.setPen(qt.QPen(qt.QColor(qt.Qt.red), 1))
예제 #22
0
 def __movetoMosaicStateChanged(self,state):
     if self.movetoColorWhenActivate:
         if state:
             self.__movetoActionMosaic.setPaletteBackgroundColor(qt.QColor(self.movetoColorWhenActivate))
         else:
             self.__movetoActionMosaic.setPaletteBackgroundColor(self.__oldMoveToMosaicActionColor)
예제 #23
0
    def drawShape(self, painter):
        """
        Overloads the QCanvasRectangle drawShape. Performs the drawing of the
        grid.

        :param painter: The QPainter object to use when drawing.
        :type painter: QPainter
        """
        self.__painter = painter
        rect = self.rect()

        self.__num_cells = 0
        num_rows = (rect.bottom() - rect.top()) / self.__cell_height
        num_colls = (rect.right() - rect.left()) / self.__cell_width

        if self.__highlighted:
            painter.setPen(qt.QPen(qt.Qt.green, 0, qt.Qt.SolidLine))
        else:
            painter.setPen(qt.QPen(qt.Qt.black, 0, qt.Qt.DotLine))

        for i in range(0, num_rows + 1):
            offset = i * self.__cell_height
            self.__height = offset
            painter.drawLine(rect.left(),
                             rect.top() + offset, rect.right(),
                             rect.top() + offset)

        for i in range(0, num_colls + 1):
            offset = i * self.__cell_width
            self.__width = offset
            painter.drawLine(rect.left() + offset, rect.top(),
                             rect.left() + offset, rect.bottom())

        for i in range(0, num_rows):
            row_offset = i * self.__cell_height
            for k in range(0, num_colls):
                coll_offset = k * self.__cell_width
                self.__num_cells += 1
                if not self.__has_data:
                    if self.__num_cells % 2:
                        self.__grid_data[self.__num_cells] = (self.__num_cells,
                                                              (0, 0, 150))
                    else:
                        self.__grid_data[self.__num_cells] = (self.__num_cells,
                                                              (0, 0, 150))

                painter.setPen(qt.QPen(qt.Qt.black, 0, qt.Qt.SolidLine))

                color = self.__grid_data[self.__num_cells][1]

                #if self.__highlighted:
                painter.setBrush(
                    qt.QBrush(qt.QColor(*color), qt.Qt.Dense4Pattern))
                #else:
                #    painter.setBrush(qt.QBrush(qt.QColor(*color), qt.Qt.Dense6Pattern))

                beam_hspacing = (self.__cell_width - self.__beam_width) / 2
                beam_vspacing = (self.__cell_height - self.__beam_height) / 2

                painter.drawEllipse(rect.left() + coll_offset + beam_hspacing,
                                    rect.top() + row_offset + beam_vspacing,
                                    self.__beam_width, self.__beam_height)

                painter.setPen(qt.QPen(qt.Qt.black, 1, qt.Qt.SolidLine))
                tr = qt.QRect(rect.left() + coll_offset,
                              rect.top() + row_offset, self.__cell_width,
                              self.__cell_height)

                score = self.__grid_data[self.__num_cells][0]

                if score:
                    painter.drawText(tr, qt.Qt.AlignCenter, str(score))

            if self.__label and self.__highlighted:
                #painter.setPen(qt.QPen(qt.Qt.green, 0, qt.Qt.SolidLine))
                painter.drawText(rect.right() + 2,
                                 rect.top() - 5, self.__label)

        self.__num_rows = num_rows
        self.__num_colls = num_colls
예제 #24
0
 def stateChanged(self, index):
     state = SpecValueBrick.nameState[index]      
     qcolor = qt.QColor(SpecValueBrick.colorState[state])
     if self.displayWidget is not None:
         self.displayWidget.setValueBackgroundColor(qcolor)
    def setup(self):
        ScriptedLoadableModuleWidget.setup(self)

        #
        # the I/O panel
        #

        inputsCollapsibleButton = ctk.ctkCollapsibleButton()
        inputsCollapsibleButton.text = "Inputs"
        self.layout.addWidget(inputsCollapsibleButton)
        inputsFormLayout = qt.QFormLayout(inputsCollapsibleButton)

        # inputVolume selector
        self.inputVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.inputVolumeNodeSelector.objectName = 'inputVolumeNodeSelector'
        self.inputVolumeNodeSelector.toolTip = "Select the input volume. This should always be the original image and not a vesselness image, if possible."
        self.inputVolumeNodeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
        self.inputVolumeNodeSelector.noneEnabled = False
        self.inputVolumeNodeSelector.addEnabled = False
        self.inputVolumeNodeSelector.removeEnabled = False
        inputsFormLayout.addRow("Input Volume:", self.inputVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.inputVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')
        self.inputVolumeNodeSelector.connect(
            'currentNodeChanged(vtkMRMLNode*)', self.onInputVolumeChanged)

        # vesselnessVolume selector
        self.vesselnessVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.vesselnessVolumeNodeSelector.objectName = 'vesselnessVolumeNodeSelector'
        self.vesselnessVolumeNodeSelector.toolTip = "Select the input vesselness volume."
        self.vesselnessVolumeNodeSelector.nodeTypes = [
            'vtkMRMLScalarVolumeNode'
        ]
        self.vesselnessVolumeNodeSelector.noneEnabled = True
        self.vesselnessVolumeNodeSelector.addEnabled = False
        self.vesselnessVolumeNodeSelector.removeEnabled = False
        inputsFormLayout.addRow("Vesselness Volume:",
                                self.vesselnessVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.vesselnessVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')
        self.vesselnessVolumeNodeSelector.connect(
            'currentNodeChanged(vtkMRMLNode*)', self.onVesselnessVolumeChanged)
        self.vesselnessVolumeNodeSelector.setCurrentNode(None)

        # seed selector
        self.seedFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
        self.seedFiducialsNodeSelector.objectName = 'seedFiducialsNodeSelector'
        self.seedFiducialsNodeSelector.toolTip = "Select start and end point of the vessel branch. Only the first and last point in the list are used."
        self.seedFiducialsNodeSelector.defaultNodeColor = qt.QColor(
            0, 0, 255)  # blue
        self.seedFiducialsNodeSelector.jumpToSliceEnabled = True
        self.seedFiducialsNodeSelector.markupsPlaceWidget(
        ).placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceMultipleMarkups
        self.seedFiducialsNodeSelector.setNodeBaseName("seeds")
        self.seedFiducialsNodeSelector.markupsSelectorComboBox(
        ).baseName = "Seeds"
        self.seedFiducialsNodeSelector.markupsSelectorComboBox(
        ).noneEnabled = False
        self.seedFiducialsNodeSelector.markupsSelectorComboBox(
        ).removeEnabled = True
        inputsFormLayout.addRow("Seeds:", self.seedFiducialsNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.seedFiducialsNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        # stopper selector
        self.stopperFiducialsNodeSelector = slicer.qSlicerSimpleMarkupsWidget()
        self.stopperFiducialsNodeSelector.objectName = 'stopperFiducialsNodeSelector'
        self.stopperFiducialsNodeSelector.toolTip = "(Optional) Select a hierarchy containing the fiducials to use as Stoppers. Whenever one stopper is reached, the segmentation stops."
        self.stopperFiducialsNodeSelector.defaultNodeColor = qt.QColor(
            0, 0, 255)  # blue
        self.stopperFiducialsNodeSelector.setNodeBaseName("seeds")
        self.stopperFiducialsNodeSelector.tableWidget().hide()
        self.stopperFiducialsNodeSelector.markupsSelectorComboBox(
        ).baseName = "Stoppers"
        self.stopperFiducialsNodeSelector.markupsSelectorComboBox(
        ).noneEnabled = True
        self.stopperFiducialsNodeSelector.markupsSelectorComboBox(
        ).removeEnabled = True
        inputsFormLayout.addRow("Stoppers:", self.stopperFiducialsNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.stopperFiducialsNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        #
        # Outputs
        #

        outputsCollapsibleButton = ctk.ctkCollapsibleButton()
        outputsCollapsibleButton.text = "Outputs"
        self.layout.addWidget(outputsCollapsibleButton)
        outputsFormLayout = qt.QFormLayout(outputsCollapsibleButton)

        # outputVolume selector
        self.outputVolumeNodeSelector = slicer.qMRMLNodeComboBox()
        self.outputVolumeNodeSelector.toolTip = "Select the output labelmap."
        self.outputVolumeNodeSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']
        self.outputVolumeNodeSelector.baseName = "LevelSetSegmentation"
        self.outputVolumeNodeSelector.noneEnabled = False
        self.outputVolumeNodeSelector.addEnabled = True
        self.outputVolumeNodeSelector.selectNodeUponCreation = True
        self.outputVolumeNodeSelector.removeEnabled = True
        outputsFormLayout.addRow("Output Labelmap:",
                                 self.outputVolumeNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.outputVolumeNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        # outputModel selector
        self.outputModelNodeSelector = slicer.qMRMLNodeComboBox()
        self.outputModelNodeSelector.objectName = 'outputModelNodeSelector'
        self.outputModelNodeSelector.toolTip = "Select the output model."
        self.outputModelNodeSelector.nodeTypes = ['vtkMRMLModelNode']
        self.outputModelNodeSelector.hideChildNodeTypes = [
            'vtkMRMLAnnotationNode'
        ]  # hide all annotation nodes
        self.outputModelNodeSelector.baseName = "LevelSetSegmentationModel"
        self.outputModelNodeSelector.noneEnabled = False
        self.outputModelNodeSelector.addEnabled = True
        self.outputModelNodeSelector.selectNodeUponCreation = True
        self.outputModelNodeSelector.removeEnabled = True
        outputsFormLayout.addRow("Output Model:", self.outputModelNodeSelector)
        self.parent.connect('mrmlSceneChanged(vtkMRMLScene*)',
                            self.outputModelNodeSelector,
                            'setMRMLScene(vtkMRMLScene*)')

        #
        # the segmentation panel
        #

        segmentationCollapsibleButton = ctk.ctkCollapsibleButton()
        segmentationCollapsibleButton.text = "Segmentation"
        self.layout.addWidget(segmentationCollapsibleButton)

        segmentationFormLayout = qt.QFormLayout(segmentationCollapsibleButton)

        # Threshold slider
        thresholdLabel = qt.QLabel()
        thresholdLabel.text = "Thresholding" + (' ' * 7)
        thresholdLabel.toolTip = "Choose the intensity range to segment."
        thresholdLabel.setAlignment(4)
        segmentationFormLayout.addRow(thresholdLabel)

        self.thresholdSlider = slicer.qMRMLRangeWidget()
        segmentationFormLayout.addRow(self.thresholdSlider)
        self.thresholdSlider.connect('valuesChanged(double,double)',
                                     self.onThresholdSliderChanged)

        self.segmentationAdvancedToggle = qt.QCheckBox(
            "Show Advanced Segmentation Properties")
        self.segmentationAdvancedToggle.setChecked(False)
        segmentationFormLayout.addRow(self.segmentationAdvancedToggle)

        #
        # segmentation advanced panel
        #

        self.segmentationAdvancedPanel = qt.QFrame(
            segmentationCollapsibleButton)
        self.segmentationAdvancedPanel.hide()
        self.segmentationAdvancedPanel.setFrameStyle(6)
        segmentationFormLayout.addRow(self.segmentationAdvancedPanel)
        self.segmentationAdvancedToggle.connect(
            "clicked()", self.onSegmentationAdvancedToggle)

        segmentationAdvancedFormLayout = qt.QFormLayout(
            self.segmentationAdvancedPanel)

        # inflation slider
        inflationLabel = qt.QLabel()
        inflationLabel.text = "less inflation <-> more inflation" + (' ' * 14)
        inflationLabel.setAlignment(4)
        inflationLabel.toolTip = "Define how fast the segmentation expands."
        segmentationAdvancedFormLayout.addRow(inflationLabel)

        self.inflationSlider = ctk.ctkSliderWidget()
        self.inflationSlider.decimals = 0
        self.inflationSlider.minimum = -100
        self.inflationSlider.maximum = 100
        self.inflationSlider.singleStep = 10
        self.inflationSlider.toolTip = inflationLabel.toolTip
        segmentationAdvancedFormLayout.addRow(self.inflationSlider)

        # curvature slider
        curvatureLabel = qt.QLabel()
        curvatureLabel.text = "less curvature <-> more curvature" + (' ' * 14)
        curvatureLabel.setAlignment(4)
        curvatureLabel.toolTip = "Choose a high curvature to generate a smooth segmentation."
        segmentationAdvancedFormLayout.addRow(curvatureLabel)

        self.curvatureSlider = ctk.ctkSliderWidget()
        self.curvatureSlider.decimals = 0
        self.curvatureSlider.minimum = -100
        self.curvatureSlider.maximum = 100
        self.curvatureSlider.singleStep = 10
        self.curvatureSlider.toolTip = curvatureLabel.toolTip
        segmentationAdvancedFormLayout.addRow(self.curvatureSlider)

        # attraction slider
        attractionLabel = qt.QLabel()
        attractionLabel.text = "less attraction to gradient <-> more attraction to gradient" + (
            ' ' * 14)
        attractionLabel.setAlignment(4)
        attractionLabel.toolTip = "Configure how the segmentation travels towards gradient ridges (vessel lumen wall)."
        segmentationAdvancedFormLayout.addRow(attractionLabel)

        self.attractionSlider = ctk.ctkSliderWidget()
        self.attractionSlider.decimals = 0
        self.attractionSlider.minimum = -100
        self.attractionSlider.maximum = 100
        self.attractionSlider.singleStep = 10
        self.attractionSlider.toolTip = attractionLabel.toolTip
        segmentationAdvancedFormLayout.addRow(self.attractionSlider)

        # iteration spinbox
        self.iterationSpinBox = qt.QSpinBox()
        self.iterationSpinBox.minimum = 0
        self.iterationSpinBox.maximum = 5000
        self.iterationSpinBox.singleStep = 10
        self.iterationSpinBox.toolTip = "Choose the number of evolution iterations."
        segmentationAdvancedFormLayout.addRow((' ' * 100) + "Iterations:",
                                              self.iterationSpinBox)

        #
        # Reset, preview and apply buttons
        #

        self.buttonBox = qt.QDialogButtonBox()
        self.resetButton = self.buttonBox.addButton(
            self.buttonBox.RestoreDefaults)
        self.resetButton.toolTip = "Click to reset all input elements to default."
        self.previewButton = self.buttonBox.addButton(self.buttonBox.Discard)
        self.previewButton.setIcon(qt.QIcon())
        self.previewButton.text = "Preview"
        self.previewButton.toolTip = "Click to refresh the preview."
        self.startButton = self.buttonBox.addButton(self.buttonBox.Apply)
        self.startButton.setIcon(qt.QIcon())
        self.startButton.text = "Start"
        self.startButton.enabled = False
        self.startButton.toolTip = "Click to start the filtering."
        self.layout.addWidget(self.buttonBox)
        self.resetButton.connect("clicked()", self.restoreDefaults)
        self.previewButton.connect("clicked()", self.onPreviewButtonClicked)
        self.startButton.connect("clicked()", self.onStartButtonClicked)

        self.inputVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.seedFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.vesselnessVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.outputVolumeNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.outputModelNodeSelector.setMRMLScene(slicer.mrmlScene)
        self.stopperFiducialsNodeSelector.setMRMLScene(slicer.mrmlScene)

        # set default values
        self.restoreDefaults()
        self.onInputVolumeChanged()

        # compress the layout
        self.layout.addStretch(1)
    def setup(self):
        """
    Called when the user opens the module the first time and the widget is initialized.
    """

        ScriptedLoadableModuleWidget.setup(self)

        # Load widget from .ui file (created by Qt Designer)
        uiWidget = slicer.util.loadUI(
            self.resourcePath('UI/AbdominalBiopsyNavigation.ui'))
        self.layout.addWidget(uiWidget)
        self.ui = slicer.util.childWidgetVariables(uiWidget)

        # Set scene in MRML widgets. Make sure that in Qt designer
        # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
        # "setMRMLScene(vtkMRMLScene*)" slot.
        uiWidget.setMRMLScene(slicer.mrmlScene)

        # Set up slicer scene
        self.setupScene()
        self.setupCustomViews()

        # Create a new parameterNode
        # This parameterNode stores all user choices in parameter values, node selections, etc.
        # so that when the scene is saved and reloaded, these settings are restored.
        self.logic = AbdominalBiopsyNavigationLogic()
        self.ui.parameterNodeSelector.addAttribute("vtkMRMLScriptedModuleNode",
                                                   "ModuleName",
                                                   self.moduleName)
        self.setParameterNode(self.logic.getParameterNode())

        # Dependencies
        self.markupsLogic = slicer.modules.markups.logic()

        # Connections
        self.ui.parameterNodeSelector.connect(
            'currentNodeChanged(vtkMRMLNode*)', self.setParameterNode)

        self.ui.saveButton.connect('clicked(bool)', self.onSaveScene)
        self.ui.connectPLUSButton.connect('clicked(bool)', self.onConnectPLUS)
        self.ui.layoutComboBox.connect('activated(const QString &)',
                                       self.onChangeLayout)
        self.ui.needleSpinCalibrationButton.connect('clicked(bool)',
                                                    self.needleSpinCalibration)
        self.ui.needlePivotCalibrationButton.connect(
            'clicked(bool)', self.needlePivotCalibration)
        self.ui.stylusSpinCalibrationButton.connect('clicked(bool)',
                                                    self.stylusSpinCalibration)
        self.ui.stylusPivotCalibrationButton.connect(
            'clicked(bool)', self.stylusPivotCalibration)
        self.ui.USCalibrationButton.connect('clicked(bool)',
                                            self.USCalibration)
        self.ui.initialCTRegistrationButton.connect('clicked(bool)',
                                                    self.initialCTRegistration)
        self.ui.placeToCTToReferenceFiducialButton.connect(
            'clicked(bool)', self.placeToCTToReferenceFiducial)
        self.ui.freezeUltrasoundButton.connect('clicked(bool)',
                                               self.onFreezeUltrasound)

        # Default widget settings
        self.toolCalibrationTimer = qt.QTimer()
        self.toolCalibrationTimer.setInterval(500)
        self.toolCalibrationTimer.connect('timeout()',
                                          self.toolCalibrationTimeout)

        self.ui.fromProbeToUSFiducialWidget.setCurrentNode(
            slicer.util.getFirstNodeByName(
                'FromProbeToUSFiducialNode',
                className='vtkMRMLMarkupsFiducialNode'))
        self.ui.fromProbeToUSFiducialWidget.setNodeColor(
            qt.QColor(207, 26, 0, 255))
        self.ui.toProbeToUSFiducialWidget.setCurrentNode(
            slicer.util.getFirstNodeByName(
                'ToProbeToUSFiducialNode',
                className='vtkMRMLMarkupsFiducialNode'))
        self.ui.toProbeToUSFiducialWidget.setNodeColor(
            qt.QColor(103, 0, 225, 255))

        self.ui.fromCTToReferenceFiducialWidget.setCurrentNode(
            slicer.util.getFirstNodeByName(
                'FromCTToReferenceFiducialNode',
                className='vtkMRMLMarkupsFiducialNode'))
        self.ui.fromCTToReferenceFiducialWidget.setNodeColor(
            qt.QColor(85, 255, 0, 255))
        self.ui.toCTToReferenceFiducialWidget.setCurrentNode(
            slicer.util.getFirstNodeByName(
                'ToCTToReferenceFiducialNode',
                className='vtkMRMLMarkupsFiducialNode'))
        self.ui.toCTToReferenceFiducialWidget.setNodeColor(
            qt.QColor(255, 170, 0, 255))

        # These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
        # (in the selected parameter node).
        self.ui.fromCTToReferenceFiducialWidget.connect(
            "currentNodeChanged(vtkMRMLNode*)",
            self.updateParameterNodeFromGUI)
        self.ui.toCTToReferenceFiducialWidget.connect(
            "currentNodeChanged(vtkMRMLNode*)",
            self.updateParameterNodeFromGUI)
        self.ui.fromProbeToUSFiducialWidget.connect(
            "currentNodeChanged(vtkMRMLNode*)",
            self.updateParameterNodeFromGUI)
        self.ui.toProbeToUSFiducialWidget.connect(
            "currentNodeChanged(vtkMRMLNode*)",
            self.updateParameterNodeFromGUI)

        # Initial GUI update
        self.updateGUIFromParameterNode()
예제 #27
0
class BeamstopDistanceBrick(BlissWidget):
    CONNECTED_COLOR = widget_colors.LIGHT_GREEN
    CHANGED_COLOR = qt.QColor(255, 165, 0)
    OUTLIMITS_COLOR = widget_colors.LIGHT_RED

    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.addProperty('mnemonic', 'string', '')
        self.addProperty('icons', 'string', '')
        self.addProperty('formatString', 'formatString', '###.##')

        self.beamstop_hwobj = None

        self.top_gbox = qt.QHGroupBox('Beamstop distance', self)
        self.top_gbox.setInsideMargin(4)
        self.top_gbox.setInsideSpacing(2)

        self.params_widget = qt.QWidget(self.top_gbox)
        qt.QGridLayout(self.params_widget, 2, 3, 0, 2)

        label1 = qt.QLabel("Current:", self.params_widget)
        label1.setFixedWidth(70)
        self.params_widget.layout().addWidget(label1, 0, 0)

        self.current_position_ledit = qt.QLineEdit(self.params_widget)
        self.current_position_ledit.setReadOnly(True)
        self.params_widget.layout().addWidget(self.current_position_ledit, 0,
                                              1)

        label2 = qt.QLabel("Set to:", self.params_widget)
        label2.setFixedWidth(70)
        self.params_widget.layout().addWidget(label2, 1, 0)

        self.new_position_ledit = qt.QLineEdit(self.params_widget)
        self.new_position_ledit.setAlignment(qt.QWidget.AlignRight)
        self.params_widget.layout().addWidget(self.new_position_ledit, 1, 1)
        self.new_position_ledit.setValidator(qt.QDoubleValidator(self))
        self.new_position_ledit.setPaletteBackgroundColor(
            BeamstopDistanceBrick.CONNECTED_COLOR)

        qt.QObject.connect(self.new_position_ledit,
                           qt.SIGNAL('returnPressed()'), self.change_position)
        qt.QObject.connect(self.new_position_ledit,
                           qt.SIGNAL('textChanged(const QString &)'),
                           self.input_field_changed)

        self.instanceSynchronize("new_position_ledit")

        qt.QVBoxLayout(self)
        self.layout().addWidget(self.top_gbox)

    def propertyChanged(self, property, oldValue, newValue):
        if property == 'mnemonic':
            if self.beamstop_hwobj is not None:
                self.disconnect(self.beamstop_hwobj,
                                qt.PYSIGNAL('deviceReady'), self.connected)
                self.disconnect(self.beamstop_hwobj,
                                qt.PYSIGNAL('deviceNotReady'),
                                self.disconnected)
                self.disconnect(self.beamstop_hwobj,
                                qt.PYSIGNAL('beamstopDistanceChanged'),
                                self.beamstop_distance_changed)
            self.beamstop_hwobj = self.getHardwareObject(newValue)
            if self.beamstop_hwobj is not None:
                self.connect(self.beamstop_hwobj, qt.PYSIGNAL('deviceReady'),
                             self.connected)
                self.connect(self.beamstop_hwobj,
                             qt.PYSIGNAL('deviceNotReady'), self.disconnected)
                self.connect(self.beamstop_hwobj,
                             qt.PYSIGNAL('beamstopDistanceChanged'),
                             self.beamstop_distance_changed)
                if self.beamstop_hwobj.isReady():
                    self.connected()
                    self.beamstop_hwobj.update_values()
                else:
                    self.disconnected()
            else:
                self.disconnected()
        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    def input_field_changed(self, text):
        text = str(text)
        if text == "":
            self.new_position_ledit.setPaletteBackgroundColor(
                BeamstopDistanceBrick.CONNECTED_COLOR)
        else:
            try:
                val = float(text)
            except (TypeError, ValueError):
                widget_color = BeamstopDistanceBrick.OUTLIMITS_COLOR
            else:
                widget_color = BeamstopDistanceBrick.CHANGED_COLOR
                if self.beamstop_limits is not None:
                    if val < self.beamstop_limits[
                            0] or val > self.beamstop_limits[1]:
                        widget_color = BeamstopDistanceBrick.OUTLIMITS_COLOR

            self.new_position_ledit.setPaletteBackgroundColor(widget_color)

    def change_position(self):
        try:
            val = float(str(self.new_position_ledit.text()))
        except (ValueError, TypeError):
            return

        if self.beamstop_limits is not None:
            if val < self.beamstop_limits[0] or val > self.beamstop_limits[1]:
                return

        self.beamstop_hwobj.set_positions(val)
        self.new_position_ledit.setText('')

    def connected(self):
        self.beamstop_limits = (0, 200)
        self.top_gbox.setEnabled(True)

    def disconnected(self):
        self.beamstop_limits = None
        self.top_gbox.setEnabled(False)

    def beamstop_distance_changed(self, value):
        if value is None:
            return
        if value < 0:
            self.current_position_ledit.setText("")
        else:
            value_str = self['formatString'] % value
            self.current_position_ledit.setText('%s mm' % value_str)
예제 #28
0
    def section_SimpleMarkupsWidget(self):
        self.delayDisplay("Test SimpleMarkupsWidget", self.delayMs)

        simpleMarkupsWidget = slicer.qSlicerSimpleMarkupsWidget()
        nodeSelector = slicer.util.findChildren(simpleMarkupsWidget,
                                                "MarkupsNodeComboBox")[0]
        self.assertIsNone(simpleMarkupsWidget.interactionNode())
        simpleMarkupsWidget.setMRMLScene(slicer.mrmlScene)
        simpleMarkupsWidget.show()

        placeWidget = simpleMarkupsWidget.markupsPlaceWidget()
        self.assertIsNotNone(placeWidget)

        simpleMarkupsWidget.setCurrentNode(None)
        simpleMarkupsWidget.enterPlaceModeOnNodeChange = False
        placeWidget.placeModeEnabled = False
        nodeSelector.setCurrentNode(self.markupsNode1)
        self.assertFalse(placeWidget.placeModeEnabled)

        simpleMarkupsWidget.enterPlaceModeOnNodeChange = True
        nodeSelector.setCurrentNode(self.markupsNode2)
        self.assertTrue(placeWidget.placeModeEnabled)

        simpleMarkupsWidget.jumpToSliceEnabled = True
        self.assertTrue(simpleMarkupsWidget.jumpToSliceEnabled)
        simpleMarkupsWidget.jumpToSliceEnabled = False
        self.assertFalse(simpleMarkupsWidget.jumpToSliceEnabled)

        simpleMarkupsWidget.nodeSelectorVisible = False
        self.assertFalse(simpleMarkupsWidget.nodeSelectorVisible)
        simpleMarkupsWidget.nodeSelectorVisible = True
        self.assertTrue(simpleMarkupsWidget.nodeSelectorVisible)

        simpleMarkupsWidget.optionsVisible = False
        self.assertFalse(simpleMarkupsWidget.optionsVisible)
        simpleMarkupsWidget.optionsVisible = True
        self.assertTrue(simpleMarkupsWidget.optionsVisible)

        defaultColor = qt.QColor(0, 255, 0)
        simpleMarkupsWidget.defaultNodeColor = defaultColor
        self.assertEqual(simpleMarkupsWidget.defaultNodeColor, defaultColor)

        self.markupsNode3 = nodeSelector.addNode()
        displayNode3 = self.markupsNode3.GetDisplayNode()
        color3 = displayNode3.GetColor()
        self.assertEqual(color3[0] * 255, defaultColor.red())
        self.assertEqual(color3[1] * 255, defaultColor.green())
        self.assertEqual(color3[2] * 255, defaultColor.blue())

        numberOfFiducialsAdded = 5
        for i in range(numberOfFiducialsAdded):
            self.markupsLogic.AddFiducial()

        tableWidget = simpleMarkupsWidget.tableWidget()
        self.assertEqual(tableWidget.rowCount, numberOfFiducialsAdded)

        self.assertEqual(simpleMarkupsWidget.interactionNode(),
                         slicer.app.applicationLogic().GetInteractionNode())
        otherInteractionNode = slicer.vtkMRMLInteractionNode()
        otherInteractionNode.SetSingletonOff()
        slicer.mrmlScene.AddNode(otherInteractionNode)
        simpleMarkupsWidget.setInteractionNode(otherInteractionNode)
        self.assertEqual(simpleMarkupsWidget.interactionNode(),
                         otherInteractionNode)
예제 #29
0
    def editMarkups(self, selectOption, fiducialsNode, curveNode, viewNode):

        layoutManager = slicer.app.layoutManager()
        threeDWidget = layoutManager.viewWidget(viewNode)
        threeDView = threeDWidget.threeDView()
        aspectRatio = threeDWidget.width / threeDWidget.height
        className = "vtkMRMLMarkupsDisplayableManager"
        markupsDisplayableManager = threeDView.displayableManagerByClassName(
            className)
        fiducialsWidget = markupsDisplayableManager.GetWidget(
            fiducialsNode.GetDisplayNode())
        fiducialsRepresentation = fiducialsWidget.GetRepresentation()

        cameraNode = slicer.modules.cameras.logic().GetViewActiveCameraNode(
            viewNode)
        camera = cameraNode.GetCamera()
        raswToXYZW = vtk.vtkMatrix4x4()
        modelView = camera.GetModelViewTransformMatrix()
        projection = camera.GetProjectionTransformMatrix(
            aspectRatio, 1, 100)  # near/far are arbitrary
        raswToXYZW.Multiply4x4(projection, modelView, raswToXYZW)

        def rasToColumnRow(ras):
            rasw = *ras, 1
            xyzw = raswToXYZW.MultiplyPoint(rasw)
            x, y = [xyzw[0], xyzw[1]]
            if viewNode.GetRenderMode() == viewNode.Perspective:
                x, y = [x / xyzw[3], y / xyzw[3]]
            column = (x + 1) / 2 * threeDWidget.width
            row = (1 - (y + 1) / 2) * threeDWidget.height
            return column, row

        selectionPolygon = qt.QPolygonF()
        for index in range(curveNode.GetNumberOfControlPoints()):
            ras = [0] * 3
            curveNode.GetNthControlPointPositionWorld(index, ras)
            column, row = rasToColumnRow(ras)
            point = qt.QPointF(column, row)
            selectionPolygon.push_back(point)

        pickImage = qt.QImage(threeDWidget.width, threeDWidget.height,
                              qt.QImage().Format_ARGB32)
        backgroundColor = qt.QColor("#ffffffff")
        pickImage.fill(backgroundColor)

        painter = qt.QPainter()
        painter.begin(pickImage)
        painterPath = qt.QPainterPath()
        painterPath.addPolygon(selectionPolygon)
        brush = qt.QBrush(qt.Qt.SolidPattern)
        painter.setBrush(brush)
        painter.drawPath(painterPath)
        painter.end()

        debugging = False
        if debugging:
            pixmap = qt.QPixmap().fromImage(pickImage)
            slicer.modules.label = qt.QLabel()
            slicer.modules.label.setPixmap(pixmap)
            slicer.modules.label.show()

        visibleCount = 0
        pickedCount = 0
        for index in range(fiducialsNode.GetNumberOfControlPoints()):
            pointVisible = fiducialsRepresentation.GetNthControlPointViewVisibility(
                index)
            if pointVisible:
                visibleCount += 1
            ras = [0] * 3
            fiducialsNode.GetNthControlPointPositionWorld(index, ras)
            column, row = rasToColumnRow(ras)
            if (column >= 0 and column < pickImage.width and row >= 0
                    and row < pickImage.height):
                pickColor = pickImage.pixelColor(column, row)
                picked = (pickColor != backgroundColor)
                if picked:
                    pickedCount += 1
                if selectOption == "set":
                    if pointVisible:
                        fiducialsNode.SetNthControlPointSelected(index, picked)
                    else:
                        fiducialsNode.SetNthControlPointSelected(index, False)
                elif selectOption == "add":
                    if picked and pointVisible:
                        fiducialsNode.SetNthControlPointSelected(index, True)
                elif selectOption == "unset":
                    if picked and pointVisible:
                        fiducialsNode.SetNthControlPointSelected(index, False)
                else:
                    logging.error(f"Unknown selectOption {selectOption}")
예제 #30
0
    def updateStructures(self, caller=None, event=None):
        """re-build the Structures frame
    - optional caller and event ignored (for use as vtk observer callback)
    """

        if slicer.mrmlScene.IsBatchProcessing():
            return

        if self.mergeButton.destroyed():
            """ TODO: here the python class still exists but the
      Qt widgets are gone - need to figure out when to remove observers
      and free python code - probably the destroyed() signal.
      """
            self.cleanup()
            return

        #self.mergeSelector.setDisabled(not self.master)

        # reset to a fresh model
        self.structures = qt.QStandardItemModel()
        self.structuresView.setModel(self.structures)

        # if no merge volume exists, disable everything - else enable
        merge = self.merge

        self.addStructureButton.setDisabled(not merge)
        self.deleteStructuresButton.setDisabled(not merge)
        self.deleteSelectedStructureButton.setDisabled(not merge)
        self.mergeButton.setDisabled(not merge)
        self.splitButton.setDisabled(not merge)
        self.mergeAndBuildButton.setDisabled(not merge)
        self.replaceModels.setDisabled(not merge)
        if self.mergeValidCommand:
            # will be passed current
            self.mergeValidCommand(merge)

        if not merge:
            return

        colorNode = merge.GetDisplayNode().GetColorNode()
        lut = colorNode.GetLookupTable()

        masterName = self.master.GetName()
        volumeNodes = self.structureVolumes()
        for vNode in volumeNodes:
            vName = vNode.GetName()
            # figure out what name it is
            # - account for the fact that sometimes a number will be added to the end of the name
            start = 1 + len(masterName)
            end = vName.rfind(self.mergeVolumePostfix)
            structureName = vName[start:end]
            structureIndex = colorNode.GetColorIndexByName(structureName)
            structureColor = lut.GetTableValue(structureIndex)[0:3]
            color = qt.QColor()
            color.setRgb(structureColor[0] * 255, structureColor[1] * 255,
                         structureColor[2] * 255)

            # label index
            item = qt.QStandardItem()
            item.setEditable(False)
            item.setText("%03d" % int(structureIndex))
            self.structures.setItem(self.row, 0, item)

            # label color
            item = qt.QStandardItem()
            item.setEditable(False)
            item.setData(color, 1)
            self.structures.setItem(self.row, 1, item)

            # structure name
            item = qt.QStandardItem()
            item.setEditable(False)
            item.setText(structureName)
            self.structures.setItem(self.row, 2, item)

            # volumeName name
            item = qt.QStandardItem()
            item.setEditable(False)
            item.setText(vName)
            self.structures.setItem(self.row, 3, item)

            # sort order
            item = qt.QStandardItem()
            item.setEditable(True)
            item.setText("")
            self.structures.setItem(self.row, 4, item)

            self.row += 1

        for i in range(5):
            self.structuresView.resizeColumnToContents(i)

        self.structures.setHeaderData(0, 1, "Number")
        self.structures.setHeaderData(1, 1, "Color")
        self.structures.setHeaderData(2, 1, "Name")
        self.structures.setHeaderData(3, 1, "Label Volume")
        self.structures.setHeaderData(4, 1, "Order")
        self.structuresView.setModel(self.structures)
        self.structuresView.connect("activated(QModelIndex)",
                                    self.onStructuresClicked)
        self.structuresView.setProperty(
            'SH_ItemView_ActivateItemOnSingleClick', 1)

        self.structureLabelNames = []
        rows = self.structures.rowCount()
        for row in xrange(rows):
            self.structureLabelNames.append(
                self.structures.item(row, 2).text())