def onCenterPointSet(self, xy):
    import vtk.util.numpy_support as vnp

    zFrameTemplateVolume = self.zFrameTemplateVolumeSelector.currentNode()
    volumesLogic = slicer.modules.volumes.logic()
    zFrameTemplateMask = volumesLogic.CreateLabelVolume(slicer.mrmlScene, zFrameTemplateVolume, 'zFrameTemplateMask')

    imageDataWorkingCopy = vtk.vtkImageData()
    imageDataWorkingCopy.DeepCopy(zFrameTemplateMask.GetImageData())
    newLabelNodeImage=vtk.vtkImageData()
    newLabelNodeImage.AllocateScalars(vtk.VTK_SHORT, 1)
    newLabelNodeImage.SetExtent(zFrameTemplateMask.GetImageData().GetExtent())
    numpyArray = vnp.vtk_to_numpy(imageDataWorkingCopy.GetPointData().GetScalars()).reshape(imageDataWorkingCopy.GetDimensions()).transpose(2,1,0)
    numpyArray[6:10,70:185,65:190].fill(1)
    spacing = imageDataWorkingCopy.GetSpacing()
    vtk_data = vnp.numpy_to_vtk(num_array=numpyArray.ravel(), deep=True, array_type=vtk.VTK_SHORT)
    newLabelNodeImage.GetPointData().SetScalars(vtk_data)
    dims = numpyArray.shape
    newLabelNodeImage.SetDimensions(dims[2], dims[1], dims[0])
    newLabelNodeImage.SetOrigin(0,0,0)
    newLabelNodeImage.SetSpacing(spacing[0], spacing[1], spacing[2])
    zFrameTemplateMask.SetAndObserveImageData(newLabelNodeImage)
    # update the default label map to the generic anatomy colors
    labelDisplayNode = zFrameTemplateMask.GetDisplayNode()
    labelColorTable = slicer.util.getNode('GenericAnatomyColors')
    labelDisplayNode.SetAndObserveColorNodeID(labelColorTable.GetID())

    self.redCompositeNode.SetBackgroundVolumeID(zFrameTemplateVolume.GetID())
    self.redCompositeNode.SetLabelVolumeID(zFrameTemplateMask.GetID())
    self.redCompositeNode.SetLabelOpacity(0.6)

    self.maskedVolume = self.createMaskedVolume(zFrameTemplateVolume, zFrameTemplateMask)
Пример #2
0
def to_vtk(n_array, spacing, slice_number, orientation):
    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == 'AXIAL':
        extent = (0, dx -1, 0, dy -1, slice_number, slice_number + dz - 1)
    elif orientation == 'SAGITAL':
        dx, dy, dz = dz, dx, dy
        extent = (slice_number, slice_number + dx - 1, 0, dy - 1, 0, dz - 1)
    elif orientation == 'CORONAL':
        dx, dy, dz = dx, dz, dy
        extent = (0, dx - 1, slice_number, slice_number + dy - 1, 0, dz - 1)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetDimensions(dx, dy, dz)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)

    return image_copy
Пример #3
0
    def read(self, path):
        try:
            mat_dict = scipy.io.loadmat(path)
        except NotImplementedError as e:
            # matlab v7.3 requires h5py to load
            if 'matlab v7.3' in str(e).lower():
                print('Tomviz does not currently support matlab v7.3 files')
                print('Please convert the file to matlab v7.2 or earlier')
                return vtkImageData()
            raise

        data = None
        for item in mat_dict.values():
            # Assume only one 3D array per file
            if isinstance(item, np.ndarray):
                if len(item.shape) == 3:
                    data = item
                    break

        if data is None:
            return vtkImageData()

        image_data = vtkImageData()
        (x, y, z) = data.shape
        image_data.SetOrigin(0, 0, 0)
        image_data.SetSpacing(1, 1, 1)
        image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1)
        tomviz.utils.set_array(image_data, data)

        return image_data
Пример #4
0
  def __init__(self, inputVolumes, outputVolume):
    """Configure outputVolume and an iterationVolume to match
    the first inputVolume."""

    self.inputVolumes = inputVolumes
    self.outputVolume = outputVolume

    if len(inputVolumes) < 1:
      raise "Must have at least one input volume"
    self.volume0 = inputVolumes[0]
    if not self.volume0.GetImageData():
      raise "Must have a valid input volume with image data"

    # TODO: caller should be required to specify all scratch volumes
    iterationName = '%s-iteration' % self.outputVolume.GetName()
    self.iterationVolume = slicer.util.getNode(iterationName)
    if not self.iterationVolume:
      self.iterationVolume = slicer.vtkMRMLScalarVolumeNode()
      self.iterationVolume.SetName(iterationName)
      slicer.mrmlScene.AddNode(self.iterationVolume)

    rasToIJK = vtk.vtkMatrix4x4()
    self.volume0.GetRASToIJKMatrix(rasToIJK)
    for volume in [self.iterationVolume, self.outputVolume]:
      volume.SetRASToIJKMatrix(rasToIJK)
      volume.SetAndObserveTransformNodeID(self.volume0.GetTransformNodeID())
      image = vtk.vtkImageData()
      image.SetDimensions(self.volume0.GetImageData().GetDimensions())
      image.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 4) # TODO: needs to be RGBA for rendering
      volume.SetAndObserveImageData(image)

    self.header = """
      #version 120

      vec3 transformPoint(const in vec3 samplePoint)
      {
        return samplePoint; // identity
      }
    """

    self.vertexShaderTemplate = """
      #version 120
      attribute vec3 vertexAttribute;
      attribute vec2 textureCoordinateAttribute;
      varying vec3 interpolatedTextureCoordinate;
      void main()
      {
        interpolatedTextureCoordinate = vec3(textureCoordinateAttribute, .5);
        gl_Position = vec4(vertexAttribute, 1.);
      }
    """

    self.readBackToVolumeNode = False
    self.dummyImage = vtk.vtkImageData()
    self.dummyImage.SetDimensions(5,5,5)
    self.dummyImage.AllocateScalars(vtk.VTK_SHORT, 1)
Пример #5
0
def FixGantryTilt(imagedata, tilt):
    """
    Fix gantry tilt given a vtkImageData and the tilt value. Return new
    vtkImageData.
    """

    # Retrieve data from original imagedata
    extent = [int(value) for value in imagedata.GetExtent()]
    origin = imagedata.GetOrigin()
    spacing = [float(value) for value in imagedata.GetSpacing()]

    n_slices = int(extent[5])
    new_zspacing = math.cos(tilt*(math.acos(-1.0)/180.0)) * spacing[2] #zspacing
    translate_coef = math.tan(tilt*math.pi/180.0)*new_zspacing*(n_slices-1)

    # Class responsible for translating data
    reslice = vtk.vtkImageReslice()
    reslice.SetInput(imagedata)
    reslice.SetInterpolationModeToLinear()
    # Translation will create new pixels. Let's set new pixels' colour to black.
    reslice.SetBackgroundLevel(imagedata.GetScalarRange()[0])

    # Class responsible for append translated data
    append = vtk.vtkImageAppend()
    append.SetAppendAxis(2)

    # Translate and append each slice
    for i in xrange(n_slices+1):
        slice_imagedata = vtk.vtkImageData()
        value = math.tan(tilt*math.pi/180.0) * new_zspacing * i
        new_origin1 = origin[1] + value - translate_coef
        # Translate data
        reslice.SetOutputOrigin(origin[0], new_origin1, origin[2])
        reslice.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], i,i)
        reslice.Update()
        # Append data
        slice_imagedata.DeepCopy(reslice.GetOutput())
        slice_imagedata.UpdateInformation()

        append.AddInput(slice_imagedata)

    append.Update()

    # Final imagedata
    imagedata = vtk.vtkImageData()
    imagedata.DeepCopy(append.GetOutput())
    imagedata.SetSpacing(spacing[0], spacing[1], new_zspacing)
    imagedata.SetExtent(extent)
    imagedata.UpdateInformation()

    return imagedata
Пример #6
0
 def convertArray2vtkImage(self, nparray, t_ImagedataVTK, npImagesandMask): 
     """ Takes a numpy.ndarray and converts it to a vtkimageData. require npImagesandMask to pass on image info """
     # Create vtk object
     size_array = npImagesandMask['dims'][0]*npImagesandMask['dims'][1]*npImagesandMask['dims'][2]
     flatim = nparray.transpose(2,1,0)
     flatim = flatim.flatten()
     
     # create vtk image
     vtk_image = vtk.vtkImageData()
     vtk_image.DeepCopy(t_ImagedataVTK)
     vtk_image.SetNumberOfScalarComponents(1)
     vtk_image.SetScalarTypeToDouble()
     vtk_image.AllocateScalars()
     
     # Get scalars from numpy
     image_array = vtk.vtkDoubleArray() 
     image_array.SetNumberOfValues(size_array)
     image_array.SetNumberOfComponents(1) 
     
     # not too efficient convertion of np.array to vtk. Far from ideal
     for k in range(size_array):
         image_array.InsertTuple1(k,flatim[k])
         
     vtk_image.GetPointData().SetScalars(image_array) 
     vtk_image.Update()
       
     return vtk_image   
  def createSampleLabelmapVolumeNode(self, volumeNode, name, label, colorNode=None):
    self.assertTrue( volumeNode != None )
    self.assertTrue( volumeNode.IsA('vtkMRMLScalarVolumeNode') )
    self.assertTrue( label > 0 )

    sampleLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    sampleLabelmapNode.SetName(name)
    sampleLabelmapNode = slicer.mrmlScene.AddNode(sampleLabelmapNode)
    sampleLabelmapNode.Copy(volumeNode)
    imageData = vtk.vtkImageData()
    imageData.DeepCopy(volumeNode.GetImageData())
    sampleLabelmapNode.SetAndObserveImageData(imageData)

    extent = imageData.GetExtent()
    for x in xrange(extent[0], extent[1]+1):
      for y in xrange(extent[2], extent[3]+1):
        for z in xrange(extent[4], extent[5]+1):
          if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
            imageData.SetScalarComponentFromDouble(x,y,z,0,label)
          else:
            imageData.SetScalarComponentFromDouble(x,y,z,0,0)

    # Display labelmap
    labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
    slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
    if colorNode == None:
      colorNode = slicer.util.getNode('GenericAnatomyColors')
      self.assertTrue( colorNode != None )
    labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
    labelmapVolumeDisplayNode.VisibilityOn()
    sampleLabelmapNodeName = slicer.mrmlScene.GenerateUniqueName(name)
    sampleLabelmapNode.SetName(sampleLabelmapNodeName)
    sampleLabelmapNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())

    return sampleLabelmapNode
Пример #8
0
  def __init__(self, sliceWidget):
    super(ThresholdEffectTool,self).__init__(sliceWidget)

    # create a logic instance to do the non-gui work
    self.logic = ThresholdEffectLogic(self.sliceWidget.sliceLogic())
    self.logic.undoRedo = self.undoRedo

    # interaction state variables
    self.min = 0
    self.max = 0

    # class instances
    self.lut = None
    self.thresh = None
    self.map = None

    # feedback actor
    self.cursorMapper = vtk.vtkImageMapper()
    self.cursorDummyImage = vtk.vtkImageData()
    self.cursorDummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.cursorMapper.SetInputData( self.cursorDummyImage )
    self.cursorActor = vtk.vtkActor2D()
    self.cursorActor.VisibilityOff()
    self.cursorActor.SetMapper( self.cursorMapper )
    self.cursorMapper.SetColorWindow( 255 )
    self.cursorMapper.SetColorLevel( 128 )

    self.actors.append( self.cursorActor )

    self.renderer.AddActor2D( self.cursorActor )
Пример #9
0
    def IsosurfaceInitialize(self):

        self.PrintLog('Isosurface initialization.')

        if self.Interactive:
            queryString = "Please input isosurface level (\'n\' for none): "
            self.IsoSurfaceValue = self.ThresholdInput(queryString)
        
        imageMathematics = vtk.vtkImageMathematics()
        imageMathematics.SetInput(self.Image)
        imageMathematics.SetConstantK(-1.0)
        imageMathematics.SetOperationToMultiplyByK()
        imageMathematics.Update()

        subtract = vtk.vtkImageMathematics()
        subtract.SetInput(imageMathematics.GetOutput())
        subtract.SetOperationToAddConstant()
        subtract.SetConstantC(self.IsoSurfaceValue)
        subtract.Update()

        self.InitialLevelSets = vtk.vtkImageData()
        self.InitialLevelSets.DeepCopy(subtract.GetOutput())
        self.InitialLevelSets.Update()

        self.IsoSurfaceValue = 0.0
  def __init__(self):
    self.lookupTable = vtk.vtkLookupTable()
    self.lookupTable.SetRampToLinear()
    self.lookupTable.SetNumberOfTableValues(2)
    self.lookupTable.SetTableRange(0, 1)
    self.lookupTable.SetTableValue(0,  0, 0, 0,  0)
    self.colorMapper = vtk.vtkImageMapToRGBA()
    self.colorMapper.SetOutputFormatToRGBA()
    self.colorMapper.SetLookupTable(self.lookupTable)
    self.thresholdFilter = vtk.vtkImageThreshold()
    self.thresholdFilter.SetInValue(1)
    self.thresholdFilter.SetOutValue(0)
    self.thresholdFilter.SetOutputScalarTypeToUnsignedChar()

    # Feedback actor
    self.mapper = vtk.vtkImageMapper()
    self.dummyImage = vtk.vtkImageData()
    self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
    self.mapper.SetInputData(self.dummyImage)
    self.actor = vtk.vtkActor2D()
    self.actor.VisibilityOff()
    self.actor.SetMapper(self.mapper)
    self.mapper.SetColorWindow(255)
    self.mapper.SetColorLevel(128)

    # Setup pipeline
    self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort())
    self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
Пример #11
0
  def removeIslandsMorphology(self):
    """
    Remove cruft from image by eroding away by iterations number of layers of surface
    pixels and then saving only islands that are bigger than the minimumSize.
    Then dilate back and save only the pixels that are in both the original and
    result image.  Result is that small islands outside the foreground and small features
    on the foreground are removed.

    By calling the decrufter twice with fg and bg reversed, you can clean up small features in
    a label map while preserving the original boundary in other places.
    """
    if not self.sliceLogic:
      self.sliceLogic = self.editUtil.getSliceLogic()
    parameterNode = self.editUtil.getParameterNode()
    self.minimumSize = int(parameterNode.GetParameter("IslandEffect,minimumSize"))
    self.fullyConnected = bool(parameterNode.GetParameter("IslandEffect,fullyConnected"))

    labelImage = vtk.vtkImageData()
    labelImage.DeepCopy( self.getScopedLabelInput() )
    label = self.editUtil.getLabel()

    slicer.modules.EditorWidget.toolsBox.undoRedo.saveState()

    self.removeIslandsMorphologyDecruft(labelImage,0,label)
    self.getScopedLabelOutput().DeepCopy(labelImage)
    self.applyScopedLabel()
    slicer.app.processEvents(qt.QEventLoop.ExcludeUserInputEvents)

    self.removeIslandsMorphologyDecruft(labelImage,label,0)
    self.getScopedLabelOutput().DeepCopy(labelImage)
    self.applyScopedLabel()
Пример #12
0
    def SeedInitialize(self):

        self.PrintLog('Seed initialization.')

        queryString = 'Please place seeds'
        seeds = self.SeedInput(queryString,0)
        
        self.InitialLevelSets = vtk.vtkImageData()
        self.InitialLevelSets.DeepCopy(self.Image)
        self.InitialLevelSets.Update()

        levelSetsInputScalars = self.InitialLevelSets.GetPointData().GetScalars()
        levelSetsInputScalars.FillComponent(0,1.0)

        dimensions = self.Image.GetDimensions()
        for i in range(seeds.GetNumberOfPoints()):
            id = self.Image.FindPoint(seeds.GetPoint(i))
            levelSetsInputScalars.SetComponent(id,0,-1.0)

        dilateErode = vtk.vtkImageDilateErode3D()
        dilateErode.SetInput(self.InitialLevelSets)
        dilateErode.SetDilateValue(-1.0)
        dilateErode.SetErodeValue(1.0)
        dilateErode.SetKernelSize(3,3,3)
        dilateErode.Update()

        self.InitialLevelSets.DeepCopy(dilateErode.GetOutput())

        self.IsoSurfaceValue = 0.0
Пример #13
0
 def WriteLonI(self, src, dest):
   dim = src.GetDimensions()
   i = vtk.vtkImageData().NewInstance()
   i.SetDimensions(dim[0],dim[1],1)
   i.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,3)
   for x in range(0,dim[0]):
     for y in range(0,dim[1]):
       if (src.GetScalarComponentAsDouble(x,y,0,0)==0):
         for c in range(0,3):
           i.SetScalarComponentFromDouble(x,y,0,c,dest.GetScalarComponentAsDouble(x,y,0,c))
       else:
         if (
            (src.GetScalarComponentAsDouble(x+1,y-1,0,0)==1) and
            (src.GetScalarComponentAsDouble(x+1,y,0,0)==1) and
            (src.GetScalarComponentAsDouble(x+1,y+1,0,0)==1) and
            (src.GetScalarComponentAsDouble(x,y+1,0,0)==1) and
            (src.GetScalarComponentAsDouble(x,y-1,0,0)==1) and
            (src.GetScalarComponentAsDouble(x-1,y+1,0,0)==1) and
            (src.GetScalarComponentAsDouble(x-1,y,0,0)==1) and
            (src.GetScalarComponentAsDouble(x-1,y-1,0,0)==1)):
           for c in range(0,3):
             i.SetScalarComponentFromDouble(x,y,0,c,dest.GetScalarComponentAsDouble(x,y,0,c))
         else:
           i.SetScalarComponentFromDouble(x,y,0,0,0)
           i.SetScalarComponentFromDouble(x,y,0,1,250)
           i.SetScalarComponentFromDouble(x,y,0,2,0)
   i.Modified()
   return i
Пример #14
0
    def run(self):
        global vtk_error

        #----- verify extension ------------------
        extension = VerifyDataType(self.filepath)

        file_name = self.filepath.split(os.path.sep)[-1]

        n_array = ReadBitmap(self.filepath)
      
        if not(isinstance(n_array, numpy.ndarray)):
            return False
            
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        dim = image.GetDimensions()
        x = dim[0]
        y = dim[1]

        img = vtk.vtkImageResample()
        img.SetInputData(image)
        img.SetAxisMagnificationFactor ( 0, 0.25 )
        img.SetAxisMagnificationFactor ( 1, 0.25 )
        img.SetAxisMagnificationFactor ( 2, 1 )    
        img.Update()

        tp = img.GetOutput().GetScalarTypeAsString()

        image_copy = vtk.vtkImageData()
        image_copy.DeepCopy(img.GetOutput())
        
        thumbnail_path = tempfile.mktemp()

        write_png = vtk.vtkPNGWriter()
        write_png.SetInputConnection(img.GetOutputPort())
        write_png.AddObserver("WarningEvent", VtkErrorPNGWriter)
        write_png.SetFileName(thumbnail_path)
        write_png.Write()

        if vtk_error:
            img = vtk.vtkImageCast()
            img.SetInputData(image_copy)
            img.SetOutputScalarTypeToUnsignedShort()
            #img.SetClampOverflow(1)
            img.Update()

            write_png = vtk.vtkPNGWriter()
            write_png.SetInputConnection(img.GetOutputPort())
            write_png.SetFileName(thumbnail_path)
            write_png.Write()
    
            vtk_error = False

        id = wx.NewId()

        bmp_item = [self.filepath, thumbnail_path, extension, x, y,\
                                str(x) + ' x ' + str(y), file_name, id]
        self.bmp_file.Add(bmp_item)
Пример #15
0
def create_volume_node(volume_type, attach_display_node = False, dimensions=None, prefix=''):
    """
    Creates a volume node and inserts it into the MRML tree
    """
    if volume_type not in __VOLUME_TYPES__:
        raise ValueError('Volume type %s is not valid' % volume_type )

    volume_node = eval('slicer.vtkMRML%sVolumeNode()' % volume_type)
    volume_node.SetName(slicer.mrmlScene.GetUniqueNameByString('%s%s' % (prefix, volume_type)))

    if dimensions:
        image_data = vtk.vtkImageData()
        image_data.SetDimensions(dimensions)
        if vtk.VTK_MAJOR_VERSION <= 5:
            image_data.AllocateScalars()
        else:
            image_data.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)

        volume_node.SetAndObserveImageData(image_data)

    slicer.mrmlScene.AddNode(volume_node)

    if attach_display_node:
        display_node = eval('slicer.vtkMRML%sVolumeDisplayNode()' % volume_type)
        slicer.mrmlScene.AddNode(display_node)
        volume_node.AddAndObserveDisplayNodeID( display_node.GetID() )

    return volume_node
Пример #16
0
def dat2mhd(fn):
    with open("L2_17aug.dat") as fd:
        D = np.fromfile(file=fd, dtype=np.uint8).reshape((256, 256, 120)).astype("float32") / 255.0

    D = np.log(D + 1)

    from scipy.ndimage.interpolation import zoom

    D = zoom(D, [1, 1, 256.0 / 120.0])

    flat_d = D.transpose(2, 1, 0).flatten()
    vtk_d_array = ns.numpy_to_vtk(flat_d)

    image = vtk.vtkImageData()

    points = image.GetPointData()
    points.SetScalars(vtk_d_array)

    image.SetDimensions(D.shape)

    image.Update()

    w = vtk.vtkMetaImageWriter()
    w.SetFileName("bla.hdr")
    w.SetInput(image)
    w.Write()
  def takeScreenshot(self,name,description,type=-1):
    # show the message even if not taking a screen shot
    slicer.util.delayDisplay('Take screenshot: '+description+'.\nResult is available in the Annotations module.', 3000)

    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
    qimage = ctk.ctkWidgetsUtils.grabWidget(widget)
    imageData = vtk.vtkImageData()
    slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData)

    annotationLogic = slicer.modules.annotations.logic()
    annotationLogic.CreateSnapShot(name, description, type, 1, imageData)
Пример #18
0
    def __init__(self, image_handler):
        self._name = 'Image View'
        self._view = PythonQt.dd.ddQVTKWidgetView()
        self._image_handler = image_handler

        self._image = vtk.vtkImageData()
        self._prev_attrib = None

        # Initialize the view.
        self._view.installImageInteractor()
        # Add actor.
        self._image_actor = vtk.vtkImageActor()
        vtk_SetInputData(self._image_actor, self._image)
        self._image_actor.SetVisibility(False)
        self._view.renderer().AddActor(self._image_actor)

        self._view.orientationMarkerWidget().Off()
        self._view.backgroundRenderer().SetBackground(0, 0, 0)
        self._view.backgroundRenderer().SetBackground2(0, 0, 0)

        self._depth_mapper = None

        # Add timer.
        self._render_timer = TimerCallback(
            targetFps=60,
            callback=self.render)
        self._render_timer.start()
Пример #19
0
def create_image_data(nx, ny, nz, dx=1.0, dy=1.0, dz=1.0, ox=0, oy=0, oz=0):
    """
    Construct an empty vtkImageData.  This data structure is a regular grid
    with constant spacing.

    :param nx: number of grid points along x-axis
    :param ny: number of grid points along y-axis
    :param nz: number of grid points along z-axis
    :param dx: spacing along x-axis
    :param dy: spacing along y-axis
    :param dz: spacing along z-axis
    :param ox: origin of x-axis
    :param oy: origin of y-axis
    :param oz: origin of z-axis

    :type nx: int
    :type ny: int
    :type nz: int
    :type dx: float
    :type dy: float
    :type dz: float
    :type ox: float
    :type oy: float
    :type oz: float

    >>> image_data = create_image_data(32, 32, 32)
    """
    image_data = vtk.vtkImageData()
    image_data.SetDimensions(nx, ny, nz)
    image_data.SetExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    image_data.SetOrigin(ox, oy, oz)
    image_data.SetSpacing(dx, dy, dz)
    return image_data
Пример #20
0
    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.CubeSource = vtk.vtkCubeSource()
        self.CubeActor = vtk.vtkActor()
        
        self.BoxActive = 0
        self.BoxBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        self.CroppedImage = vtk.vtkImageData()

        self.vmtkRenderer = None
        self.OwnRenderer = 0

        self.PlaneWidgetX = None
        self.PlaneWidgetY = None
        self.PlaneWidgetZ = None
        self.BoxWidget = None

        self.Image = None

        self.Interactive = 1

        self.SetScriptName('vmtkimagevoiselector')
        self.SetScriptDoc('select a cubical volume of interest and get rid of the rest of the image')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Interactive','interactive','bool',1,'','toggle interactivity'],
            ['BoxBounds','boxbounds','float',6,'','bounds of the cubical region of interest'],
            ['vmtkRenderer','renderer','vmtkRenderer',1,'','external renderer']
            ])
        self.SetOutputMembers([
            ['Image','o','vtkImageData',1,'','the output image','vmtkimagewriter']
            ])
Пример #21
0
def mask_color(image, mask_color):
    """
    Turns a color transparent; assumes that everything else should be the inverse color of mask_color (1-r , 1-b, 1-g)
    """
    from math import floor

    mask_color = [ floor(255 * component) for component in mask_color]

    keep_color = [ 255 - component for component in mask_color]
    # Create an image with an alpha channel
    image_data = vtkImageData()

    width, height, _ = image.GetDimensions()
    image_data = img(width, height)
    # Consider tracking what the min and max opacities are, and mapping all opacities to that range
    # Probably hide that behind a KWARG opation; sounds like extra cycles for not a lot of gain.
    # Copy over the pixels from image
    for x in range(width):
        for y in range(height):
            for component in range(3):
                pix_component = image.GetScalarComponentAsFloat(x, y, 0, component)
                # Remap all colors to the keep color; we're using alpha to get rid of the mask color
                image_data.SetScalarComponentFromFloat(x, y, 0, component, keep_color[component])
            # Since the mask color is the inverse of the keep color, we only need one component to figure out the alpha
            alpha = floor(abs(mask_color[component] - pix_component) / abs(keep_color[component] - mask_color[component]) * 255)
            alpha = min(alpha, 255)
            if alpha < 10:
                # Colors aren't perfect; let's just chop everything off below here, this is basically invisible anyway
                alpha = 0
            if alpha > 245:
                alpha = 255
            image_data.SetScalarComponentFromFloat(x, y, 0, 3, alpha)

    return image_data
Пример #22
0
    def __init__(self, volume, level=None):
        self._surface_algorithm = None
        self._renderer = None
        self._actor = None
        self._mapper = None
        self._volume_array = None

        self._float_array = _vtk.vtkFloatArray()
        self._image_data = _vtk.vtkImageData()
        self._image_data.GetPointData().SetScalars(self._float_array)
        self._setup_data(_numpy.float32(volume))

        self._surface_algorithm = _vtk.vtkMarchingCubes()
        self._surface_algorithm.SetInputData(self._image_data)
        self._surface_algorithm.ComputeNormalsOn()

        if level is not None:
            try:
                self.set_multiple_levels(iter(level))
            except TypeError:
                self.set_level(0, level)

        self._mapper = _vtk.vtkPolyDataMapper()
        self._mapper.SetInputConnection(self._surface_algorithm.GetOutputPort())
        self._mapper.ScalarVisibilityOn() # new
        self._actor = _vtk.vtkActor()
        self._actor.SetMapper(self._mapper)
Пример #23
0
def coprocess(time, timeStep, grid, attributes):
    global coProcessor
    import vtk
    from paraview.vtk import vtkPVCatalyst as catalyst
    import paraview
    from paraview.vtk.util import numpy_support
    dataDescription = catalyst.vtkCPDataDescription()
    dataDescription.SetTimeData(time, timeStep)
    dataDescription.AddInput("input")

    if coProcessor.RequestDataDescription(dataDescription):
        import fedatastructures
        imageData = vtk.vtkImageData()
        imageData.SetExtent(grid.XStartPoint, grid.XEndPoint, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1)
        imageData.SetSpacing(grid.Spacing)

        velocity = numpy_support.numpy_to_vtk(attributes.Velocity)
        velocity.SetName("velocity")
        imageData.GetPointData().AddArray(velocity)

        pressure = numpy_support.numpy_to_vtk(attributes.Pressure)
        pressure.SetName("pressure")
        imageData.GetCellData().AddArray(pressure)
        dataDescription.GetInputDescriptionByName("input").SetGrid(imageData)
        dataDescription.GetInputDescriptionByName("input").SetWholeExtent(0, grid.NumberOfGlobalXPoints-1, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1)
        coProcessor.CoProcess(dataDescription)
Пример #24
0
 def __init__(self,volumeNode):
   self.volumeNode = volumeNode
   self.stashImage = vtk.vtkImageData()
   self.stash = slicer.vtkImageStash()
   self.stashImage.DeepCopy( volumeNode.GetImageData() )
   self.stash.SetStashImage( self.stashImage )
   self.stash.ThreadedStash()
Пример #25
0
    def Execute(self):

        self.PrintLog('Converting Numpy Array to vtkImageData')
        self.Image = vtk.vtkImageData()
        self.Image.SetDimensions(self.ArrayDict['Dimensions'])
        self.Image.SetOrigin(self.ArrayDict['Origin'])
        self.Image.SetSpacing(self.ArrayDict['Spacing'])
        self.Image.SetExtent((0, self.ArrayDict['Dimensions'][0] - 1,
                                0, self.ArrayDict['Dimensions'][1] - 1,
                                0, self.ArrayDict['Dimensions'][2] - 1,))


        self.PrintLog('converting point data')
        for pointKey in self.ArrayDict['PointData'].keys():
            if np.issubdtype(self.ArrayDict['PointData'][pointKey].dtype, np.floating):
                pointDataArrayType = vtk.VTK_FLOAT
            else:
                for checkDt in [int, np.uint8, np.uint16, np.uint32, np.uint64]:
                    if np.issubdtype(self.ArrayDict['PointData'][pointKey].dtype, checkDt):
                        pointDataArrayType = vtk.VTK_INT
                        break
                    else:
                        continue

            flatArray = self.ArrayDict['PointData'][pointKey].ravel(order='F')

            pointDataArray = dsa.numpyTovtkDataArray(flatArray, name=pointKey, array_type=pointDataArrayType)

            self.Image.GetPointData().SetActiveScalars(pointKey)
            self.Image.GetPointData().SetScalars(pointDataArray)
Пример #26
0
  def sumManualSegmentations(self, manualSegmentationsDirectory, mergedVolume):
    # Get the manual segmentations and create a single summed image
    import glob
    manualSegmentationFilenames = glob.glob(manualSegmentationsDirectory+"/*.mha")

    # Get the first image which each successive image will be added to
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(manualSegmentationFilenames[0])
    reader.Update()
    summedImage = vtk.vtkImageData()
    summedImage.SetExtent(reader.GetOutput().GetExtent())
    summedImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,1)
    summedImage.ShallowCopy(reader.GetOutput())

    # Initialize filter to add images together
    mathFilter = vtk.vtkImageMathematics()

    # Iterate list and add each new image
    for currentFile in manualSegmentationFilenames[1:]:
      # Get new image
      reader.SetFileName(currentFile)
      reader.Update()

      # Add it to existing summation
      mathFilter.SetInput1Data(summedImage)
      mathFilter.SetInput2Data(reader.GetOutput())
      mathFilter.Update()

      # Get new summation
      summedImage.ShallowCopy(mathFilter.GetOutput())

    # Add summed image to slicer scene
    mergedVolume.SetRASToIJKMatrix(self.rasToIjk)
    mergedVolume.SetIJKToRASMatrix(self.ijkToRas)
    mergedVolume.SetAndObserveImageData(summedImage)
def DICOMReaderToNumpy(directory):
    file_list = glob.glob(directory + os.sep + "*")
    file_list = sorted(file_list)

    ipp = gdcm.IPPSorter()
    ipp.SetComputeZSpacing(True)
    ipp.Sort(file_list)

    file_list = ipp.GetFilenames()

    array = vtk.vtkStringArray()

    for x in xrange(len(file_list)):
        array.InsertValue(x, file_list[x])

    read = vtkgdcm.vtkGDCMImageReader()
    read.SetFileNames(array)
    read.Update()

    img = vtk.vtkImageData()
    img.DeepCopy(read.GetOutput())
    img.SetSpacing(1, 1, 1)
    img.Update()

    ex = img.GetExtent()
    image = vtk.util.numpy_support.vtk_to_numpy(img.GetPointData().GetScalars())
    image = image.reshape((ex[5] + 1, ex[1] + 1, ex[3] + 1))

    return ApplyWindowLevel(image, 2000, 300)
   def createMaskfromMesh(self, VOI_mesh, im):
       """ Takes an image and a VOI_mesh and returns a boolean image with only 1s inside the VOI_mesh """                
       
       # Create an Image of Fext
       white_image = vtk.vtkImageData()
       white_image.DeepCopy(im) 
 
       # polygonal data --> image stencil:
       pol2stenc = vtk.vtkPolyDataToImageStencil()
       pol2stenc.SetInputData(VOI_mesh)
       pol2stenc.SetOutputOrigin(im.GetOrigin())
       pol2stenc.SetOutputSpacing(im.GetSpacing())
       pol2stenc.SetOutputWholeExtent(white_image.GetExtent())
       pol2stenc.SetInformationInput(white_image)
       pol2stenc.Update()
        
       # cut the corresponding white image and set the background:
       imgstenc = vtk.vtkImageStencil()
       imgstenc.SetInputData(white_image)
       imgstenc.SetStencilData(pol2stenc.GetOutput())
       imgstenc.ReverseStencilOff()
       imgstenc.SetBackgroundValue(0.0)
       imgstenc.Update()
       
       # write to image        
       dims = im.GetDimensions()
       scalars = imgstenc.GetOutput().GetPointData().GetScalars()
       np_scalars = vtk_to_numpy(scalars)     
       np_scalars = np_scalars.reshape(dims[2], dims[1], dims[0]) 
       np_scalars = np_scalars.transpose(2,1,0)
       
       return np_scalars
Пример #29
0
def ndarray2vtkImageData(ndarray, cast_type=11, spacing=[1, 1, 1]):
    """
    Convert a NumPy array to a vtkImageData, with a default casting type VTK_DOUBLE
    :param ndarray: input NumPy array, can be 3D array
    :param cast_type: 11 means VTK_DOUBLE
    :return: a vtkImageData
    """
    # Convert numpy array to VTK array (vtkDoubleArray)
    vtk_data_array = numpy_support.numpy_to_vtk(
        num_array=ndarray.transpose(2, 1, 0).ravel(),
        deep=True,
        array_type=vtk.VTK_DOUBLE)

    # Convert the VTK array to vtkImageData
    img_vtk = vtk.vtkImageData()
    img_vtk.SetDimensions(ndarray.shape)
    img_vtk.SetSpacing(spacing[::-1])  # Note the order should be reversed!
    img_vtk.GetPointData().SetScalars(vtk_data_array)  # is a vtkImageData

    # casting
    cast = vtk.vtkImageCast()
    cast.SetInputData(img_vtk)
    cast.SetOutputScalarType(cast_type)
    cast.Update()

    return cast.GetOutput()  # vtkImageData
Пример #30
-2
    def ApplyVED(self):

        vesselness = vtkvmtk.vtkvmtkVesselEnhancingDiffusionImageFilter()
        vesselness.SetInputData(self.Image)
        vesselness.SetSigmaMin(self.SigmaMin)
        vesselness.SetSigmaMax(self.SigmaMax)
        vesselness.SetNumberOfSigmaSteps(self.NumberOfSigmaSteps)
        vesselness.SetAlpha(self.Alpha)
        vesselness.SetBeta(self.Beta)
        vesselness.SetGamma(self.Gamma)
        vesselness.SetC(self.C)
        vesselness.SetTimeStep(self.TimeStep)
        vesselness.SetEpsilon(self.Epsilon)
        vesselness.SetWStrength(self.WStrength)
        vesselness.SetSensitivity(self.Sensitivity)
        vesselness.SetNumberOfIterations(self.NumberOfIterations)
        vesselness.SetNumberOfDiffusionSubIterations(self.NumberOfDiffusionSubIterations)
        if self.SigmaStepMethod == 'equispaced':
            vesselness.SetSigmaStepMethodToEquispaced()
        elif self.SigmaStepMethod == 'logarithmic':
            vesselness.SetSigmaStepMethodToLogarithmic()
        vesselness.Update()

        self.EnhancedImage = vtk.vtkImageData()
        self.EnhancedImage.DeepCopy(vesselness.GetOutput())