def setCropButtonClicked(self): vol = self.inputSelector.currentNode() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) mainWindow = slicer.util.mainWindow() mainWindow.moduleSelector().selectModule('CropVolume') cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode() cropVolumeNode.SetScene(slicer.mrmlScene) cropVolumeNode.SetName('ChangeTracker_CropVolume_node') cropVolumeNode.SetIsotropicResampling(True) cropVolumeNode.SetSpacingScalingConst(0.5) slicer.mrmlScene.AddNode(cropVolumeNode) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic = slicer.modules.cropvolume.logic() cropVolumeLogic.Apply(cropVolumeNode) #self.delayDisplay('First test passed, closing the scene and running again') # test clearing the scene and running a second time slicer.mrmlScene.Clear(0) # the module will re-add the removed parameters node mainWindow.moduleSelector().selectModule('Transforms') mainWindow.moduleSelector().selectModule('CropVolume') cropVolumeNode = slicer.mrmlScene.GetNodeByID( 'vtkMRMLCropVolumeParametersNode1') #vol = SampleData.downloadSample("MRHead") roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic.Apply(cropVolumeNode)
def createUserInterface( self ): ''' ''' self.__layout = super( EMSegmentQuickStep4, self ).createUserInterface() # deactivate next button since it is the last step self.buttonBoxHints = self.NextButtonDisabled # the ROI parameters voiGroupBox = qt.QGroupBox() voiGroupBox.setTitle( 'Define VOI' ) self.__layout.addWidget( voiGroupBox ) voiGroupBoxLayout = qt.QFormLayout( voiGroupBox ) self.__roiWidget = slicer.modulewidget.qMRMLAnnotationROIWidget() self.__roiWidget.toolTip = 'Select a sub-volume for segmentation. Then, only the selected area will be segmented. By default, the complete volume will be segmented.' voiGroupBoxLayout.addWidget( self.__roiWidget ) self.__roi = slicer.vtkMRMLAnnotationROINode() self.__roi.SetXYZ( [0, 0, 0] ); self.__roi.SetRadiusXYZ( 100, 100, 100 ); self.__roi.Initialize( slicer.mrmlScene ) self.__roi.AddObserver( vtk.vtkCommand.ModifiedEvent, self.updateMRMLFromROI ) self.__roiWidget.setMRMLAnnotationROINode( self.__roi ) self.__roiWidget.setDisplayClippingBox( 0 )
def test_CropVolumeSelfTest(self): """ Replicate the crashe in issue 3117 """ print("Running CropVolumeSelfTest Test case:") vol = self.downloadMRHead() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) mainWindow = slicer.util.mainWindow() mainWindow.moduleSelector().selectModule('CropVolume') cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode() cropVolumeNode.SetScene(slicer.mrmlScene) cropVolumeNode.SetName('ChangeTracker_CropVolume_node') cropVolumeNode.SetIsotropicResampling(True) cropVolumeNode.SetSpacingScalingConst(0.5) slicer.mrmlScene.AddNode(cropVolumeNode) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic = slicer.modules.cropvolume.logic() cropVolumeLogic.Apply(cropVolumeNode) slicer.mrmlScene.RemoveNode(roi) self.delayDisplay('Test passed')
def test_VolumeClipWithRoi1(self): # Download MRHead from sample data import SampleData sampleDataLogic = SampleData.SampleDataLogic() self.delayDisplay("Getting MR Head Volume") mrHeadVolume = sampleDataLogic.downloadMRHead() # Create output volume outputVolume = slicer.vtkMRMLScalarVolumeNode() slicer.mrmlScene.AddNode(outputVolume) # Create clipping ROI roiNode = slicer.vtkMRMLAnnotationROINode() roiNode.SetXYZ(36, 17, -10) roiNode.SetRadiusXYZ(25, 40, 65) roiNode.Initialize(slicer.mrmlScene) fillValue = 17 clipOutsideSurface = True logic = VolumeClipWithRoiLogic() logic.clipVolumeWithRoi(roiNode, mrHeadVolume, fillValue, clipOutsideSurface, outputVolume) self.delayDisplay("Test passed!")
def test_ROISegmentation(self, samplevolume, labelmapSelector): roiSNode = slicer.vtkMRMLAnnotationROINode() roiBNode = slicer.vtkMRMLAnnotationROINode() roiSNode.SetXYZ(-5.12, 26.72, 27.54) roiSNode.SetRadiusXYZ(7.87, 7.87, 9.84) roiBNode.SetXYZ(-3.93, 26.71, 28.72) roiBNode.SetRadiusXYZ(20.07, 18.88, 19.67) roiBNode.Initialize(slicer.mrmlScene) roiBNode.Initialize(slicer.mrmlScene) logic = ROISegmentation1Logic() logic.roiSegment(samplevolume, roiSNode, roiBNode, labelmapSelector) self.delayDisplay("test passed.")
def test_CropVolumeSelfTest(self): """ Replicate the crashe in issue 3117 """ print("Running CropVolumeSelfTest Test case:") vol = self.downloadMRHead() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) mainWindow = slicer.util.mainWindow() mainWindow.moduleSelector().selectModule('CropVolume') cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode() cropVolumeNode.SetScene(slicer.mrmlScene) cropVolumeNode.SetName('ChangeTracker_CropVolume_node') cropVolumeNode.SetIsotropicResampling(True) cropVolumeNode.SetSpacingScalingConst(0.5) slicer.mrmlScene.AddNode(cropVolumeNode) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic = slicer.modules.cropvolume.logic() cropVolumeLogic.Apply(cropVolumeNode) self.delayDisplay( 'First test passed, closing the scene and running again') # test clearing the scene and running a second time slicer.mrmlScene.Clear(0) # the module will re-add the removed parameters node cropVolumeNode = slicer.mrmlScene.GetNodeByID( 'vtkMRMLCropVolumeParametersNode1') vol = self.downloadMRHead() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic.Apply(cropVolumeNode) self.delayDisplay('Test passed')
def updateWidgetFromParameterNode(self, parameterNode): roiNode = parameterNode.GetNodeReference('roiNode') if not roiNode: roiNode = slicer.vtkMRMLAnnotationROINode() roiNode.Initialize(slicer.mrmlScene) parameterNode.SetNodeReferenceID('roiNode', roiNode.GetID()) roiNode.SetRadiusXYZ(50, 50, 100) # initialize slightly off-center, as spine is usually towards posterior side of the image roiNode.SetXYZ(0, -50, 0) self.__roiSelector.setCurrentNode(roiNode) self.onROIChanged()
def test_CropVolumeSelfTest(self): """ Replicate the crashe in issue 3117 """ print("Running CropVolumeSelfTest Test case:") vol = self.downloadMRHead() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) mainWindow = slicer.util.mainWindow() mainWindow.moduleSelector().selectModule('CropVolume') cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode() cropVolumeNode.SetScene(slicer.mrmlScene) cropVolumeNode.SetName('ChangeTracker_CropVolume_node') cropVolumeNode.SetIsotropicResampling(True) cropVolumeNode.SetSpacingScalingConst(0.5) slicer.mrmlScene.AddNode(cropVolumeNode) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic = slicer.modules.cropvolume.logic() cropVolumeLogic.Apply(cropVolumeNode) self.delayDisplay('First test passed, closing the scene and running again') # test clearing the scene and running a second time slicer.mrmlScene.Clear(0) # the module will re-add the removed parameters node cropVolumeNode = slicer.mrmlScene.GetNodeByID('vtkMRMLCropVolumeParametersNode1') vol = self.downloadMRHead() roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) cropVolumeNode.SetInputVolumeNodeID(vol.GetID()) cropVolumeNode.SetROINodeID(roi.GetID()) cropVolumeLogic.Apply(cropVolumeNode) self.delayDisplay('Test passed')
def updateWidgetFromParameterNode(self, parameterNode): roiNodeID = parameterNode.GetParameter('roiNodeID') if roiNodeID != '': self.__roi = slicer.mrmlScene.GetNodeByID(roiNodeID) self.__roiSelector.setCurrentNode(Helper.getNodeByID(self.__roi.GetID())) else: roi = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roi) parameterNode.SetParameter('roiNodeID', roi.GetID()) self.__roiSelector.setCurrentNode(roi) self.onROIChanged()
def updateWidgetFromParameterNode(self, parameterNode): roiNodeID = parameterNode.GetParameter("roiNodeID") if roiNodeID != "": self.__roi = slicer.mrmlScene.GetNodeByID(roiNodeID) self.__roiSelector.setCurrentNode(Helper.getNodeByID(self.__roi.GetID())) else: roi = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roi) parameterNode.SetParameter("roiNodeID", roi.GetID()) self.__roiSelector.setCurrentNode(roi) self.onROIChanged()
def updateWidgetFromParameterNode(self, parameterNode): roiNodeID = parameterNode.GetParameter('roiNodeID') if roiNodeID != '': self.__roi = slicer.mrmlScene.GetNodeByID(roiNodeID) self.__roiSelector.setCurrentNode(Helper.getNodeByID(self.__roi.GetID())) else: roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) parameterNode.SetParameter('roiNodeID', roi.GetID()) self.__roiSelector.setCurrentNode(roi) self.onROIChanged()
def updateWidgetFromParameterNode(self, parameterNode): """ Effectively creates the ROI node upon entry, and then uses onROIChanged to calculate its intial position. """ roiNodeID = parameterNode.GetParameter('roiNodeID') if roiNodeID != '': self.__roi = slicer.mrmlScene.GetNodeByID(roiNodeID) self.__roiSelector.setCurrentNode(Helper.getNodeByID(self.__roi.GetID())) else: roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) parameterNode.SetParameter('roiNodeID', roi.GetID()) self.__roiSelector.setCurrentNode(roi) self.onROIChanged()
def updateWidgetFromParameterNode(self, parameterNode): roiNodeID = parameterNode.GetParameter('roiNodeID') if roiNodeID != '': self.__roi = slicer.mrmlScene.GetNodeByID(roiNodeID) self.__roiSelector.setCurrentNode(Helper.getNodeByID(self.__roi.GetID())) else: roi = slicer.vtkMRMLAnnotationROINode() roi.Initialize(slicer.mrmlScene) parameterNode.SetParameter('roiNodeID', roi.GetID()) self.__roiSelector.setCurrentNode(roi) baselineROIVolume = Helper.getNodeByID(parameterNode.GetParameter('baselineVolumeID')) baselineROIRange = baselineROIVolume.GetImageData().GetScalarRange() self.__roiVolume = baselineROIVolume self.__corticalRange.minimum = -1000 self.__corticalRange.maximum = baselineROIRange[1] vl = slicer.modules.volumes.logic() self.__corticalNode = vl.CreateAndAddLabelVolume(slicer.mrmlScene, baselineROIVolume, 'corticalROI_segmentation') #self.__cancellousNode = vl.CreateAndAddLabelVolume(slicer.mrmlScene, baselineROIVolume, 'cancellousROI_segmentation') Helper.SetLabelVolume(None) labelsColorNode = slicer.modules.colors.logic().GetColorTableNodeID(10) self.__corticalNode.GetDisplayNode().SetAndObserveColorNodeID(labelsColorNode) Helper.SetLabelVolume(self.__corticalNode.GetID()) thresholdRange = str(0.5*(baselineROIRange[0]+baselineROIRange[1]))+','+str(baselineROIRange[1]) if thresholdRange != '': rangeArray = string.split(thresholdRange, ',') #self.__corticalRange.minimumValue = float(rangeArray[0]) self.__corticalRange.minimumValue = 150 self.__corticalRange.maximumValue = float(rangeArray[1]) #self.__cancellousRange.minimumValue = float(rangeArray[0]) #self.__cancellousRange.maximumValue = float(rangeArray[1]) else: Helper.Error('Unexpected parameter values!') #self.onCancellousChanged() self.onCorticalChanged()
def refineLandmark(self, state): """Refine the specified landmark""" # Refine landmark, or if none, do nothing # Crop images around the fiducial # Affine registration of the cropped images # Transform the fiducial using the transformation # # No need to take into account the current transformation because landmarks are in World RAS timing = False if self.VerboseMode == "Verbose": timing = True if state.fixed == None or state.moving == None or state.fixedFiducials == None or state.movingFiducials == None or state.currentLandmarkName == None: print "Cannot refine landmarks. Images or landmarks not selected." return print("Refining landmark " + state.currentLandmarkName) + " using " + self.name start = time.time() volumes = (state.fixed, state.moving) (fixedVolume, movingVolume) = volumes slicer.mrmlScene.StartState(slicer.mrmlScene.BatchProcessState) landmarks = state.logic.landmarksForVolumes(volumes) cvpn = slicer.vtkMRMLCropVolumeParametersNode() cvpn.SetInterpolationMode(1) cvpn.SetVoxelBased(1) fixedPoint = [ 0, ] * 3 movingPoint = [ 0, ] * 3 (fixedFiducial, movingFiducial) = landmarks[state.currentLandmarkName] (fixedList, fixedIndex) = fixedFiducial (movingList, movingIndex) = movingFiducial # define an roi for the fixed if timing: roiStart = time.time() roiFixed = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roiFixed) fixedList.GetNthFiducialPosition(fixedIndex, fixedPoint) roiFixed.SetDisplayVisibility(0) roiFixed.SelectableOff() roiFixed.SetXYZ(fixedPoint) roiFixed.SetRadiusXYZ(30, 30, 30) # crop the fixed. note we hide the display node temporarily to avoid the automated # window level calculation on temporary nodes created by cloning cvpn.SetROINodeID(roiFixed.GetID()) cvpn.SetInputVolumeNodeID(fixedVolume.GetID()) fixedDisplayNode = fixedVolume.GetDisplayNode() fixedVolume.SetAndObserveDisplayNodeID( 'This is not a valid DisplayNode ID') if timing: roiEnd = time.time() if timing: cropStart = time.time() state.logic.cropLogic.Apply(cvpn) if timing: cropEnd = time.time() croppedFixedVolume = slicer.mrmlScene.GetNodeByID( cvpn.GetOutputVolumeNodeID()) fixedVolume.SetAndObserveDisplayNodeID(fixedDisplayNode.GetID()) # define an roi for the moving if timing: roi2Start = time.time() roiMoving = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roiMoving) movingList.GetNthFiducialPosition(movingIndex, movingPoint) roiMoving.SetDisplayVisibility(0) roiMoving.SelectableOff() roiMoving.SetXYZ(movingPoint) if self.LocalBRAINSFitMode == "Small": roiMoving.SetRadiusXYZ(45, 45, 45) else: roiMoving.SetRadiusXYZ(60, 60, 60) # crop the moving. note we hide the display node temporarily to avoid the automated # window level calculation on temporary nodes created by cloning cvpn.SetROINodeID(roiMoving.GetID()) cvpn.SetInputVolumeNodeID(movingVolume.GetID()) movingDisplayNode = movingVolume.GetDisplayNode() movingVolume.SetAndObserveDisplayNodeID( 'This is not a valid DisplayNode ID') if timing: roi2End = time.time() if timing: crop2Start = time.time() state.logic.cropLogic.Apply(cvpn) if timing: crop2End = time.time() croppedMovingVolume = slicer.mrmlScene.GetNodeByID( cvpn.GetOutputVolumeNodeID()) movingVolume.SetAndObserveDisplayNodeID(movingDisplayNode.GetID()) if timing: print 'Time to set up fixed ROI was ' + str(roiEnd - roiStart) + ' seconds' if timing: print 'Time to set up moving ROI was ' + str( roi2End - roi2Start) + ' seconds' if timing: print 'Time to crop fixed volume ' + str(cropEnd - cropStart) + ' seconds' if timing: print 'Time to crop moving volume ' + str(crop2End - crop2Start) + ' seconds' # transform = slicer.vtkMRMLLinearTransformNode() slicer.mrmlScene.AddNode(transform) matrix = vtk.vtkMatrix4x4() # define the registration parameters minPixelSpacing = min(croppedFixedVolume.GetSpacing()) parameters = {} parameters['fixedVolume'] = croppedFixedVolume.GetID() parameters['movingVolume'] = croppedMovingVolume.GetID() parameters['linearTransform'] = transform.GetID() parameters['useRigid'] = True parameters['initializeTransformMode'] = 'useGeometryAlign' parameters['samplingPercentage'] = 0.2 parameters['minimumStepLength'] = 0.1 * minPixelSpacing parameters['maximumStepLength'] = minPixelSpacing # run the registration if timing: regStart = time.time() slicer.cli.run(slicer.modules.brainsfit, None, parameters, wait_for_completion=True) if timing: regEnd = time.time() if timing: print 'Time for local registration ' + str(regEnd - regStart) + ' seconds' # apply the local transform to the landmark #print transform if timing: resultStart = time.time() transform.GetMatrixTransformToWorld(matrix) matrix.Invert() tp = [ 0, ] * 4 tp = matrix.MultiplyPoint(fixedPoint + [ 1, ]) #print fixedPoint, movingPoint, tp[:3] movingList.SetNthFiducialPosition(movingIndex, tp[0], tp[1], tp[2]) if timing: resultEnd = time.time() if timing: print 'Time for transforming landmark was ' + str( resultEnd - resultStart) + ' seconds' # clean up cropped volmes, need to reset the foreground/background display before we delete it if timing: cleanUpStart = time.time() slicer.mrmlScene.RemoveNode(croppedFixedVolume) slicer.mrmlScene.RemoveNode(croppedMovingVolume) slicer.mrmlScene.RemoveNode(roiFixed) slicer.mrmlScene.RemoveNode(roiMoving) slicer.mrmlScene.RemoveNode(transform) roiFixed = None roiMoving = None transform = None matrix = None if timing: cleanUpEnd = time.time() if timing: print 'Cleanup took ' + str(cleanUpEnd - cleanUpStart) + ' seconds' end = time.time() print 'Refined landmark ' + state.currentLandmarkName + ' in ' + str( end - start) + ' seconds' slicer.mrmlScene.EndState(slicer.mrmlScene.BatchProcessState)
def createUserInterface(self): ''' ''' self.__layout = super(EMSegmentDefineMiscParametersStep, self).createUserInterface() # deactivate next button since it is the last step self.buttonBoxHints = self.NextButtonDisabled # the ROI parameters voiGroupBox = qt.QGroupBox() voiGroupBox.setTitle('Define VOI') self.__layout.addWidget(voiGroupBox) voiGroupBoxLayout = qt.QFormLayout(voiGroupBox) self.__roiWidget = slicer.modulewidget.qMRMLAnnotationROIWidget() self.__roiWidget.toolTip = 'Select a sub-volume for segmentation. Then, only the selected area will be segmented. By default, the complete volume will be segmented.' voiGroupBoxLayout.addWidget(self.__roiWidget) self.__roi = slicer.vtkMRMLAnnotationROINode() self.__roi.SetXYZ([0, 0, 0]) self.__roi.SetRadiusXYZ(100, 100, 100) self.__roi.Initialize(slicer.mrmlScene) # since revision 21159 taken out SetVisibility was Replaced with SetDisplayVisibility # however when setting it I got a message that int values was not correct # self.__roi.SetDisplayVisibility( 0 ) self.__roi.AddObserver(vtk.vtkCommand.ModifiedEvent, self.updateMRMLFromROI) self.__roiWidget.setMRMLAnnotationROINode(self.__roi) self.__roiWidget.setDisplayClippingBox(0) # # save groupbox # saveGroupBox = qt.QGroupBox() saveGroupBox.setTitle('Save') self.__layout.addWidget(saveGroupBox) saveGroupBoxLayout = qt.QFormLayout(saveGroupBox) self.__saveButton = qt.QPushButton('Create') self.__saveButton.toolTip = 'Create a template file which can be shared and used to re-apply the configured task.' saveGroupBoxLayout.addRow("Create Template File:", self.__saveButton) self.__saveButton.connect('clicked()', self.onSaveButtonClicked) self.__saveIntermediateResultsCheckBox = qt.QCheckBox() self.__saveIntermediateResultsCheckBox.toolTip = 'Toggle to save intermediate results as well.' saveGroupBoxLayout.addRow("Save Intermediate Results:", self.__saveIntermediateResultsCheckBox) self.__saveIntermediateResultsCheckBox.connect('stateChanged(int)', self.propagateToMRML) self.__selectDirectoryButton = qt.QPushButton('Select') self.__selectDirectoryButton.toolTip = 'Select a directory to save intermediate results, if selected.' saveGroupBoxLayout.addRow("Select Intermediate Directory:", self.__selectDirectoryButton) self.__selectDirectoryButton.connect( 'clicked()', self.onSelectDirectoryButtonClicked) # # post processing groupbox # postProcessingGroupBox = qt.QGroupBox() postProcessingGroupBox.setTitle('Postprocessing') self.__layout.addWidget(postProcessingGroupBox) postProcessingGroupBoxLayout = qt.QFormLayout(postProcessingGroupBox) self.__subparcellationCheckBox = qt.QCheckBox() self.__subparcellationCheckBox.toolTip = 'Enable subpacellation.' postProcessingGroupBoxLayout.addRow("Subparcellation enabled:", self.__subparcellationCheckBox) self.__subparcellationCheckBox.connect('stateChanged(int)', self.propagateToMRML) self.__minimumIslandSizeSpinBox = qt.QSpinBox() self.__minimumIslandSizeSpinBox.toolTip = 'Configure the minimum island size.' self.__minimumIslandSizeSpinBox.minimum = 0 self.__minimumIslandSizeSpinBox.maximum = 200 self.__minimumIslandSizeSpinBox.singleStep = 1 postProcessingGroupBoxLayout.addRow("Minimum island size:", self.__minimumIslandSizeSpinBox) self.__minimumIslandSizeSpinBox.connect('stateChanged(int)', self.propagateToMRML) self.__twoDIslandNeighborhoodCheckBox = qt.QCheckBox() self.__twoDIslandNeighborhoodCheckBox.toolTip = 'Enable 2D Island Neighborhood' postProcessingGroupBoxLayout.addRow( "2D Island Neighborhood:", self.__twoDIslandNeighborhoodCheckBox) self.__twoDIslandNeighborhoodCheckBox.connect('stateChanged(int)', self.propagateToMRML) # # Misc. groupbox # miscGroupBox = qt.QGroupBox() miscGroupBox.setTitle('Misc.') self.__layout.addWidget(miscGroupBox) miscGroupBoxLayout = qt.QFormLayout(miscGroupBox) self.__multithreadingCheckBox = qt.QCheckBox() self.__multithreadingCheckBox.toolTip = 'Enhance speed by using multiple threads.' miscGroupBoxLayout.addRow("Multi-threading enabled:", self.__multithreadingCheckBox) self.__multithreadingCheckBox.connect('stateChanged(int)', self.propagateToMRML)
def step2_3(self): '''Step 2: 5 - 10''' key = 'step2_3' # 5. Convert ex 2d contour to ex 3d contour slicer.util.loadVolume(os.path.join(self.nii_folder, 'ex_2d_contour.nii')) slicer.util.loadVolume(os.path.join(self.nii_folder, 'ex_3d.nii')) output = dict( warpImg( inImg=os.path.join(self.nii_folder, 'ex_2d_contour.nii'), refImg=os.path.join(self.nii_folder, '(ex_3d)_to_(ex_2d).nii'), outImg=os.path.join(self.nii_folder, 'ex_3d_contour_blocky.nii'), pixelT='uchar', tfmFile=os.path.join(self.tfm_folder, 'identity.tfm'), intplMode='NearestNeighbor', # US spelling labelMap=True)) # LabelMapSmoothing output.update( labelMapSmoothing(inImg=os.path.join(self.nii_folder, 'ex_3d_contour_blocky.nii'), outImg=os.path.join(self.nii_folder, 'ex_3d_contour.nii'), sigma=2)) slicer.mrmlScene.Clear(0) # 6. Crop ex 3d as a reference image slicer.util.loadVolume( os.path.join(self.nii_folder, '(ex_3d)_to_(ex_2d).nii')) selectModule(slicer.modules.cropvolume) # Create an Annotation ROI Node roiNode = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roiNode) # Create an output volume node outputNode = slicer.vtkMRMLScalarVolumeNode() slicer.mrmlScene.AddNode(outputNode) outputNode.SetName('(ex_3d)_to_(ex_2d)_cropped') # Set the parameters. Note that the positions of the # widgets might be dependent on the Slicer version w = slicer.modules.cropvolume.widgetRepresentation() w.children()[2].children()[5].setCurrentNode(roiNode) w.children()[2].children()[10].setCurrentNode(outputNode) # Manually adjust the ROI try: _ = input("Please adjust the cropping volume \n\ 1. Use the control points to crop ex_3d; \n\ 2. Click 'Apply' in the 'Crop Volume' module; \n\ 3. Press ENTER to continue. ") except: # In case of an EOF error (empty string) pass # print("Cropping the volume") # Simulate the click # w.findChildren('QPushButton', 'CropButton')[0].animateClick() print('*' * 20, 'Done', '*' * 20) # Save node ex_3d_cropped_path = os.path.join(self.nii_folder, 'ex_3d_cropped.nii') saved = slicer.util.saveNode(outputNode, ex_3d_cropped_path) if saved: output.update({ex_3d_cropped_path: True}) slicer.util.saveNode( roiNode, os.path.join(self.temp_folder, 'ex_3d_cropped_roi.acsv')) # To load the annotation node # slicer.util.loadAnnotationROI(os.path.join(self.temp_folder, 'ex_3d_cropped_roi.acsv')) selectModule(slicer.modules.pyregpipe) # 7. Filter in 3d # in_3d_log_path = os.path.join(self.nii_folder, 'in_3d_log.nii') # genLogMacro(infile=os.path.join(self.nii_folder, 'in_3d.nii'), # outfile=in_3d_log_path, # macroPath=os.path.join(self.script_folder, 'in_3d_log.imj')) # filterLoG(macro_path=os.path.join(self.script_folder, 'in_3d_log.imj'), # exe_path=self.imagej_path) # copyHeader(os.path.join(self.nii_folder, 'in_3d_log.nii'), # os.path.join(self.nii_folder, 'in_3d.nii'), # self.nii_folder, # self.temp_folder) # if os.path.exists(in_3d_log_path): # output.update({os.path.join(self.nii_folder, 'in_3d_log.nii'):True}) output.update( logFilter(inFile=os.path.join(self.nii_folder, 'in_3d.nii'), outFile=os.path.join(self.nii_folder, 'in_3d_log.nii'))) # 8. Filter ex 3d cropped # ex_3d_cropped_log_path = os.path.join(self.nii_folder, # 'ex_3d_cropped_log.nii') # genLogMacro(infile=os.path.join(self.nii_folder, 'ex_3d_cropped.nii'), # outfile=ex_3d_cropped_log_path, # macroPath=os.path.join(self.script_folder, 'ex_3d_log.imj')) # filterLoG(macro_path=os.path.join(self.script_folder, 'ex_3d_log.imj'), # exe_path=self.imagej_path) # copyHeader(os.path.join(self.nii_folder, 'ex_3d_cropped_log.nii'), # os.path.join(self.nii_folder, 'ex_3d_cropped.nii'), # self.nii_folder, # self.temp_folder) # if os.path.exists(ex_3d_cropped_log_path): # output.update({ex_3d_cropped_log_path: True}) output.update( logFilter(inFile=os.path.join(self.nii_folder, 'ex_3d_cropped.nii'), outFile=os.path.join(self.nii_folder, 'ex_3d_cropped_log.nii'))) # 9. Mask in 3d log with manual contour output.update( maskVolume(infile=os.path.join(self.nii_folder, 'in_3d_log.nii'), contFile=os.path.join(self.nii_folder, 'in_3d_contour.nii'), outFile=os.path.join(self.nii_folder, 'in_3d_log_masked.nii'), label=1)) # 10. mask ex 3d cropped log with the manual contour output.update( maskVolume(infile=os.path.join(self.nii_folder, 'ex_3d_cropped_log.nii'), contFile=os.path.join(self.nii_folder, 'ex_3d_contour.nii'), outFile=os.path.join(self.nii_folder, 'ex_3d_cropped_log_masked.nii'), label=1)) update(self, key, output)
def createUserInterface( self ): ''' ''' self.__layout = super( EMSegmentDefineMiscParametersStep, self ).createUserInterface() # deactivate next button since it is the last step self.buttonBoxHints = self.NextButtonDisabled # the ROI parameters voiGroupBox = qt.QGroupBox() voiGroupBox.setTitle( 'Define VOI' ) self.__layout.addWidget( voiGroupBox ) voiGroupBoxLayout = qt.QFormLayout( voiGroupBox ) self.__roiWidget = slicer.modulewidget.qMRMLAnnotationROIWidget() self.__roiWidget.toolTip = 'Select a sub-volume for segmentation. Then, only the selected area will be segmented. By default, the complete volume will be segmented.' voiGroupBoxLayout.addWidget( self.__roiWidget ) self.__roi = slicer.vtkMRMLAnnotationROINode() self.__roi.SetXYZ( [0, 0, 0] ); self.__roi.SetRadiusXYZ( 100, 100, 100 ) self.__roi.Initialize( slicer.mrmlScene ) # since revision 21159 taken out SetVisibility was Replaced with SetDisplayVisibility # however when setting it I got a message that int values was not correct # self.__roi.SetDisplayVisibility( 0 ) self.__roi.AddObserver( vtk.vtkCommand.ModifiedEvent, self.updateMRMLFromROI ) self.__roiWidget.setMRMLAnnotationROINode( self.__roi ) self.__roiWidget.setDisplayClippingBox( 0 ) # # save groupbox # saveGroupBox = qt.QGroupBox() saveGroupBox.setTitle( 'Save' ) self.__layout.addWidget( saveGroupBox ) saveGroupBoxLayout = qt.QFormLayout ( saveGroupBox ) self.__saveButton = qt.QPushButton( 'Create' ) self.__saveButton.toolTip = 'Create a template file which can be shared and used to re-apply the configured task.' saveGroupBoxLayout.addRow( "Create Template File:", self.__saveButton ) self.__saveButton.connect( 'clicked()', self.onSaveButtonClicked ) self.__saveIntermediateResultsCheckBox = qt.QCheckBox() self.__saveIntermediateResultsCheckBox.toolTip = 'Toggle to save intermediate results as well.' saveGroupBoxLayout.addRow( "Save Intermediate Results:", self.__saveIntermediateResultsCheckBox ) self.__saveIntermediateResultsCheckBox.connect( 'stateChanged(int)', self.propagateToMRML ) self.__selectDirectoryButton = qt.QPushButton( 'Select' ) self.__selectDirectoryButton.toolTip = 'Select a directory to save intermediate results, if selected.' saveGroupBoxLayout.addRow( "Select Intermediate Directory:", self.__selectDirectoryButton ) self.__selectDirectoryButton.connect( 'clicked()', self.onSelectDirectoryButtonClicked ) # # post processing groupbox # postProcessingGroupBox = qt.QGroupBox() postProcessingGroupBox.setTitle( 'Postprocessing' ) self.__layout.addWidget( postProcessingGroupBox ) postProcessingGroupBoxLayout = qt.QFormLayout( postProcessingGroupBox ) self.__subparcellationCheckBox = qt.QCheckBox() self.__subparcellationCheckBox.toolTip = 'Enable subpacellation.' postProcessingGroupBoxLayout.addRow( "Subparcellation enabled:", self.__subparcellationCheckBox ) self.__subparcellationCheckBox.connect( 'stateChanged(int)', self.propagateToMRML ) self.__minimumIslandSizeSpinBox = qt.QSpinBox() self.__minimumIslandSizeSpinBox.toolTip = 'Configure the minimum island size.' self.__minimumIslandSizeSpinBox.minimum = 0 self.__minimumIslandSizeSpinBox.maximum = 200 self.__minimumIslandSizeSpinBox.singleStep = 1 postProcessingGroupBoxLayout.addRow( "Minimum island size:", self.__minimumIslandSizeSpinBox ) self.__minimumIslandSizeSpinBox.connect( 'stateChanged(int)', self.propagateToMRML ) self.__twoDIslandNeighborhoodCheckBox = qt.QCheckBox() self.__twoDIslandNeighborhoodCheckBox.toolTip = 'Enable 2D Island Neighborhood' postProcessingGroupBoxLayout.addRow( "2D Island Neighborhood:", self.__twoDIslandNeighborhoodCheckBox ) self.__twoDIslandNeighborhoodCheckBox.connect( 'stateChanged(int)', self.propagateToMRML ) # # Misc. groupbox # miscGroupBox = qt.QGroupBox() miscGroupBox.setTitle( 'Misc.' ) self.__layout.addWidget( miscGroupBox ) miscGroupBoxLayout = qt.QFormLayout( miscGroupBox ) self.__multithreadingCheckBox = qt.QCheckBox() self.__multithreadingCheckBox.toolTip = 'Enhance speed by using multiple threads.' miscGroupBoxLayout.addRow( "Multi-threading enabled:", self.__multithreadingCheckBox ) self.__multithreadingCheckBox.connect( 'stateChanged(int)', self.propagateToMRML )
def refineLandmark(self, state): """Refine the specified landmark""" # Refine landmark, or if none, do nothing # Crop images around the fiducial # Affine registration of the cropped images # Transform the fiducial using the transformation # # No need to take into account the current transformation because landmarks are in World RAS timing = False if self.VerboseMode == "Verbose": timing = True if state.logic.cropLogic is None: print("Cannot refine landmarks. CropVolume module is not available.") if state.fixed == None or state.moving == None or state.fixedFiducials == None or state.movingFiducials == None or state.currentLandmarkName == None: print "Cannot refine landmarks. Images or landmarks not selected." return print ("Refining landmark " + state.currentLandmarkName) + " using " + self.name start = time.time() volumes = (state.fixed, state.moving) (fixedVolume, movingVolume) = volumes slicer.mrmlScene.StartState(slicer.mrmlScene.BatchProcessState) landmarks = state.logic.landmarksForVolumes(volumes) cvpn = slicer.vtkMRMLCropVolumeParametersNode() cvpn.SetInterpolationMode(1) cvpn.SetVoxelBased(1) fixedPoint = [0,]*3 movingPoint = [0,]*3 (fixedFiducial, movingFiducial) = landmarks[state.currentLandmarkName] (fixedList,fixedIndex) = fixedFiducial (movingList, movingIndex) = movingFiducial # define an roi for the fixed if timing: roiStart = time.time() roiFixed = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roiFixed) fixedList.GetNthFiducialPosition(fixedIndex,fixedPoint) roiFixed.SetDisplayVisibility(0) roiFixed.SelectableOff() roiFixed.SetXYZ(fixedPoint) roiFixed.SetRadiusXYZ(30, 30, 30) # crop the fixed. note we hide the display node temporarily to avoid the automated # window level calculation on temporary nodes created by cloning cvpn.SetROINodeID( roiFixed.GetID() ) cvpn.SetInputVolumeNodeID( fixedVolume.GetID() ) fixedDisplayNode = fixedVolume.GetDisplayNode() fixedVolume.SetAndObserveDisplayNodeID('This is not a valid DisplayNode ID') if timing: roiEnd = time.time() if timing: cropStart = time.time() state.logic.cropLogic.Apply( cvpn ) if timing: cropEnd = time.time() croppedFixedVolume = slicer.mrmlScene.GetNodeByID( cvpn.GetOutputVolumeNodeID() ) fixedVolume.SetAndObserveDisplayNodeID(fixedDisplayNode.GetID()) # define an roi for the moving if timing: roi2Start = time.time() roiMoving = slicer.vtkMRMLAnnotationROINode() slicer.mrmlScene.AddNode(roiMoving) movingList.GetNthFiducialPosition(movingIndex,movingPoint) roiMoving.SetDisplayVisibility(0) roiMoving.SelectableOff() roiMoving.SetXYZ(movingPoint) if self.LocalBRAINSFitMode == "Small": roiMoving.SetRadiusXYZ(45, 45, 45) else: roiMoving.SetRadiusXYZ(60, 60, 60) # crop the moving. note we hide the display node temporarily to avoid the automated # window level calculation on temporary nodes created by cloning cvpn.SetROINodeID( roiMoving.GetID() ) cvpn.SetInputVolumeNodeID( movingVolume.GetID() ) movingDisplayNode = movingVolume.GetDisplayNode() movingVolume.SetAndObserveDisplayNodeID('This is not a valid DisplayNode ID') if timing: roi2End = time.time() if timing: crop2Start = time.time() state.logic.cropLogic.Apply( cvpn ) if timing: crop2End = time.time() croppedMovingVolume = slicer.mrmlScene.GetNodeByID( cvpn.GetOutputVolumeNodeID() ) movingVolume.SetAndObserveDisplayNodeID(movingDisplayNode.GetID()) if timing: print 'Time to set up fixed ROI was ' + str(roiEnd - roiStart) + ' seconds' if timing: print 'Time to set up moving ROI was ' + str(roi2End - roi2Start) + ' seconds' if timing: print 'Time to crop fixed volume ' + str(cropEnd - cropStart) + ' seconds' if timing: print 'Time to crop moving volume ' + str(crop2End - crop2Start) + ' seconds' # transform = slicer.vtkMRMLLinearTransformNode() slicer.mrmlScene.AddNode(transform) matrix = vtk.vtkMatrix4x4() # define the registration parameters minPixelSpacing = min(croppedFixedVolume.GetSpacing()) parameters = {} parameters['fixedVolume'] = croppedFixedVolume.GetID() parameters['movingVolume'] = croppedMovingVolume.GetID() parameters['linearTransform'] = transform.GetID() parameters['useRigid'] = True parameters['initializeTransformMode'] = 'useGeometryAlign'; parameters['samplingPercentage'] = 0.2 parameters['minimumStepLength'] = 0.1 * minPixelSpacing parameters['maximumStepLength'] = minPixelSpacing # run the registration if timing: regStart = time.time() slicer.cli.run(slicer.modules.brainsfit, None, parameters, wait_for_completion=True) if timing: regEnd = time.time() if timing: print 'Time for local registration ' + str(regEnd - regStart) + ' seconds' # apply the local transform to the landmark #print transform if timing: resultStart = time.time() transform.GetMatrixTransformToWorld(matrix) matrix.Invert() tp = [0,]*4 tp = matrix.MultiplyPoint(fixedPoint + [1,]) #print fixedPoint, movingPoint, tp[:3] movingList.SetNthFiducialPosition(movingIndex, tp[0], tp[1], tp[2]) if timing: resultEnd = time.time() if timing: print 'Time for transforming landmark was ' + str(resultEnd - resultStart) + ' seconds' # clean up cropped volmes, need to reset the foreground/background display before we delete it if timing: cleanUpStart = time.time() slicer.mrmlScene.RemoveNode(croppedFixedVolume) slicer.mrmlScene.RemoveNode(croppedMovingVolume) slicer.mrmlScene.RemoveNode(roiFixed) slicer.mrmlScene.RemoveNode(roiMoving) slicer.mrmlScene.RemoveNode(transform) roiFixed = None roiMoving = None transform = None matrix = None if timing: cleanUpEnd = time.time() if timing: print 'Cleanup took ' + str(cleanUpEnd - cleanUpStart) + ' seconds' end = time.time() print 'Refined landmark ' + state.currentLandmarkName + ' in ' + str(end - start) + ' seconds' slicer.mrmlScene.EndState(slicer.mrmlScene.BatchProcessState)