• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python vtk.vtkImageData函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中vtk.vtkImageData函数的典型用法代码示例。如果您正苦于以下问题:Python vtkImageData函数的具体用法?Python vtkImageData怎么用?Python vtkImageData使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了vtkImageData函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: onCenterPointSet

  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)
开发者ID:che85,项目名称:SliceTracker,代码行数:32,代码来源:SliceTrackerZFrameRegistration.py


示例2: to_vtk

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
开发者ID:Houssk,项目名称:invesalius3,代码行数:35,代码来源:converters.py


示例3: read

    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
开发者ID:OpenChemistry,项目名称:tomviz,代码行数:30,代码来源:matlab.py


示例4: FixGantryTilt

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
开发者ID:151706061,项目名称:invesalius,代码行数:51,代码来源:imagedata_utils.py


示例5: __init__

  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)
开发者ID:afruehstueck,项目名称:CommonGL,代码行数:56,代码来源:GLFilters.py


示例6: convertArray2vtkImage

 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   
开发者ID:cgallego,项目名称:display_features,代码行数:27,代码来源:feature_maps.py


示例7: createSampleLabelmapVolumeNode

  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
开发者ID:kingofpanda,项目名称:Slicer,代码行数:35,代码来源:SubjectHierarchyGenericSelfTest.py


示例8: __init__

  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 )
开发者ID:BRAINSia,项目名称:Slicer,代码行数:30,代码来源:ThresholdEffect.py


示例9: IsosurfaceInitialize

    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
开发者ID:ChaliZhg,项目名称:vmtk,代码行数:25,代码来源:vmtkimageinitialization.py


示例10: __init__

  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())
开发者ID:BRAINSia,项目名称:Slicer,代码行数:28,代码来源:SegmentEditorThresholdEffect.py


示例11: removeIslandsMorphology

  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()
开发者ID:LucasGandel,项目名称:Slicer,代码行数:31,代码来源:RemoveIslandsEffect.py


示例12: SeedInitialize

    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
开发者ID:SaraZanchi,项目名称:vmtk,代码行数:29,代码来源:vmtkimageinitialization.py


示例13: WriteLonI

 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
开发者ID:naucoin,项目名称:SlicerPathology,代码行数:28,代码来源:SlicerPathology.py


示例14: run

    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)
开发者ID:invesalius,项目名称:invesalius3,代码行数:60,代码来源:bitmap_reader.py


示例15: create_volume_node

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
开发者ID:OpenAtWork,项目名称:Slicer,代码行数:28,代码来源:workflow_support.py


示例16: dat2mhd

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()
开发者ID:temporaer,项目名称:wurzel,代码行数:26,代码来源:conv.py


示例17: takeScreenshot

  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)
开发者ID:andrewfzheng,项目名称:Slicer,代码行数:35,代码来源:AddStorableDataAfterSceneViewTest.py


示例18: __init__

    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()
开发者ID:RobotLocomotion,项目名称:drake,代码行数:27,代码来源:show_image.py


示例19: create_image_data

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
开发者ID:JoshuaSBrown,项目名称:langmuir,代码行数:33,代码来源:vtkutils.py


示例20: __init__

    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']
            ])
开发者ID:ValentinaRossi,项目名称:vmtk,代码行数:35,代码来源:vmtkimagevoiselector.py



注:本文中的vtk.vtkImageData函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python vtk.vtkImageDataGeometryFilter函数代码示例发布时间:2022-05-26
下一篇:
Python vtk.vtkImageClip函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap