Beispiel #1
0
    def storeSceneView(self, name, description=""):
        """  

        NOTE: Taken from here:
        https://github.com/Slicer/Slicer/blob/master/Applications/SlicerApp/
            Testing/Python/SlicerMRBTest.py#L273


        Store a scene view into the current scene.
        TODO: this might move to slicer.util


        @param name: TheSceneViewName
        @return: vtkImageData
        """
        viewport = slicer.app.layoutManager().viewport()
        qImage = qt.QPixmap().grabWidget(viewport).toImage()
        imageData = vtk.vtkImageData()

        slicer.qMRMLUtils().qImageToVtkImageData(qImage, imageData)

        sceneViewNode = slicer.vtkMRMLSceneViewNode()
        sceneViewNode.SetScreenShotType(4)
        sceneViewNode.SetScreenShot(imageData)

        return sceneViewNode.GetScreenShot()
  def takeScreenshot(self,name,description,type=-1,screenshotScaleFactor=1):
    lm = slicer.app.layoutManager()
    # switch on the type to get the requested window
    widget = 0
    if type == -1:
      # full window
      widget = slicer.util.mainWindow()
    elif type == slicer.qMRMLScreenShotDialog().FullLayout:
      # full layout
      widget = lm.viewport()
    elif type == slicer.qMRMLScreenShotDialog().ThreeD:
      # just the 3D window
      widget = lm.threeDWidget(0).threeDView()
    elif type == slicer.qMRMLScreenShotDialog().Red:
      # red slice window
      widget = lm.sliceWidget("Red")
    elif type == slicer.qMRMLScreenShotDialog().Yellow:
      # yellow slice window
      widget = lm.sliceWidget("Yellow")
    elif type == slicer.qMRMLScreenShotDialog().Green:
      # green slice window
      widget = lm.sliceWidget("Green")

    # grab and convert to vtk image data
    qpixMap = qt.QPixmap().grabWidget(widget)
    qimage = qpixMap.toImage()
    imageData = vtk.vtkImageData()
    slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData)

    annotationLogic = slicer.modules.annotations.logic()
    annotationLogic.CreateSnapShot(name, description, type, screenshotScaleFactor, imageData)
    def storeSceneView(self, name, description=""):
        """  

        NOTE: Taken from here:
        https://github.com/Slicer/Slicer/blob/master/Applications/SlicerApp/
            Testing/Python/SlicerMRBTest.py#L273


        Store a scene view into the current scene.
        TODO: this might move to slicer.util


        @param name: TheSceneViewName
        @return: vtkImageData
        """
        viewport = slicer.app.layoutManager().viewport()
        qImage = qt.QPixmap().grabWidget(viewport).toImage()
        imageData = vtk.vtkImageData()

        slicer.qMRMLUtils().qImageToVtkImageData(qImage,imageData)

        sceneViewNode = slicer.vtkMRMLSceneViewNode()
        sceneViewNode.SetScreenShotType(4)
        sceneViewNode.SetScreenShot(imageData)
 
        return sceneViewNode.GetScreenShot()
Beispiel #4
0
    def captureBitmap(self, threeDWidget, filePath):

        # grab and convert to vtk image data
        qpixMap = qt.QPixmap().grabWidget(threeDWidget)
        qimage = qpixMap.toImage()
        imageData = vtk.vtkImageData()
        slicer.qMRMLUtils().qImageToVtkImageData(qimage, imageData)
        qimage.save(filePath)
 def onLoadFinished(self,worked):
   self.qImage.fill(0)
   self.webView.render(self.qImage)
   utils = slicer.qMRMLUtils()
   utils.qImageToVtkImageData(self.qImage,self.vtkImage)
   self.imageActor.SetInput(self.vtkImage)
   self.threeDView.scheduleRender()
Beispiel #6
0
  def timeimage(self,cmd=''):
    """For debugging - return an image with the current time
    rendered as text down to the hundredth of a second"""

    # check arguments
    p = urlparse.urlparse(cmd)
    q = urlparse.parse_qs(p.query)
    try:
      color = "#" + q['color'][0].strip().lower()
    except KeyError:
      color = "#330"

    #
    # make a generally transparent image,
    #
    imageWidth = 128
    imageHeight = 32
    timeImage = qt.QImage(imageWidth, imageHeight, qt.QImage().Format_ARGB32)
    timeImage.fill(0)

    # a painter to use for various jobs
    painter = qt.QPainter()

    # draw a border around the pixmap
    painter.begin(timeImage)
    pen = qt.QPen()
    color = qt.QColor(color)
    color.setAlphaF(0.8)
    pen.setColor(color)
    pen.setWidth(5)
    pen.setStyle(3) # dotted line (Qt::DotLine)
    painter.setPen(pen)
    rect = qt.QRect(1, 1, imageWidth-2, imageHeight-2)
    painter.drawRect(rect)
    color = qt.QColor("#333")
    pen.setColor(color)
    painter.setPen(pen)
    position = qt.QPoint(10,20)
    text = str(time.time()) # text to draw
    painter.drawText(position, text)
    painter.end()

    # convert the image to vtk, then to png from there
    vtkTimeImage = vtk.vtkImageData()
    slicer.qMRMLUtils().qImageToVtkImageData(timeImage, vtkTimeImage)
    pngData = self.vtkImageDataToPNG(vtkTimeImage)
    return pngData
Beispiel #7
0
  def _createMagnifiedPixmap(self, xyz, inputImageDataConnection, outputSize, crosshairColor, imageZoom=10):

    # Use existing instance of objects to avoid instanciating one at each event.
    imageCrop = self.imageCrop
    painter = self.painter
    pen = self.pen

    def _roundInt(value):
      try:
        return int(round(value))
      except ValueError:
        return 0

    imageCrop.SetInputConnection(inputImageDataConnection)
    xyzInt = [0, 0, 0]
    xyzInt = [_roundInt(value) for value in xyz]
    producer = inputImageDataConnection.GetProducer()
    dims = producer.GetOutput().GetDimensions()
    minDim = min(dims[0],dims[1])
    imageSize = _roundInt(minDim/imageZoom/2.0)
    imin = max(0,xyzInt[0]-imageSize)
    imax = min(dims[0]-1,  xyzInt[0]+imageSize)
    jmin = max(0,xyzInt[1]-imageSize)
    jmax = min(dims[1]-1,  xyzInt[1]+imageSize)
    if (imin <= imax) and (jmin <= jmax):
      imageCrop.SetVOI(imin, imax, jmin, jmax, 0,0)
      imageCrop.Update()
      vtkImage = imageCrop.GetOutput()
      if vtkImage:
        qImage = qt.QImage()
        slicer.qMRMLUtils().vtkImageDataToQImage(vtkImage, qImage)
        imagePixmap = qt.QPixmap.fromImage(qImage)
        imagePixmap = imagePixmap.scaled(outputSize, qt.Qt.KeepAspectRatio, qt.Qt.FastTransformation)

        # draw crosshair
        painter.begin(imagePixmap)
        pen = qt.QPen()
        pen.setColor(crosshairColor)
        painter.setPen(pen)
        painter.drawLine(0, imagePixmap.height()/2, imagePixmap.width(), imagePixmap.height()/2)
        painter.drawLine(imagePixmap.width()/2,0, imagePixmap.width()/2, imagePixmap.height())
        painter.end()
        return imagePixmap
    return None
    def takeScreenshot(self, name, description, type=-1):
        # show the message even if not taking a screen shot
        self.delayDisplay(description)

        if self.enableScreenshots == 0:
            return

        lm = slicer.app.layoutManager()
        # switch on the type to get the requested window
        widget = 0
        if type == slicer.qMRMLScreenShotDialog.FullLayout:
            # full layout
            widget = lm.viewport()
        elif type == slicer.qMRMLScreenShotDialog.ThreeD:
            # just the 3D window
            widget = lm.threeDWidget(0).threeDView()
        elif type == slicer.qMRMLScreenShotDialog.Red:
            # red slice window
            widget = lm.sliceWidget("Red")
        elif type == slicer.qMRMLScreenShotDialog.Yellow:
            # yellow slice window
            widget = lm.sliceWidget("Yellow")
        elif type == slicer.qMRMLScreenShotDialog.Green:
            # green slice window
            widget = lm.sliceWidget("Green")
        else:
            # default to using the full window
            widget = slicer.util.mainWindow()
            # reset the type so that the node is set correctly
            type = slicer.qMRMLScreenShotDialog.FullLayout

        # grab and convert to vtk image data
        qpixMap = qt.QPixmap().grabWidget(widget)
        qimage = qpixMap.toImage()
        imageData = vtk.vtkImageData()
        slicer.qMRMLUtils().qImageToVtkImageData(qimage, imageData)

        annotationLogic = slicer.modules.annotations.logic()
        annotationLogic.CreateSnapShot(name, description, type,
                                       self.screenshotScaleFactor, imageData)
  def takeScreenshot(self,name,description,type=-1):
    # show the message even if not taking a screen shot
    self.delayDisplay(description)

    if self.enableScreenshots == 0:
      return

    lm = slicer.app.layoutManager()
    # switch on the type to get the requested window
    widget = 0
    if type == slicer.qMRMLScreenShotDialog.FullLayout:
      # full layout
      widget = lm.viewport()
    elif type == slicer.qMRMLScreenShotDialog.ThreeD:
      # just the 3D window
      widget = lm.threeDWidget(0).threeDView()
    elif type == slicer.qMRMLScreenShotDialog.Red:
      # red slice window
      widget = lm.sliceWidget("Red")
    elif type == slicer.qMRMLScreenShotDialog.Yellow:
      # yellow slice window
      widget = lm.sliceWidget("Yellow")
    elif type == slicer.qMRMLScreenShotDialog.Green:
      # green slice window
      widget = lm.sliceWidget("Green")
    else:
      # default to using the full window
      widget = slicer.util.mainWindow()
      # reset the type so that the node is set correctly
      type = slicer.qMRMLScreenShotDialog.FullLayout

    # grab and convert to vtk image data
    qpixMap = qt.QPixmap().grabWidget(widget)
    qimage = qpixMap.toImage()
    imageData = vtk.vtkImageData()
    slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData)

    annotationLogic = slicer.modules.annotations.logic()
    annotationLogic.CreateSnapShot(name, description, type, self.screenshotScaleFactor, imageData)
Beispiel #10
0
  def saveScreenshot(self, name, filePath, description):
    type = slicer.qMRMLScreenShotDialog.FullLayout
    lm = slicer.app.layoutManager()
    widget = lm.viewport()
    # grab and convert to vtk image data
    qpixMap = qt.QPixmap().grabWidget(widget)
    qimage = qpixMap.toImage()
    imageData = vtk.vtkImageData()
    slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData)

    annotationLogic = slicer.modules.annotations.logic()
    annotationLogic.CreateSnapShot(name, description, type, 1, imageData)
    
    snapshotNode = slicer.util.getNode(name)
    
    if not snapshotNode:
       print "Can't get snapshotNode"
       return
    
    if not slicer.util.saveNode(snapshotNode, filePath):
       print "Can't save " + filePath
       return
Beispiel #11
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)
  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)
Beispiel #13
0
    def generate(self,
                 volumeRenderingNode,
                 filePattern="/tmp/slice_%04d.png"):  # underscore not dash
        self.cancelRequested = False

        # Ensure view node and widget exists and cross-references are up-to-date
        self.create3dView(volumeRenderingNode)
        self.threeDViewNode.SetAndObserveParentLayoutNodeID(
            volumeRenderingNode.GetID())
        self.threeDWidget.setMRMLViewNode(self.threeDViewNode)

        # Make sure the selected volume rendering node is visible in the capture view
        if not volumeRenderingNode.IsDisplayableInView(
                self.threeDViewNode.GetID()):
            volumeRenderingNode.AddViewNodeID(self.threeDViewNode.GetID())

        # Configure view and widget
        self.threeDViewNode.SetBoxVisible(0)
        self.threeDViewNode.SetAxisLabelsVisible(0)
        self.threeDViewNode.SetVolumeRenderingQuality(
            slicer.vtkMRMLViewNode.Normal
        )  # viewNode.Maximum could provide better quality but slower
        self.threeDViewNode.SetRenderMode(slicer.vtkMRMLViewNode.Orthographic)
        self.threeDViewNode.SetBackgroundColor((1, 1, 1))
        self.threeDViewNode.SetBackgroundColor2((1, 1, 1))

        # Turn off shading. We do not want any lighting effect (specular reflections, etc.) to be baked into the image.
        originalShade = volumeRenderingNode.GetVolumePropertyNode(
        ).GetVolumeProperty().GetShade()
        volumeRenderingNode.GetVolumePropertyNode().GetVolumeProperty(
        ).SetShade(False)

        self.threeDWidget.resize(self.width, self.height)
        self.threeDWidget.show()

        # Save original ROI
        volumeRenderingNode.SetCroppingEnabled(True)
        roi = volumeRenderingNode.GetROINode()
        roiCenter = [0] * 3
        roiRadius = [0] * 3
        roi.GetXYZ(roiCenter)
        roi.GetRadiusXYZ(roiRadius)
        originalRoiVisibility = roi.GetDisplayVisibility()
        roi.SetDisplayVisibility(False)

        cameraPositionOffset = 100.0
        cameraNode = slicer.modules.cameras.logic().GetViewActiveCameraNode(
            self.threeDViewNode)
        cameraNode.SetFocalPoint(roiCenter)
        cameraNode.SetPosition(
            roiCenter[0], roiCenter[1],
            roiCenter[2] + roiRadius[2] + cameraPositionOffset)
        cameraNode.SetViewUp((0, 1, 0))
        cameraNode.GetCamera().SetClippingRange(
            cameraPositionOffset / 2.0,
            roiRadius[2] * 2 + cameraPositionOffset * 2.0)

        windowSizeInPixels = self.threeDWidget.threeDView().renderWindow(
        ).GetSize()

        pixelSizeInMm = 25.4 / self.yResolutionDpi
        heightOfViewportInMm = windowSizeInPixels[
            1] * pixelSizeInMm / self.printScale
        cameraNode.SetParallelScale(heightOfViewportInMm)

        # cycle through the slabs
        slabRadius = list(roiRadius)
        slabRadius[2] = self.slabThickness
        roi.SetRadiusXYZ(slabRadius)
        slabCounter = 0
        slabCenter = [roiCenter[0], roiCenter[1], roiCenter[2] - roiRadius[2]]
        slabTop = roiCenter[2] + roiRadius[2]
        scaledSlabSpacingMm = self.slabSpacingMm / self.printScale
        numberOfSlabs = int(roiRadius[2] * 2.0 / scaledSlabSpacingMm) + 1

        threeDView = self.threeDWidget.threeDView()
        renderWindow = threeDView.renderWindow()
        renderer = renderWindow.GetRenderers().GetFirstRenderer()

        originalCameraUserTransform = cameraNode.GetCamera().GetUserTransform()
        originalPixelAspect = renderer.GetPixelAspect()
        cameraUserTransform = vtk.vtkTransform()
        cameraUserTransform.Scale(self.xResolutionDpi / self.yResolutionDpi,
                                  1.0, 1.0)
        cameraNode.GetCamera().SetUserTransform(cameraUserTransform)

        if self.transparentBackground:
            originalAlphaBitPlanes = renderWindow.GetAlphaBitPlanes()
            renderWindow.SetAlphaBitPlanes(1)
            originalGradientBackground = renderer.GetGradientBackground()
            renderer.SetGradientBackground(False)

        logging.info("Starting render...")

        while slabCenter[2] <= slabTop:
            slicer.app.processEvents()
            if self.cancelRequested:
                break

            roi.SetXYZ(slabCenter)
            threeDView.forceRender()
            windowToImage = vtk.vtkWindowToImageFilter()
            if self.transparentBackground:
                windowToImage.SetInputBufferTypeToRGBA()
                renderWindow.Render()

            windowToImage.SetInput(renderWindow)

            # Write to file with custom DPI
            # (use Qt file writer to allow saving DPI values)
            filename = "c:/tmp/test.png"
            windowToImage.Update()
            vtkImage = windowToImage.GetOutput()
            qImage = qt.QImage()
            slicer.qMRMLUtils().vtkImageDataToQImage(vtkImage, qImage)
            inchesPerMeter = 1000 / 25.4
            qImage.setDotsPerMeterX(self.xResolutionDpi * inchesPerMeter)
            qImage.setDotsPerMeterY(self.yResolutionDpi * inchesPerMeter)
            imagePixmap = qt.QPixmap.fromImage(qImage)
            filePath = filePattern % slabCounter
            imagePixmap.save(filePath)

            slabCounter += 1
            slabCenter[2] = slabCenter[2] + scaledSlabSpacingMm
            logging.info("Slab {0}/{1} saved to {2}".format(
                slabCounter, numberOfSlabs, filePath))

        self.threeDWidget.hide()

        # reset ROI
        roi.SetXYZ(roiCenter)
        roi.SetRadiusXYZ(roiRadius)
        roi.SetDisplayVisibility(originalRoiVisibility)

        cameraNode.GetCamera().SetUserTransform(originalCameraUserTransform)

        if self.transparentBackground:
            renderWindow.SetAlphaBitPlanes(originalAlphaBitPlanes)
            renderer.SetGradientBackground(originalGradientBackground)

        volumeRenderingNode.GetVolumePropertyNode().GetVolumeProperty(
        ).SetShade(originalShade)

        # for debugging convenience
        slicer.modules.BitmapGeneratorWidget.threeDWidget = self.threeDWidget
        slicer.modules.BitmapGeneratorWidget.threeDViewNode = self.threeDViewNode
        slicer.modules.BitmapGeneratorWidget.volumeRenderingNode = volumeRenderingNode

        if self.cancelRequested:
            raise ValueError('User requested cancel.')
Beispiel #14
0
  def __init__(self,parent=None,width=400,height=400,showWidget=False,scale=False):
    super(ROIManager,self).__init__()
    self.width = width
    self.height = height
    self.showWidget = showWidget
    self.scale = scale
    self.renderer = None
    self.ROIRadius = 20.0
    self.minValueBG=0
    self.maxValueBG=0
    self.minValueFG=0
    self.maxValueFG=0
    self.probeWidget = None
    self.drawOverlay = 0

    # 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)

    # make a circle actor
    self.circle = vtk.vtkRegularPolygonSource()
    self.circle.SetNumberOfSides(50)
    self.circle.SetRadius(5)
    self.circle.SetCenter(0,0,0)
    self.circle.GeneratePolylineOn()
    self.circle.GeneratePolygonOff()
    self.circle.Update()
    self.mapper = vtk.vtkPolyDataMapper2D()
    self.actor = vtk.vtkActor2D()
    if vtk.VTK_MAJOR_VERSION <= 5:
      self.mapper.SetInput(self.circle.GetOutput())
    else:
      self.mapper.SetInputConnection(self.circle.GetOutputPort())
    self.actor.SetMapper(self.mapper)
    property_ = self.actor.GetProperty()
    property_.SetColor(1,1,0)
    property_.SetLineWidth(1)
Beispiel #15
0
  def processEvent(self,observee,event):
    # TODO: use a timer to delay calculation and compress events
    insideView = False
    ras = [0.0,0.0,0.0]
    xyz = [0.0,0.0,0.0]
    sliceNode = None
    if self.CrosshairNode:
      insideView = self.CrosshairNode.GetCursorPositionRAS(ras)
      sliceNode = self.CrosshairNode.GetCursorPositionXYZ(xyz)

    sliceLogic = None
    if sliceNode:
      appLogic = slicer.app.applicationLogic()
      if appLogic:
        sliceLogic = appLogic.GetSliceLogic(sliceNode)

    if not insideView or not sliceNode or not sliceLogic:
      self.currentLayoutName = None
      # reset all the readouts
      self.viewerColor.text = ""
      self.viewInfo.text =  ""
      layers = ('L', 'F', 'B')
      for layer in layers:
        self.layerNames[layer].setText( "" )
        self.layerIJKs[layer].setText( "" )
        self.layerValues[layer].setText( "" )
      self.imageLabel.hide()
      self.viewerColor.hide()
      self.viewInfo.hide()
      self.viewerFrame.hide()
      self.showImageBox.show()
      return

    self.viewerColor.show()
    self.viewInfo.show()
    self.viewerFrame.show()
    self.showImageBox.hide()

    self.currentLayoutName = sliceNode.GetLayoutName()

    # populate the widgets
    self.viewerColor.setText( " " )
    rgbColor = sliceNode.GetLayoutColor();
    color = qt.QColor.fromRgbF(rgbColor[0], rgbColor[1], rgbColor[2])
    if hasattr(color, 'name'):
      self.viewerColor.setStyleSheet('QLabel {background-color : %s}' % color.name())

    # Described below are the details for the ras coordinate width set to 6:
    #  1: sign
    #  3: suggested number of digits before decimal point
    #  1: decimal point:
    #  1: number of digits after decimal point

    spacing = "%.1f" % sliceLogic.GetLowestVolumeSliceSpacing()[2]
    if sliceNode.GetSliceSpacingMode() == slicer.vtkMRMLSliceNode.PrescribedSliceSpacingMode:
      spacing = "(%s)" % spacing

    self.viewInfo.text = \
      "  {layoutName: <8s}  RAS: ({ras_x:6.1f}, {ras_y:6.1f}, {ras_z:6.1f})  {orient: >8s} Sp: {spacing:s}" \
      .format(layoutName=sliceNode.GetLayoutName(),
              ras_x=ras[0],
              ras_y=ras[1],
              ras_z=ras[2],
              orient=sliceNode.GetOrientationString(),
              spacing=spacing
              )

    def _roundInt(value):
      try:
        return int(round(value))
      except ValueError:
        return 0

    hasVolume = False
    layerLogicCalls = (('L', sliceLogic.GetLabelLayer),
                       ('F', sliceLogic.GetForegroundLayer),
                       ('B', sliceLogic.GetBackgroundLayer))
    for layer,logicCall in layerLogicCalls:
      layerLogic = logicCall()
      volumeNode = layerLogic.GetVolumeNode()
      ijk = [0, 0, 0]
      if volumeNode:
        hasVolume = True
        xyToIJK = layerLogic.GetXYToIJKTransform()
        ijkFloat = xyToIJK.TransformDoublePoint(xyz)
        ijk = [_roundInt(value) for value in ijkFloat]
      self.layerNames[layer].setText(
        "<b>%s</b>" % (self.fitName(volumeNode.GetName()) if volumeNode else "None"))
      self.layerIJKs[layer].setText(
        "({i:4d}, {j:4d}, {k:4d})".format(i=ijk[0], j=ijk[1], k=ijk[2]) if volumeNode else "")
      self.layerValues[layer].setText(
        "<b>%s</b>" % self.getPixelString(volumeNode,ijk) if volumeNode else "")

    # set image
    if (not slicer.mrmlScene.IsBatchProcessing()) and sliceLogic and hasVolume and self.showImage:
      self.imageCrop.SetInputConnection(sliceLogic.GetBlend().GetOutputPort())
      xyzInt = [0, 0, 0]
      xyzInt = [_roundInt(value) for value in xyz]
      dims = sliceLogic.GetBlend().GetOutput().GetDimensions()
      minDim = min(dims[0],dims[1])
      imageSize = _roundInt(minDim/self.imageZoom/2.0)
      imin = max(0,xyzInt[0]-imageSize)
      imax = min(dims[0]-1,  xyzInt[0]+imageSize)
      jmin = max(0,xyzInt[1]-imageSize)
      jmax = min(dims[1]-1,  xyzInt[1]+imageSize)
      if (imin <= imax) and (jmin <= jmax):
        self.imageCrop.SetVOI(imin, imax, jmin, jmax, 0,0)
        self.imageCrop.Update()
        vtkImage = self.imageCrop.GetOutput()
        if vtkImage:
          qImage = qt.QImage()
          slicer.qMRMLUtils().vtkImageDataToQImage(vtkImage, qImage)
          self.imagePixmap = self.imagePixmap.fromImage(qImage)
          self.imagePixmap = self.imagePixmap.scaled(self.imageLabel.size, qt.Qt.KeepAspectRatio, qt.Qt.FastTransformation)

          # draw crosshair
          self.painter.begin(self.imagePixmap)
          self.pen.setColor(color)
          self.painter.setPen(self.pen)
          self.painter.drawLine(0,self.imagePixmap.height()/2, self.imagePixmap.width(), self.imagePixmap.height()/2)
          self.painter.drawLine(self.imagePixmap.width()/2,0, self.imagePixmap.width()/2, self.imagePixmap.height())
          self.painter.end()

          self.imageLabel.setPixmap(self.imagePixmap)
          self.onShowImage(self.showImage)

    sceneName = slicer.mrmlScene.GetURL()
    if sceneName != "":
      self.frame.parent().text = "Data Probe: %s" % self.fitName(sceneName,nameSize=2*self.nameSize)
    else:
      self.frame.parent().text = "Data Probe"
Beispiel #16
0
  def processEvent(self,observee,event):
    # TODO: use a timer to delay calculation and compress events
    insideView = False
    ras = [0.0,0.0,0.0]
    xyz = [0.0,0.0,0.0]
    sliceNode = None
    if self.CrosshairNode:
      insideView = self.CrosshairNode.GetCursorPositionRAS(ras)
      sliceNode = self.CrosshairNode.GetCursorPositionXYZ(xyz)

    sliceLogic = None
    if sliceNode:
      appLogic = slicer.app.applicationLogic()
      if appLogic:
        sliceLogic = appLogic.GetSliceLogic(sliceNode)

    if not insideView or not sliceNode or not sliceLogic:
      self.currentLayoutName = None
      # reset all the readouts
      self.viewerColor.text = ""
      self.viewInfo.text =  ""
      layers = ('L', 'F', 'B')
      for layer in layers:
        self.layerNames[layer].setText( "" )
        self.layerIJKs[layer].setText( "" )
        self.layerValues[layer].setText( "" )
      self.imageLabel.hide()
      self.viewerColor.hide()
      self.viewInfo.hide()
      self.viewerFrame.hide()
      self.showImageBox.show()
      return

    self.viewerColor.show()
    self.viewInfo.show()
    self.viewerFrame.show()
    self.showImageBox.hide()

    self.currentLayoutName = sliceNode.GetLayoutName()

    # populate the widgets
    self.viewerColor.setText( " " )
    rgbColor = sliceNode.GetLayoutColor();
    color = qt.QColor.fromRgbF(rgbColor[0], rgbColor[1], rgbColor[2])
    if hasattr(color, 'name'):
      self.viewerColor.setStyleSheet('QLabel {background-color : %s}' % color.name())

    # Described below are the details for the ras coordinate width set to 6:
    #  1: sign
    #  3: suggested number of digits before decimal point
    #  1: decimal point:
    #  1: number of digits after decimal point

    spacing = "%.1f" % sliceLogic.GetLowestVolumeSliceSpacing()[2]
    if sliceNode.GetSliceSpacingMode() == slicer.vtkMRMLSliceNode.PrescribedSliceSpacingMode:
      spacing = "(%s)" % spacing

    self.viewInfo.text = \
      "  {layoutName: <8s}  RAS: ({ras_x:6.1f}, {ras_y:6.1f}, {ras_z:6.1f})  {orient: >8s} Sp: {spacing:s}" \
      .format(layoutName=sliceNode.GetLayoutName(),
              ras_x=ras[0],
              ras_y=ras[1],
              ras_z=ras[2],
              orient=sliceNode.GetOrientationString(),
              spacing=spacing
              )

    def _roundInt(value):
      try:
        return int(round(value))
      except ValueError:
        return 0

    hasVolume = False
    layerLogicCalls = (('L', sliceLogic.GetLabelLayer),
                       ('F', sliceLogic.GetForegroundLayer),
                       ('B', sliceLogic.GetBackgroundLayer))
    for layer,logicCall in layerLogicCalls:
      layerLogic = logicCall()
      volumeNode = layerLogic.GetVolumeNode()
      ijk = [0, 0, 0]
      if volumeNode:
        hasVolume = True
        xyToIJK = layerLogic.GetXYToIJKTransform()
        ijkFloat = xyToIJK.TransformDoublePoint(xyz)
        ijk = [_roundInt(value) for value in ijkFloat]
      self.layerNames[layer].setText(
        "<b>%s</b>" % (self.fitName(volumeNode.GetName()) if volumeNode else "None"))
      self.layerIJKs[layer].setText(
        "({i:4d}, {j:4d}, {k:4d})".format(i=ijk[0], j=ijk[1], k=ijk[2]) if volumeNode else "")
      self.layerValues[layer].setText(
        "<b>%s</b>" % self.getPixelString(volumeNode,ijk) if volumeNode else "")

    # set image
    if (not slicer.mrmlScene.IsBatchProcessing()) and sliceLogic and hasVolume and self.showImage:
      self.imageCrop.SetInputConnection(sliceLogic.GetBlend().GetOutputPort())
      xyzInt = [0, 0, 0]
      xyzInt = [_roundInt(value) for value in xyz]
      dims = sliceLogic.GetBlend().GetOutput().GetDimensions()
      minDim = min(dims[0],dims[1])
      imageSize = _roundInt(minDim/self.imageZoom/2.0)
      imin = max(0,xyzInt[0]-imageSize)
      imax = min(dims[0]-1,  xyzInt[0]+imageSize)
      jmin = max(0,xyzInt[1]-imageSize)
      jmax = min(dims[1]-1,  xyzInt[1]+imageSize)
      if (imin <= imax) and (jmin <= jmax):
        self.imageCrop.SetVOI(imin, imax, jmin, jmax, 0,0)
        self.imageCrop.Update()
        vtkImage = self.imageCrop.GetOutput()
        if vtkImage:
          qImage = qt.QImage()
          slicer.qMRMLUtils().vtkImageDataToQImage(vtkImage, qImage)
          self.imagePixmap = self.imagePixmap.fromImage(qImage)
          self.imagePixmap = self.imagePixmap.scaled(self.imageLabel.size, qt.Qt.KeepAspectRatio, qt.Qt.FastTransformation)

          # draw crosshair
          self.painter.begin(self.imagePixmap)
          self.pen.setColor(color)
          self.painter.setPen(self.pen)
          self.painter.drawLine(0,self.imagePixmap.height()/2, self.imagePixmap.width(), self.imagePixmap.height()/2)
          self.painter.drawLine(self.imagePixmap.width()/2,0, self.imagePixmap.width()/2, self.imagePixmap.height())
          self.painter.end()

          self.imageLabel.setPixmap(self.imagePixmap)
          self.onShowImage(self.showImage)

    sceneName = slicer.mrmlScene.GetURL()
    if sceneName != "":
      self.frame.parent().text = "Data Probe: %s" % self.fitName(sceneName,nameSize=2*self.nameSize)
    else:
      self.frame.parent().text = "Data Probe"
Beispiel #17
0
  def takeScreenshot(self,name,type=-1):
    # show the message even if not taking a screen shot
    
    filePath = '/u/kanderle/Transfer/Movie/'+name+'.png'

    if self.enableScreenshots == 0:
      return

    lm = slicer.app.layoutManager()
    description = '4D'
    # switch on the type to get the requested window
    widget = 0
    if type == -1:
      # full window
      widget = slicer.util.mainWindow()
    elif type == slicer.qMRMLScreenShotDialog().FullLayout:
      # full layout
      widget = lm.viewport()
    elif type == slicer.qMRMLScreenShotDialog().ThreeD:
      # just the 3D window
      widget = lm.threeDWidget(0).threeDView()
    elif type == slicer.qMRMLScreenShotDialog().Red:
      # red slice window
      widget = lm.sliceWidget("Red")
    elif type == slicer.qMRMLScreenShotDialog().Yellow:
      # yellow slice window
      widget = lm.sliceWidget("Yellow")
    elif type == slicer.qMRMLScreenShotDialog().Green:
      # green slice window
      widget = lm.sliceWidget("Green")

    # grab and convert to vtk image data
    
    
    
    if type == slicer.qMRMLScreenShotDialog().ThreeD:
      degrees = 71
      n = 0 #
      heartBeat = 0
      heartDisplayNode = None
      color = [0.56,0,0]
      widget = lm.threeDWidget(0).threeDView()
      for i in range(0,degrees):
	if i < 10:
	  number = '0' + str(i)
	else:
	  number = str(i)
	filePath = '/u/kanderle/Transfer/Movie/'+name+'_'+number+'.png'
	#if i%heartBeat == 0:
	  #if heartDisplayNode:
	    #heartDisplayNode.SetVisibility(0)
	  #n += 1
	  #if n>10:
	    #n = 1
          #print "Changing state to: " + str(n)
	#heartNode = slicer.util.getNode('Heart_' + str(n))
	#if not heartNode:
	  #print "No Heart Node"
	  #n = n+1
	  #continue
	#heartDisplayNode = heartNode.GetDisplayNode()
	#heartDisplayNode.SetColor(color)
	#heartDisplayNode.SetVisibility(1)
	#heartDisplayNode.SetOpacity(0.8)
	  
	rw = widget.renderWindow()
	wti = vtk.vtkWindowToImageFilter()
	wti.SetInput(rw)
	wti.Update()
	writer = vtk.vtkPNGWriter()
	writer.SetFileName(filePath)
	writer.SetInputConnection(wti.GetOutputPort())
	writer.Write()
	widget.yaw()
	widget.forceRender()
	
    else:
      qpixMap = qt.QPixmap().grabWidget(widget)
      qimage = qpixMap.toImage()
      imageData = vtk.vtkImageData()
      slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData)

      annotationLogic = slicer.modules.annotations.logic()
      annotationLogic.CreateSnapShot(name, description, type, self.screenshotScaleFactor, imageData)
  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
Beispiel #19
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