Esempio n. 1
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 doStepProcessing(self):
        '''
    prepare roi image for the next step
    '''
        #crop scalar volume
        pNode = self.parameterNode()

        pNode.SetParameter('vertebra', self.vSelector.currentText)
        pNode.SetParameter('inst_length', self.iSelector.currentText)
        pNode.SetParameter('approach', self.aSelector.currentText)

        cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
        cropVolumeNode.SetScene(slicer.mrmlScene)
        cropVolumeNode.SetName('CropVolume_node')
        cropVolumeNode.SetIsotropicResampling(True)
        cropVolumeNode.SetSpacingScalingConst(0.5)
        slicer.mrmlScene.AddNode(cropVolumeNode)
        # TODO hide from MRML tree

        cropVolumeNode.SetInputVolumeNodeID(
            pNode.GetNodeReference('baselineVolume').GetID())
        cropVolumeNode.SetROINodeID(pNode.GetNodeReference('roiNode').GetID())
        # cropVolumeNode.SetAndObserveOutputVolumeNodeID(outputVolume.GetID())

        cropVolumeLogic = slicer.modules.cropvolume.logic()
        cropVolumeLogic.Apply(cropVolumeNode)

        # TODO: cropvolume error checking
        outputVolume = slicer.mrmlScene.GetNodeByID(
            cropVolumeNode.GetOutputVolumeNodeID())
        outputVolume.SetName("baselineROI")
        pNode.SetNodeReferenceID('croppedBaselineVolume',
                                 cropVolumeNode.GetOutputVolumeNodeID())

        self.__vrDisplayNode = None
  def doStepProcessing(self):
    '''
    prepare roi image for the next step
    '''
    #crop scalar volume
    pNode = self.parameterNode()

    pNode.SetParameter('vertebra', self.vSelector.currentText)
    pNode.SetParameter('inst_length', self.iSelector.currentText)
    pNode.SetParameter('approach', self.aSelector.currentText)
    
    cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
    cropVolumeNode.SetScene(slicer.mrmlScene)
    cropVolumeNode.SetName('CropVolume_node')
    cropVolumeNode.SetIsotropicResampling(True)
    cropVolumeNode.SetSpacingScalingConst(0.5)
    slicer.mrmlScene.AddNode(cropVolumeNode)
    # TODO hide from MRML tree

    cropVolumeNode.SetInputVolumeNodeID(pNode.GetParameter('baselineVolumeID'))
    cropVolumeNode.SetROINodeID(pNode.GetParameter('roiNodeID'))
    # cropVolumeNode.SetAndObserveOutputVolumeNodeID(outputVolume.GetID())

    cropVolumeLogic = slicer.modules.cropvolume.logic()
    cropVolumeLogic.Apply(cropVolumeNode)

    # TODO: cropvolume error checking
    outputVolume = slicer.mrmlScene.GetNodeByID(cropVolumeNode.GetOutputVolumeNodeID())
    outputVolume.SetName("baselineROI")
    pNode.SetParameter('croppedBaselineVolumeID',cropVolumeNode.GetOutputVolumeNodeID())
    
    self.__vrDisplayNode = None
Esempio n. 4
0
    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)
Esempio n. 5
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')
Esempio n. 6
0
    def doStepProcessing(self):
        '''
    prepare roi image for the next step
    '''
        pNode = self.parameterNode()
        cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
        cropVolumeNode.SetScene(slicer.mrmlScene)
        cropVolumeNode.SetName('ChangeTracker_CropVolume_node')
        cropVolumeNode.SetIsotropicResampling(True)
        cropVolumeNode.SetSpacingScalingConst(0.5)
        slicer.mrmlScene.AddNode(cropVolumeNode)
        # TODO hide from MRML tree

        cropVolumeNode.SetInputVolumeNodeID(
            pNode.GetParameter('baselineVolumeID'))
        cropVolumeNode.SetROINodeID(pNode.GetParameter('roiNodeID'))
        # cropVolumeNode.SetAndObserveOutputVolumeNodeID(outputVolume.GetID())

        cropVolumeLogic = slicer.modules.cropvolume.logic()
        cropVolumeLogic.Apply(cropVolumeNode)

        # TODO: cropvolume error checking
        outputVolume = slicer.mrmlScene.GetNodeByID(
            cropVolumeNode.GetOutputVolumeNodeID())
        outputVolume.SetName("baselineROI")
        pNode.SetParameter('croppedBaselineVolumeID',
                           cropVolumeNode.GetOutputVolumeNodeID())

        roiSegmentationID = pNode.GetParameter(
            'croppedBaselineVolumeSegmentationID')
        if roiSegmentationID == '':
            roiRange = outputVolume.GetImageData().GetScalarRange()

            # default threshold is half-way of the range
            thresholdParameter = str(
                0.5 * (roiRange[0] + roiRange[1])) + ',' + str(roiRange[1])
            pNode.SetParameter('thresholdRange', thresholdParameter)
            pNode.SetParameter('useSegmentationThresholds', 'True')

        # even if the seg. volume exists, it needs to be updated, because ROI
        # could have changed
        vl = slicer.modules.volumes.logic()
        roiSegmentation = vl.CreateLabelVolume(slicer.mrmlScene, outputVolume,
                                               'baselineROI_segmentation')
        pNode.SetParameter('croppedBaselineVolumeSegmentationID',
                           roiSegmentation.GetID())
Esempio n. 7
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)

        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')
Esempio n. 8
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)

    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 doStepProcessing(self):
    '''
    prepare roi image for the next step
    '''
    pNode = self.parameterNode()
    cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
    cropVolumeNode.SetScene(slicer.mrmlScene)
    cropVolumeNode.SetName('ChangeTracker_CropVolume_node')
    cropVolumeNode.SetIsotropicResampling(True)
    cropVolumeNode.SetSpacingScalingConst(0.5)
    slicer.mrmlScene.AddNode(cropVolumeNode)
    # TODO hide from MRML tree

    cropVolumeNode.SetInputVolumeNodeID(pNode.GetParameter('baselineVolumeID'))
    cropVolumeNode.SetROINodeID(pNode.GetParameter('roiNodeID'))
    # cropVolumeNode.SetAndObserveOutputVolumeNodeID(outputVolume.GetID())

    cropVolumeLogic = slicer.modules.cropvolume.logic()
    cropVolumeLogic.Apply(cropVolumeNode)

    # TODO: cropvolume error checking
    outputVolume = slicer.mrmlScene.GetNodeByID(cropVolumeNode.GetOutputVolumeNodeID())
    outputVolume.SetName("baselineROI")
    pNode.SetParameter('croppedBaselineVolumeID',cropVolumeNode.GetOutputVolumeNodeID())

    roiSegmentationID = pNode.GetParameter('croppedBaselineVolumeSegmentationID') 
    if roiSegmentationID == '':
      roiRange = outputVolume.GetImageData().GetScalarRange()

      # default threshold is half-way of the range
      thresholdParameter = str(0.5*(roiRange[0]+roiRange[1]))+','+str(roiRange[1])
      pNode.SetParameter('thresholdRange', thresholdParameter)
      pNode.SetParameter('useSegmentationThresholds', 'True')

    # even if the seg. volume exists, it needs to be updated, because ROI
    # could have changed
    vl = slicer.modules.volumes.logic()
    roiSegmentation = vl.CreateLabelVolume(slicer.mrmlScene, outputVolume, 'baselineROI_segmentation')
    pNode.SetParameter('croppedBaselineVolumeSegmentationID', roiSegmentation.GetID())
Esempio n. 10
0
	def ThresholdPrep(self):

		""" This method prepares for the following segmentation/thresholding
			step. It accomplishes a few things things. It uses the cropvolume Slicer
			module to create a new, ROI-only node. It then creates a label volume
			and initializes threholds variables for the next step.
		"""

		# Crop volume to ROI.
		pNode = self.parameterNode()
		cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
		cropVolumeNode.SetScene(slicer.mrmlScene)
		cropVolumeNode.SetName('T1_Contrast_CropVolume_node')
		cropVolumeNode.SetIsotropicResampling(True)
		cropVolumeNode.SetSpacingScalingConst(0.5)
		slicer.mrmlScene.AddNode(cropVolumeNode)

		cropVolumeNode.SetInputVolumeNodeID(pNode.GetParameter('subtractVolumeID'))
		cropVolumeNode.SetROINodeID(pNode.GetParameter('roiNodeID'))

		cropVolumeLogic = slicer.modules.cropvolume.logic()
		cropVolumeLogic.Apply(cropVolumeNode)

		outputVolume = slicer.mrmlScene.GetNodeByID(cropVolumeNode.GetOutputVolumeNodeID())
		outputVolume.SetName("subtractROI")
		pNode.SetParameter('croppedSubtractVolumeID',cropVolumeNode.GetOutputVolumeNodeID())

		# Get starting threshold parameters.
		roiSegmentationID = pNode.GetParameter('croppedSubtractVolumeSegmentationID') 
		if roiSegmentationID == '':
			roiRange = outputVolume.GetImageData().GetScalarRange()

			thresholdParameter = str(0.5*(roiRange[0]+roiRange[1]))+','+str(roiRange[1])
			pNode.SetParameter('thresholdRange', thresholdParameter)

		# Create a label node for segmentation.
		vl = slicer.modules.volumes.logic()
		roiSegmentation = vl.CreateLabelVolume(slicer.mrmlScene, outputVolume, 'subtractROI_segmentation')
		pNode.SetParameter('croppedSubtractVolumeSegmentationID', roiSegmentation.GetID())
    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)
Esempio n. 12
0
	def ThresholdPrep(self):

		""" This method prepares for the following segmentation/thresholding
			step. It accomplishes a few things. It uses the cropvolume Slicer
			module to create a new, ROI-only node. It then creates a label volume
			and initializes threholds variables for the next step.
		"""

		pNode = self.parameterNode()
		baselineVolumeID = pNode.GetParameter('baselineVolumeID')
		followupVolumeID = pNode.GetParameter('followupVolumeID')

		followupVolume = Helper.getNodeByID(followupVolumeID)
		baselineVolume = Helper.getNodeByID(baselineVolumeID)

		if self.__ConvexROI:
			outputVolume = slicer.vtkMRMLScalarVolumeNode()
			slicer.mrmlScene.AddNode(outputVolume)

			Helper.SetLabelVolume(None)

			# Crop volume to Convex ROI
			inputVolume = self.__subtractVolume
			outputVolume = outputVolume
			clippingModel = self.__clippingModelSelector.currentNode()
			clipOutsideSurface = True
			fillValue = inputVolume.GetImageData().GetScalarRange()[0] - 1

			self.__logic.clipVolumeWithModel(inputVolume, clippingModel, clipOutsideSurface, fillValue, outputVolume)

			self.__logic.showInSliceViewers(outputVolume, ["Red", "Yellow", "Green"])

			outputVolume.SetName(baselineVolume.GetName() + '_subtraction_roi')
			pNode.SetParameter('croppedSubtractVolumeID',outputVolume.GetID())
			pNode.SetParameter('ROIType', 'convex')

		if self.__CubicROI:
			# Crop volume to Cubic ROI.
			cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
			cropVolumeNode.SetScene(slicer.mrmlScene)
			cropVolumeNode.SetName('T1_Contrast_CropVolume_node')
			cropVolumeNode.SetIsotropicResampling(True)
			cropVolumeNode.SetSpacingScalingConst(0.5)
			slicer.mrmlScene.AddNode(cropVolumeNode)

			cropVolumeNode.SetInputVolumeNodeID(pNode.GetParameter('subtractVolumeID'))
			cropVolumeNode.SetROINodeID(pNode.GetParameter('roiNodeID'))

			cropVolumeLogic = slicer.modules.cropvolume.logic()
			cropVolumeLogic.Apply(cropVolumeNode)

			outputVolume = slicer.mrmlScene.GetNodeByID(cropVolumeNode.GetOutputVolumeNodeID())
			outputVolume.SetName(baselineVolume.GetName() + '_subtraction_roi')
			pNode.SetParameter('croppedSubtractVolumeID',cropVolumeNode.GetOutputVolumeNodeID())

			pNode.SetParameter('ROIType', 'cubic')

		# Get starting threshold parameters.
		roiSegmentationID = pNode.GetParameter('croppedSubtractVolumeSegmentationID') 
		if roiSegmentationID == '':
			roiRange = outputVolume.GetImageData().GetScalarRange()

			thresholdParameter = str(0.5*(roiRange[0]+roiRange[1]))+','+str(roiRange[1])
			pNode.SetParameter('thresholdRange', thresholdParameter)

		# Create a label node for segmentation.
		vl = slicer.modules.volumes.logic()
		roiSegmentation = vl.CreateLabelVolume(slicer.mrmlScene, outputVolume, baselineVolume.GetName() + '_subtraction_annotation')
		pNode.SetParameter('croppedSubtractVolumeSegmentationID', roiSegmentation.GetID())
  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)