Exemplo n.º 1
0
    def ExtractVOI(self):

        wholeExtent = self.Image.GetExtent()
        origin = self.Image.GetOrigin()
        spacing = self.Image.GetSpacing()

        newVOI = [0, 0, 0, 0, 0, 0]
        newVOI[0] = max(
            wholeExtent[0],
            int(math.ceil((self.BoxBounds[0] - origin[0]) / spacing[0])))
        newVOI[1] = min(
            wholeExtent[1],
            int(math.floor((self.BoxBounds[1] - origin[0]) / spacing[0])))
        newVOI[2] = max(
            wholeExtent[2],
            int(math.ceil((self.BoxBounds[2] - origin[1]) / spacing[1])))
        newVOI[3] = min(
            wholeExtent[3],
            int(math.floor((self.BoxBounds[3] - origin[1]) / spacing[1])))
        newVOI[4] = max(
            wholeExtent[4],
            int(math.ceil((self.BoxBounds[4] - origin[2]) / spacing[2])))
        newVOI[5] = min(
            wholeExtent[5],
            int(math.floor((self.BoxBounds[5] - origin[2]) / spacing[2])))

        extractVOI = vtk.vtkExtractVOI()
        extractVOI.SetInputData(self.CroppedImage)
        extractVOI.SetVOI(newVOI)
        extractVOI.Update()

        self.CroppedImage.DeepCopy(extractVOI.GetOutput())
Exemplo n.º 2
0
  def __init__(self, parent=None):
    self.nameSize = 24

    self.CrosshairNode = None
    self.CrosshairNodeObserverTag = None

    self.frame = qt.QFrame(parent)
    self.frame.setLayout(qt.QVBoxLayout())

    modulePath = slicer.modules.dataprobe.path.replace("DataProbe.py","")
    self.iconsDIR = modulePath + '/Resources/Icons'

    self.showImage = False

    # Used in _createMagnifiedPixmap()
    self.imageCrop = vtk.vtkExtractVOI()
    self.painter = qt.QPainter()
    self.pen = qt.QPen()

    self._createSmall()

    #Helper class to calculate and display tensor scalars
    self.calculateTensorScalars = CalculateTensorScalars()

    # Observe the crosshair node to get the current cursor position
    self.CrosshairNode = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLCrosshairNode')
    if self.CrosshairNode:
      self.CrosshairNodeObserverTag = self.CrosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, self.processEvent)
Exemplo n.º 3
0
def CreatePlanes(func, actor, numberOfPlanes):
    #
    # Extract planes from implicit function.
    #

    append = vtk.vtkAppendFilter()

    dims = func.GetSampleDimensions()
    sliceIncr = (dims[2] - 1) // (numberOfPlanes + 1)
    sliceNum = -4
    for i in range(0, numberOfPlanes):
        extract = vtk.vtkExtractVOI()
        extract.SetInputConnection(func.GetOutputPort())
        extract.SetVOI(0, dims[0] - 1,
                       0, dims[1] - 1,
                       sliceNum + sliceIncr, sliceNum + sliceIncr)
        append.AddInputConnection(extract.GetOutputPort())
        sliceNum += sliceIncr
    append.Update()

    # Map planes
    planesMapper = vtk.vtkDataSetMapper()
    planesMapper.SetInputConnection(append.GetOutputPort())
    planesMapper.SetScalarRange(0, 7)

    actor.SetMapper(planesMapper)
    actor.GetProperty().SetAmbient(1.)
    return
Exemplo n.º 4
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)
            
            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0,0,0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Exemplo n.º 5
0
def ipl_open(image_in, open):
    ipl_open_settings(open)
    extent = image_in.GetExtent()

    clip = vtk.vtkImageReslice()
    clip.SetInput(image_in)
    clip.SetOutputExtent(extent[0] - open - 2, extent[1] + open + 2,
                         extent[2] - open - 2, extent[3] + open + 2,
                         extent[4] - open - 2, extent[5] + open + 2)
    clip.MirrorOn()
    clip.Update()

    erode = vtk.vtkImageContinuousErode3D()
    erode.SetInputConnection(clip.GetOutputPort())
    erode.SetKernelSize(2 * open + 1, 2 * open + 1, 2 * open + 1)
    erode.Update()

    #Kernel size is twice the dilation distance plus one for the center voxel

    dilate = vtk.vtkImageContinuousDilate3D()
    dilate.SetInputConnection(erode.GetOutputPort())
    dilate.SetKernelSize(2 * open + 1, 2 * open + 1, 2 * open + 1)
    dilate.Update()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(dilate.GetOutput())
    voi.SetVOI(extent[0], extent[1], extent[2], extent[3], extent[4],
               extent[5])
    voi.Update()

    image_out = voi.GetOutput()
    return image_out
Exemplo n.º 6
0
    def crop(self, top=None, bottom=None, right=None, left=None, pixels=False):
        """Crop picture.

        :param float top: fraction to crop from the top margin
        :param float bottom: fraction to crop from the bottom margin
        :param float left: fraction to crop from the left margin
        :param float right: fraction to crop from the right margin
        :param bool pixels: units are pixels
        """
        extractVOI = vtk.vtkExtractVOI()
        extractVOI.SetInputData(self._data)
        extractVOI.IncludeBoundaryOn()

        d = self.GetInput().GetDimensions()
        if pixels:
            extractVOI.SetVOI(right, d[0]-left, bottom, d[1]-top, 0, 0)
        else:
            bx0, bx1, by0, by1 = 0, d[0]-1, 0, d[1]-1
            if left is not None:   bx0 = int((d[0]-1)*left)
            if right is not None:  bx1 = int((d[0]-1)*(1-right))
            if bottom is not None: by0 = int((d[1]-1)*bottom)
            if top is not None:    by1 = int((d[1]-1)*(1-top))
            extractVOI.SetVOI(bx0, bx1, by0, by1, 0, 0)
        extractVOI.Update()
        return self._update(extractVOI.GetOutput())
Exemplo n.º 7
0
def ipl_maskaimpeel(image_in1, image_in2, peel_iter):
    ipl_maskaimpeel_settings(peel_iter)

    extent = image_in1.GetExtent()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(image_in1)
    voi.SetVOI(extent[0], extent[1], extent[2], extent[3], extent[4],
               extent[5])
    voi.Update()

    shift = vtk.vtkImageShiftScale()
    shift.SetInputConnection(voi.GetOutputPort())
    shift.SetOutputScalarTypeToUnsignedChar()
    shift.Update()

    mask = vtk.vtkImageMask()
    mask.SetImageInput(image_in2)
    mask.SetMaskInput(shift.GetOutput())
    mask.SetMaskedOutputValue(0)
    mask.Update()

    if peel_iter != 0:
        erode = vtk.vtkImageContinuousErode3D()
        erode.SetInputConnection(mask.GetOutputPort())
        erode.SetKernelSize(peel_iter + 1, peel_iter + 1, peel_iter + 1)
        erode.Update()

        mask = erode

    image_out = mask.GetOutput()
    return image_out
Exemplo n.º 8
0
def getIsoActor(fname, colour, opacity, value):
    isoreader = vtk.vtkStructuredPointsReader()
    isoreader.SetFileName(fname)
    isoreader.Update()

    extractiso = vtk.vtkExtractVOI()
    if (options.xmax > -1 or options.ymax > -1 or options.zmax > -1):
        extractiso.SetVOI(options.zmin,options.zmax, options.ymin,options.ymax, options.xmin,options.xmax)
    extractiso.SetInput(isoreader.GetOutput())

    iso = vtk.vtkMarchingCubes()
    iso.SetInput(extractiso.GetOutput())
    iso.SetValue(0,value)

    polymap = vtk.vtkPolyDataMapper()
    polymap.SetInput(iso.GetOutput())
    polymap.ScalarVisibilityOff()
    
    isoactor = vtk.vtkActor()
    isoactor.SetMapper(polymap)

    isoactor.GetProperty().SetColor(colour) 
    isoactor.GetProperty().SetOpacity(opacity)

    return (isoreader, isoactor)
Exemplo n.º 9
0
def create_planes(func: vtk.vtkSampleFunction,
                  number_of_planes: int) -> vtk.vtkActor:
    """
    Creates a number of planes that show a slice of the data at that slice.
    Adapted from
    https://lorensen.github.io/VTKExamples/site/Python/Visualization/QuadricVisualization/
    
    :param func: a vtkSampleFunction
    :param number_of_planes: the number of planes to add to the actor.
    :return: the actor to which the planes will be added.
    """
    actor = vtk.vtkActor()
    append = vtk.vtkAppendFilter()

    dimensions = func.GetSampleDimensions()
    slice_increment = (dimensions[2] - 1) // (number_of_planes + 1)
    slice_num = -4
    for i in range(0, number_of_planes):
        extract = vtk.vtkExtractVOI()
        extract.SetInputConnection(func.GetOutputPort())
        extract.SetVOI(0, dimensions[0] - 1, 0, dimensions[1] - 1,
                       slice_num + slice_increment,
                       slice_num + slice_increment)
        append.AddInputConnection(extract.GetOutputPort())
        slice_num += slice_increment
    append.Update()

    planes_mapper = vtk.vtkDataSetMapper()
    planes_mapper.SetInputConnection(append.GetOutputPort())
    planes_mapper.SetScalarRange(0, 7)

    actor.SetMapper(planes_mapper)
    actor.GetProperty().SetAmbient(1.)

    return actor
 def avgProjectionsVtk(self, filenames , extent):
     '''Returns the average of the input images
     
     Input is passed as filenames pointing to 2D TIFF
     Output is a vtkImageData
     gives the same result as avgProjections within machine precision.
     '''
     num = len(filenames)
     readers = [vtk.vtkTIFFReader() for i in range(num)]
     scalers = [vtk.vtkImageShiftScale() for i in range(num)]
     vois = [vtk.vtkExtractVOI() for i in range(num)]
     avger = vtk.vtkImageWeightedSum()
     counter = 0
     for reader, voi, scaler, filename in zip(readers, vois , scalers ,filenames):
         reader.SetFileName(filename)
         reader.Update()
         print ("reading {0}".format(filename))
         voi.SetInputData(reader.GetOutput())
         voi.SetVOI(extent)
         voi.Update()
         print ("extracting VOI")
         scaler.SetInputData(voi.GetOutput())
         scaler.SetOutputScalarTypeToDouble()
         scaler.SetScale(1)
         scaler.SetShift(0)
         scaler.Update()
         avger.AddInputData(scaler.GetOutput())
         avger.SetWeight(counter , 1/float(num))
         counter = counter + 1
         print ("adding input connection {0}".format(counter))
         
     
     avger.Update()
     return avger.GetOutput()
	def getPlane(self, data, plane, xCoordinate, yCoordinate, zCoordinate, applyZScaling = 0):
		"""
		Get a plane from given the volume
		"""   
		xAxis, yAxis, zAxis = 0, 1, 2
		dataWidth, dataHeight, dataDepth = data.GetDimensions()
		if not self.voi:
			self.voi = vtk.vtkExtractVOI()
		else:
			self.voi.RemoveAllInputs()
		if not self.permute:
			self.permute = vtk.vtkImagePermute()
		else:
			self.permute.RemoveAllInputs()
			
		self.permute.SetInputConnection(data.GetProducerPort())
		
		spacing = data.GetSpacing()

		xscale = 1
		yscale = 1

		if plane == "zy":
			data.SetUpdateExtent(xCoordinate, xCoordinate, 0, dataHeight - 1, 0, dataDepth - 1)
			self.permute.SetFilteredAxes(zAxis, yAxis, xAxis)
			self.permute.Update()
			data = self.permute.GetOutput()
			self.voi.SetInput(data)
	
			self.voi.SetVOI(0, dataDepth - 1, 0, dataHeight - 1, xCoordinate, xCoordinate)
	
			xdim = dataDepth
			ydim = dataHeight
			
			if applyZScaling: 
				xdim *= spacing[2]
				xscale = spacing[2]
			
		elif plane == "xz":
			data.SetUpdateExtent(0, dataWidth - 1, yCoordinate, yCoordinate, 0, dataDepth - 1)
			self.permute.SetFilteredAxes(xAxis, zAxis, yAxis)
			self.permute.Update()
			data = self.permute.GetOutput()
	
			self.voi.SetInput(data)
			self.voi.SetVOI(0, dataWidth - 1, 0, dataDepth - 1, yCoordinate, yCoordinate)

			xdim = dataWidth
			ydim = dataDepth
			if applyZScaling: 
				ydim *= spacing[2]
				yscale = 1
			
		self.voi.Update()
		if applyZScaling:
			self.voi.Update()
			return lib.ImageOperations.scaleImage(self.voi.GetOutput(), interpolation = 2, xfactor = xscale, yfactor = yscale)
			
		self.voi.Update()
		return self.voi.GetOutput()
Exemplo n.º 12
0
 def vtkVOIdata(self, volum = 'GAUSSIAN'):
    """ Modification du volume d'interet """
    #-----------------------------------------
    # Creation de la VOI
    #-----------------------------------------
    self.vtkVolum = vtk.vtkExtractVOI()
    self.vtkVolum.SetInput(self.vtkVolumAll.GetOutput())
    self.vtkVolum.SetVOI(self.VOI_pt1[0], self.VOI_pt2[0], \
                         self.VOI_pt1[1], self.VOI_pt2[1], \
                         self.VOI_pt1[2], self.VOI_pt2[2])
    
    self.vtkVolumBlur = vtk.vtkImageGaussianSmooth()
    #-----------------------------------------
    # Creation du volume sur volume filtre gaussien
    #-----------------------------------------
    if volum == 'GAUSSIAN':
       self.vtkVolumBlur.SetInputConnection(self.vtkVolum.GetOutputPort()) 
    #-----------------------------------------
    # Creation du volume sur volume filtre gradient + gaussien
    #-----------------------------------------
    if volum == 'GRADIENT':
       self.vtkVolumGrad = vtk.vtkImageGradientMagnitude()
       self.vtkVolumGrad.SetDimensionality(3)
       self.vtkVolumGrad.HandleBoundariesOn()
       self.vtkVolumGrad.SetInputConnection(self.vtkVolum.GetOutputPort())
       self.vtkVolumBlur.SetInputConnection(self.vtkVolumGrad.GetOutputPort()) 
    
    self.vtkVolumBlur.SetStandardDeviation(self.valGaussianFilter)
    self.vtkVolumBlur.Update()
    self.vtkVolumRange = self.vtkVolumBlur.GetOutput().GetScalarRange()
    
    print " Range from Volume Of Interest : ", self.vtkVolumRange
Exemplo n.º 13
0
    def test_dither_boat(self):
        self.print_param.fill_pattern.value = 1
        self.print_param.skin_offset.value = 1.0
        self.print_param.infill.value = 0.5

        slicer = VoxelSlicer()
        slicer.set_settings(self.printer_setting,
                            self.printhead_setting, self.print_param)
        slicer.SetInputDataObject(self.part)
        slicer.Update()

        slice_stack = slicer.GetOutputDataObject(0)
        img_dim = slice_stack.GetDimensions()
        self.assertTrue(img_dim[2] > 0)
        (x_min, x_max, y_min, y_max, _, _) = slice_stack.GetExtent()

        mid_point = int(img_dim[2]/2)
        single_im = vtk.vtkExtractVOI()
        single_im.SetVOI(x_min, x_max, y_min, y_max, mid_point, mid_point)
        single_im.SetSampleRate(1, 1, 1)
        single_im.SetInputData(slice_stack)
        single_im.Update()

        writer = vtk.vtkBMPWriter()
        writer.SetInputData(single_im.GetOutput())
        writer.SetFileName(os.path.join(self.out_dir, 'test_d.bmp'))
        writer.Update()
        writer.Write()

        writer_3d = vtk.vtkXMLImageDataWriter()
        writer_3d.SetFileName(os.path.join(self.out_dir, 'test_d.vti'))
        writer_3d.SetInputData(slice_stack)
        writer_3d.Update()
        writer_3d.Write()
Exemplo n.º 14
0
    def crop(self,
             left=None, right=None,
             back=None, front=None,
             bottom=None, top=None,
             VOI=()
            ):
        """Crop a ``Volume`` object.

        :param float left:   fraction to crop from the left plane (negative x)
        :param float right:  fraction to crop from the right plane (positive x)
        :param float back:   fraction to crop from the back plane (negative y)
        :param float front:  fraction to crop from the front plane (positive y)
        :param float bottom: fraction to crop from the bottom plane (negative z)
        :param float top:    fraction to crop from the top plane (positive z)
        :param list VOI:     extract Volume Of Interest expressed in voxel numbers

            Eg.: vol.crop(VOI=(xmin, xmax, ymin, ymax, zmin, zmax)) # all integers nrs
        """
        extractVOI = vtk.vtkExtractVOI()
        extractVOI.SetInputData(self.imagedata())

        if len(VOI):
            extractVOI.SetVOI(VOI)
        else:
            d = self.imagedata().GetDimensions()
            bx0, bx1, by0, by1, bz0, bz1 = 0, d[0]-1, 0, d[1]-1, 0, d[2]-1
            if left is not None:   bx0 = int((d[0]-1)*left)
            if right is not None:  bx1 = int((d[0]-1)*(1-right))
            if back is not None:   by0 = int((d[1]-1)*back)
            if front is not None:  by1 = int((d[1]-1)*(1-front))
            if bottom is not None: bz0 = int((d[2]-1)*bottom)
            if top is not None:    bz1 = int((d[2]-1)*(1-top))
            extractVOI.SetVOI(bx0, bx1, by0, by1, bz0, bz1)
        extractVOI.Update()
        return self._update(extractVOI.GetOutput())
def extractVOI(image, b0, b1, b2, b3, b4, b5):
    min_voxel_ijk = [int()] * 3
    max_voxel_ijk = [int()] * 3
    pcoords = [float()] * 3

    image.ComputeStructuredCoordinates([b0, b2, b4], min_voxel_ijk, pcoords)
    image.ComputeStructuredCoordinates([b1, b3, b5], max_voxel_ijk, pcoords)

    def ifZero(value):
        if value == 0:
            return value
        else:
            return value + 1

    start_voxel_ijk = map(ifZero, min_voxel_ijk)
    extents_ijk = list(
        reduce(lambda i, j: i + j, zip(start_voxel_ijk, max_voxel_ijk)))

    extract_voi = vtk.vtkExtractVOI()
    if vtk.vtkVersion.GetVTKMajorVersion() < 6:
        extract_voi.SetInput(image)
    else:
        extract_voi.SetInputData(image)

    extract_voi.SetVOI(*extents_ijk)
    extract_voi.Update()

    return extract_voi.GetOutput()
Exemplo n.º 16
0
def ipl_erosion(image_in, erode_distance):
    ipl_erosion_settings(erode_distance)
    extent = image_in.GetExtent()

    #Actual distance of pixel erosion
    distance = erode_distance + 1

    pad = vtk.vtkImageReslice()
    pad.SetInput(image_in)
    pad.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], extent[4],
                        extent[5])
    pad.Update()

    #Kernel size is twice the dilation distance plus one for the center voxel
    erode = vtk.vtkImageContinuousErode3D()
    erode.SetInputConnection(pad.GetOutputPort())
    erode.SetKernelSize(2 * distance + 1, 2 * distance + 1, 2 * distance + 1)
    erode.Update()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(erode.GetOutput())
    voi.SetVOI(extent[0] + distance, extent[1] - distance,
               extent[2] + distance, extent[3] - distance,
               extent[4] + distance, extent[5] - distance)
    voi.Update()

    image_out = voi.GetOutput()
    return image_out
Exemplo n.º 17
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)

            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0, 0, 0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Exemplo n.º 18
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExtractVOI(), 'Processing.',
         ('vtkImageData',), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 19
0
 def buildPipeline(self):
     """ execute() -> None
     Dispatch the vtkRenderer to the actual rendering widget
     """        
     self.initialOrigin = self.input.GetOrigin()
     self.initialExtent = self.input.GetExtent()
     self.initialSpacing = self.input.GetSpacing()
     self.initialAoi = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing ) 
     self.currentAoi = list( self.initialAoi )
             
     self.clip = vtk.vtkExtractVOI()  
     self.inputModule.inputToAlgorithm( self.clip )
     
     self.pad = vtk.vtkImageMagnify()
     self.pad.InterpolateOn()
     self.pad.SetInputConnection( self.clip.GetOutputPort() ) 
     
     self.imageInfo = vtk.vtkImageChangeInformation()
     self.imageInfo.SetInputConnection( self.pad.GetOutputPort() ) 
     self.imageInfo.SetOutputOrigin( self.initialOrigin[0], self.initialOrigin[1], self.initialOrigin[2] )
     self.imageInfo.SetOutputExtentStart( self.initialExtent[0], self.initialExtent[2], self.initialExtent[4] )
     self.imageInfo.SetOutputSpacing( self.initialSpacing[0], self.initialSpacing[1], self.initialSpacing[2] )
     
     self.setExtent( self.initialExtent )          
     self.set3DOutput( port=self.imageInfo.GetOutputPort() )
Exemplo n.º 20
0
def visQuadFunc():
    """ vtk sample scene with iso contours """

    # VTK supports implicit functions of the form f(x,y,z)=constant. These
    # functions can represent things spheres, cones, etc. Here we use a
    # general form for a quadric to create an elliptical data field.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    # vtkSampleFunction samples an implicit function over the x-y-z range
    # specified (here it defaults to -1,1 in the x,y,z directions).
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(30, 30, 30)
    sample.SetImplicitFunction(quadric)

    # Create five surfaces F(x,y,z) = constant between range specified. The
    # GenerateValues() method creates n isocontour values between the range
    # specified.
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(8, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contours.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)

    contActor = vtk.vtkActor()
    contActor.SetMapper(contMapper)

    # We'll put a simple outline around the data.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 0.5, 0)

    # extract data from the volume
    extract = vtk.vtkExtractVOI()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetVOI(0, 29, 0, 29, 15, 15)
    extract.SetSampleRate(1, 2, 3)

    contours2 = vtk.vtkContourFilter()
    contours2.SetInputConnection(extract.GetOutputPort())
    contours2.GenerateValues(8, 0.0, 1.2)

    contMapper2 = vtk.vtkPolyDataMapper()
    contMapper2.SetInputConnection(contours2.GetOutputPort())
    contMapper2.SetScalarRange(0.0, 1.2)

    contActor2 = vtk.vtkActor()
    contActor2.SetMapper(contMapper2)

    return contActor, contActor2, outlineActor, contours, contours2
Exemplo n.º 21
0
def visQuadFunc():
    """ vtk sample scene with iso contours """

    # VTK supports implicit functions of the form f(x,y,z)=constant. These
    # functions can represent things spheres, cones, etc. Here we use a
    # general form for a quadric to create an elliptical data field.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

    # vtkSampleFunction samples an implicit function over the x-y-z range
    # specified (here it defaults to -1,1 in the x,y,z directions).
    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(30, 30, 30)
    sample.SetImplicitFunction(quadric)

    # Create five surfaces F(x,y,z) = constant between range specified. The
    # GenerateValues() method creates n isocontour values between the range
    # specified.
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(sample.GetOutputPort())
    contours.GenerateValues(8, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contours.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)

    contActor = vtk.vtkActor()
    contActor.SetMapper(contMapper)

    # We'll put a simple outline around the data.
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(sample.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 0.5, 0)

    # extract data from the volume
    extract = vtk.vtkExtractVOI()
    extract.SetInputConnection(sample.GetOutputPort())
    extract.SetVOI(0, 29, 0, 29, 15, 15)
    extract.SetSampleRate(1, 2, 3)

    contours2 = vtk.vtkContourFilter()
    contours2.SetInputConnection(extract.GetOutputPort())
    contours2.GenerateValues(8, 0.0, 1.2)

    contMapper2 = vtk.vtkPolyDataMapper()
    contMapper2.SetInputConnection(contours2.GetOutputPort())
    contMapper2.SetScalarRange(0.0, 1.2)

    contActor2 = vtk.vtkActor()
    contActor2.SetMapper(contMapper2)

    return contActor, contActor2, outlineActor, contours, contours2
Exemplo n.º 22
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkExtractVOI(),
                                       'Processing.', ('vtkImageData', ),
                                       ('vtkImageData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 23
0
 def initialize (self):
     debug ("In ExtractGrid::__init__ ()")
     self.fil = vtk.vtkExtractVOI()
     self.dim = [0,0,0]
     self._set_input()
     self.fil.UpdateWholeExtent()
     self.fil.Update ()
     self.voi_slider = []
     self.sr_slider = []
Exemplo n.º 24
0
    def _MakeXYActors(self, reduce=1):
        # get a texture-mapped actor
        extent = self._ImageReslice.GetOutputExtent()
        origin = self._ImageReslice.GetOutputOrigin()
        spacing = self._ImageReslice.GetOutputSpacing()

        bounds = [
            origin[0] + spacing[0] * (extent[0] - 0.5),
            origin[0] + spacing[0] * (extent[1] + 0.5),
            origin[1] + spacing[1] * (extent[2] - 0.5),
            origin[1] + spacing[1] * (extent[3] + 0.5),
            origin[2] + spacing[2] * (extent[4] - 0.5),
            origin[2] + spacing[2] * (extent[5] + 0.5)
        ]

        for sliceNumber in range(extent[4], old_div((extent[5] + 1), reduce)):
            # the z position of the slice
            z = origin[2] + reduce * sliceNumber * spacing[2]

            plane = vtk.vtkPlaneSource()
            plane.SetXResolution(1)
            plane.SetYResolution(1)
            plane.SetOrigin(bounds[0], bounds[2], z)
            plane.SetPoint1(bounds[1], bounds[2], z)
            plane.SetPoint2(bounds[0], bounds[3], z)

            imageClip = vtk.vtkExtractVOI()
            imageClip.SetInput(self._ImageToStructuredPoints.GetOutput())
            imageClip.SetVOI(extent[0], extent[1], extent[2], extent[3],
                             reduce * sliceNumber, reduce * sliceNumber)
            imageClip.ReleaseDataFlagOn()

            texture = vtk.vtkTexture()
            texture.SetQualityTo32Bit()
            texture.SetInput(imageClip.GetOutput())
            texture.RepeatOff()
            texture.InterpolateOn()
            texture.MapColorScalarsThroughLookupTableOff()

            for i in range(3):
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(plane.GetOutput())
                mapper.SetClippingPlanes(self._ClippingPlanes[i])

                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.SetTexture(texture)
                actor.PickableOff()
                actor.SetProperty(self._PropertyXY)

                self._PlanesXY.append(plane)
                self._ImageClipsXY.append(imageClip)
                self._ActorsXY.append(actor)

        numberOfPlanes = (extent[5] - extent[4] + 1) / reduce * 3
        return self._ActorsXY[-numberOfPlanes:]
    def _MakeXYActors(self, reduce=1):
        # get a texture-mapped actor
        extent = self._ImageReslice.GetOutputExtent()
        origin = self._ImageReslice.GetOutputOrigin()
        spacing = self._ImageReslice.GetOutputSpacing()

        bounds = [origin[0] + spacing[0] * (extent[0] - 0.5),
                  origin[0] + spacing[0] * (extent[1] + 0.5),
                  origin[1] + spacing[1] * (extent[2] - 0.5),
                  origin[1] + spacing[1] * (extent[3] + 0.5),
                  origin[2] + spacing[2] * (extent[4] - 0.5),
                  origin[2] + spacing[2] * (extent[5] + 0.5)]

        for sliceNumber in range(extent[4], old_div((extent[5] + 1), reduce)):
            # the z position of the slice
            z = origin[2] + reduce * sliceNumber * spacing[2]

            plane = vtk.vtkPlaneSource()
            plane.SetXResolution(1)
            plane.SetYResolution(1)
            plane.SetOrigin(bounds[0], bounds[2], z)
            plane.SetPoint1(bounds[1], bounds[2], z)
            plane.SetPoint2(bounds[0], bounds[3], z)

            imageClip = vtk.vtkExtractVOI()
            imageClip.SetInput(self._ImageToStructuredPoints.GetOutput())
            imageClip.SetVOI(extent[0], extent[1],
                             extent[2], extent[3],
                             reduce * sliceNumber, reduce * sliceNumber)
            imageClip.ReleaseDataFlagOn()

            texture = vtk.vtkTexture()
            texture.SetQualityTo32Bit()
            texture.SetInput(imageClip.GetOutput())
            texture.RepeatOff()
            texture.InterpolateOn()
            texture.MapColorScalarsThroughLookupTableOff()

            for i in range(3):
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(plane.GetOutput())
                mapper.SetClippingPlanes(self._ClippingPlanes[i])

                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.SetTexture(texture)
                actor.PickableOff()
                actor.SetProperty(self._PropertyXY)

                self._PlanesXY.append(plane)
                self._ImageClipsXY.append(imageClip)
                self._ActorsXY.append(actor)

        numberOfPlanes = (extent[5] - extent[4] + 1) / reduce * 3
        return self._ActorsXY[-numberOfPlanes:]
Exemplo n.º 26
0
def ipl_add_aims(image_in1, image_in2):
    ipl_add_aims_settings()

    extent1 = image_in1.GetExtent()

    voi1 = vtk.vtkExtractVOI()
    voi1.SetInput(image_in1)
    voi1.SetVOI(extent1[0], extent1[1], extent1[2], extent1[3], extent1[4],
                extent1[5])

    extent2 = image_in2.GetExtent()

    voi2 = vtk.vtkExtractVOI()
    voi2.SetInput(image_in2)
    voi2.SetVOI(extent2[0], extent2[1], extent2[2], extent2[3], extent2[4],
                extent2[5])

    shift1 = vtk.vtkImageShiftScale()
    shift1.SetInputConnection(voi1.GetOutputPort())
    shift1.SetOutputScalarTypeToChar()
    shift1.Update()

    shift2 = vtk.vtkImageShiftScale()
    shift2.SetInputConnection(voi2.GetOutputPort())
    shift2.SetOutputScalarTypeToChar()
    shift2.Update()

    add = vtk.vtkImageMathematics()
    add.SetInput1(shift1.GetOutput())
    add.SetInput2(shift2.GetOutput())
    add.SetOperationToAdd()
    add.Update()

    temp = vtk.vtkImageMathematics()
    temp.SetInput1(add.GetOutput())
    temp.SetConstantC(-2)
    temp.SetConstantK(127)
    temp.SetOperationToReplaceCByK()
    temp.Update()

    image_out = temp.GetOutput()
    return image_out
Exemplo n.º 27
0
def ExtractVOI(imagedata, xi, xf, yi, yf, zi, zf):
    """
    Cropping the vtkImagedata according
    with values.
    """
    voi = vtk.vtkExtractVOI()
    voi.SetVOI(xi, xf, yi, yf, zi, zf)
    voi.SetInput(imagedata)
    voi.SetSampleRate(1, 1, 1)
    voi.Update()
    return voi.GetOutput()
Exemplo n.º 28
0
def ExtractVOI(imagedata,xi,xf,yi,yf,zi,zf):
    """
    Cropping the vtkImagedata according
    with values.
    """
    voi = vtk.vtkExtractVOI()
    voi.SetVOI(xi,xf,yi,yf,zi,zf)
    voi.SetInputData(imagedata)
    voi.SetSampleRate(1, 1, 1)
    voi.Update()
    return voi.GetOutput()
Exemplo n.º 29
0
    def updateRendering(self):
        """
		Update the Rendering of this module
		"""
        data = self.getInput(1)
        x, y, z = self.dataUnit.getDimensions()
        data = optimize.optimize(image=data,
                                 updateExtent=(0, x - 1, 0, y - 1, 0, z - 1))
        if data.GetNumberOfScalarComponents() > 3:
            extract = vtk.vtkImageExtractComponents()
            extract.SetInput(data)
            extract.SetComponents(1, 1, 1)
            data = extract.GetOutput()
        if data.GetNumberOfScalarComponents() > 1:
            self.luminance.SetInput(data)
            data = self.luminance.GetOutput()

        z = self.parameters["Slice"]
        ext = (0, x - 1, 0, y - 1, z, z)

        voi = vtk.vtkExtractVOI()
        voi.SetVOI(ext)
        voi.SetInput(data)
        slice = voi.GetOutput()
        self.geometry.SetInput(slice)

        self.warp.SetInput(self.geometry.GetOutput())
        self.warp.SetScaleFactor(self.parameters["Scale"])
        self.merge.SetGeometry(self.warp.GetOutput())

        if slice.GetNumberOfScalarComponents() == 1:
            maptocol = vtk.vtkImageMapToColors()
            ctf = self.getInputDataUnit(1).getColorTransferFunction()
            maptocol.SetInput(slice)
            maptocol.SetLookupTable(ctf)
            maptocol.Update()
            scalars = maptocol.GetOutput()
        else:
            scalars = slice

        self.merge.SetScalars(scalars)
        data = self.merge.GetOutput()

        if self.parameters["Normals"]:
            self.normals.SetInput(data)
            self.normals.SetFeatureAngle(self.parameters["FeatureAngle"])
            print "Feature angle=", self.parameters["FeatureAngle"]
            data = self.normals.GetOutput()

        self.mapper.SetInput(data)
        self.mapper.Update()
        VisualizationModule.updateRendering(self)
        self.parent.Render()
Exemplo n.º 30
0
    def initialize_pipeline(self):
        """ Set up the necessary VTK classes for the pipeline, and the color of the contours"""

        for i in range(self.nr_doseplans):
            self.extracts_axial["c{0}".format(i)] = vtk.vtkExtractVOI()
            self.contours_axial["c{0}".format(i)] = vtk.vtkContourFilter()
            self.contour_mappers_axial["c{0}".format(
                i)] = vtk.vtkPolyDataMapper()
            self.contour_actors_axial["c{0}".format(i)] = vtk.vtkActor()
            self.contour_actors_axial["c{0}".format(i)].GetProperty().SetColor(
                0, 1, 0)
            self.contour_actors_axial["c{0}".format(
                i)].GetProperty().SetLineWidth(2)

            self.extracts_sagittal["c{0}".format(i)] = vtk.vtkExtractVOI()
            self.contours_sagittal["c{0}".format(i)] = vtk.vtkContourFilter()
            self.contour_mappers_sagittal["c{0}".format(
                i)] = vtk.vtkPolyDataMapper()
            self.contour_actors_sagittal["c{0}".format(i)] = vtk.vtkActor()
            self.contour_actors_sagittal["c{0}".format(
                i)].GetProperty().SetColor(0, 1, 0)
            self.contour_actors_sagittal["c{0}".format(
                i)].GetProperty().SetLineWidth(2)

            self.extracts_coronal["c{0}".format(i)] = vtk.vtkExtractVOI()
            self.contours_coronal["c{0}".format(i)] = vtk.vtkContourFilter()
            self.contour_mappers_coronal["c{0}".format(
                i)] = vtk.vtkPolyDataMapper()
            self.contour_actors_coronal["c{0}".format(i)] = vtk.vtkActor()
            self.contour_actors_coronal["c{0}".format(
                i)].GetProperty().SetColor(0, 1, 0)
            self.contour_actors_coronal["c{0}".format(
                i)].GetProperty().SetLineWidth(2)

            self.extracts_axial["c{0}".format(i)].SetInput(
                self.doseplans["p{0}".format(i)])
            self.extracts_coronal["c{0}".format(i)].SetInput(
                self.doseplans["p{0}".format(i)])
            self.extracts_sagittal["c{0}".format(i)].SetInput(
                self.doseplans["p{0}".format(i)])
	def updateRendering(self):
		"""
		Update the Rendering of this module
		"""
		data = self.getInput(1)
		x,y,z = self.dataUnit.getDimensions()
		data = optimize.optimize(image = data, updateExtent = (0, x-1, 0, y-1, 0, z-1))
		if data.GetNumberOfScalarComponents() > 3:
			extract = vtk.vtkImageExtractComponents()
			extract.SetInput(data)
			extract.SetComponents(1, 1, 1)
			data = extract.GetOutput()
		if data.GetNumberOfScalarComponents() > 1:
			self.luminance.SetInput(data)
			data = self.luminance.GetOutput()
		
		z = self.parameters["Slice"]
		ext = (0, x - 1, 0, y - 1, z, z)

		voi = vtk.vtkExtractVOI()
		voi.SetVOI(ext)
		voi.SetInput(data)
		slice = voi.GetOutput()
		self.geometry.SetInput(slice)         
		
		self.warp.SetInput(self.geometry.GetOutput())
		self.warp.SetScaleFactor(self.parameters["Scale"])		
		self.merge.SetGeometry(self.warp.GetOutput())
		
		if slice.GetNumberOfScalarComponents() == 1:
			maptocol = vtk.vtkImageMapToColors()
			ctf = self.getInputDataUnit(1).getColorTransferFunction()
			maptocol.SetInput(slice)
			maptocol.SetLookupTable(ctf)
			maptocol.Update()
			scalars = maptocol.GetOutput()
		else:
			scalars = slice
			
		self.merge.SetScalars(scalars)
		data = self.merge.GetOutput()
		
		if self.parameters["Normals"]:
			self.normals.SetInput(data)
			self.normals.SetFeatureAngle(self.parameters["FeatureAngle"])
			print "Feature angle=", self.parameters["FeatureAngle"]            
			data = self.normals.GetOutput()
		
		self.mapper.SetInput(data)
		self.mapper.Update()
		VisualizationModule.updateRendering(self)
		self.parent.Render()
Exemplo n.º 32
0
def ImageCropper(Image,X1, X2,Y1,Y2, Z1,Z2):
     CroppedImage = vtk.vtkExtractVOI()
     CroppedImage.SetInputData(Image)
     CroppedImage.SetVOI(X1, X2,Y1,Y2, Z1,Z2)
     CroppedImage.Update()
     writer=vtk.vtkNIFTIImageWriter()
     writer.SetInputConnection(CroppedImage.GetOutputPort())
     writer.SetFileName("CroppedImageout.nii")
     writer.Write()
     reader=vtk.vtkNIFTIImageReader()
     reader.SetFileName("CroppedImageout.nii")
     reader.Update()
     image=reader.GetOutput()
     return(image)
Exemplo n.º 33
0
def extract1Slice(image, slice=30, dir=2):
    voi = vtk.vtkExtractVOI()
    voi.SetInput(image)
    extent = image.GetExtent()
    if dir == 0:
        voi.SetVOI(slice,slice,extent[2],extent[3],extent[4],extent[5])
    if dir == 1:
        voi.SetVOI(extent[0],extent[1],slice,slice,extent[4],extent[5])
    if dir == 2:
        voi.SetVOI(extent[0],extent[1],extent[2],extent[3],slice,slice)
    voi.Update()
    imagedata = voi.GetOutput()
    imagedata.SetOrigin(image.GetOrigin())
    imagedata.Update()
    return imagedata
	def __init__(self):
		"""
		Initialization
		"""        
		lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1))
		self.reportGUI = None
		self.measurements = []
		self.vtkfilter = vtk.vtkExtractVOI()
		self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send)
		lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress)
		self.translation = []
		self.descs = {"UseROI": "Use Region of Interest to define resulting region", \
						"ROI": "Region of Interest Used in Cutting", \
						"FirstSlice": "First Slice in Resulting Stack", \
						"LastSlice": "Last Slice in Resulting Stack"}
		self.filterDesc = "Extracts a subset from a dataset by removing slices from the top and/or bottom and/or by using a ROI to specify the subset in X and Y.\nInput: Any image\nOutput: Extracted image"
Exemplo n.º 35
0
def ipl_write(image_in, output):
    ipl_write_settings(image_in, output)
    print "Writing: ", output
    extent = image_in.GetExtent()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(image_in)
    voi.SetVOI(extent[0], extent[1], extent[2], extent[3], extent[4],
               extent[5])

    writer = vtkn88.vtkn88AIMWriter()
    writer.SetInputConnection(voi.GetOutputPort())
    writer.SetFileName(output)
    writer.Update()

    print "Done"
Exemplo n.º 36
0
    def __init__(self):
        """
		Initialization
		"""
        lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1))
        self.reportGUI = None
        self.measurements = []
        self.vtkfilter = vtk.vtkExtractVOI()
        self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send)
        lib.messenger.connect(self.vtkfilter, 'ProgressEvent',
                              self.updateProgress)
        self.translation = []
        self.descs = {"UseROI": "Use Region of Interest to define resulting region", \
            "ROI": "Region of Interest Used in Cutting", \
            "FirstSlice": "First Slice in Resulting Stack", \
            "LastSlice": "Last Slice in Resulting Stack"}
        self.filterDesc = "Extracts a subset from a dataset by removing slices from the top and/or bottom and/or by using a ROI to specify the subset in X and Y.\nInput: Any image\nOutput: Extracted image"
def getSlice(volume, zslice, startpos=None, endpos=None):
    """
	Extract a given slice from a volume
	"""
    voi = vtk.vtkExtractVOI()
    voi.SetInputConnection(volume.GetProducerPort())
    if startpos:
        startx, starty = startpos
        endx, endy = endpos
    else:
        # startx, starty = 0, 0
        # endx, endy = volume.GetDimensions()[0:2]
        startx, endx, starty, endy, a, b = volume.GetExtent()

    voi.SetVOI((int(startx), int(endx), int(starty), int(endy), int(zslice), int(zslice)))
    voi.Update()
    data = voi.GetOutput()
    return data
Exemplo n.º 38
0
def ipl_median_filter(image_in, support):
    ipl_median_filter_settings(support)

    extent = image_in.GetExtent()

    voi = vtk.vtkExtractVOI()
    voi.SetInput(image_in)
    voi.SetVOI(extent[0] + support, extent[1] - support, extent[2] + support,
               extent[3] - support, extent[4] + support, extent[5] - support)
    voi.Update()

    median = vtk.vtkImageMedian3D()
    median.SetKernelSize(support, support, support)
    median.SetInputConnection(voi.GetOutputPort())
    median.Update()

    image_out = median.GetOutput()
    return image_out
Exemplo n.º 39
0
    def getTimepoint(self, n, onlyDims=0):
        """
		Return the nth timepoint
		"""
        if not self.readers:
            self.getReadersFromFilenames()

        if self.is3DImage():
            if not self.readers:
                raise Logging.GUIError(
                    "Attempt to read bad timepoint",
                    "Timepoint %d is not defined by the given filenames" % n)
            self.reader = self.readers[0]
            minZ = n * self.slicesPerTimepoint
            maxZ = (n + 1) * self.slicesPerTimepoint - 1
            extract = vtk.vtkExtractVOI()
            extract.SetInput(self.reader.GetOutput())
            extract.SetVOI(0, self.x - 1, 0, self.y - 1, minZ, maxZ)
            changeInfo = vtk.vtkImageChangeInformation()
            changeInfo.SetInput(extract.GetOutput())
            changeInfo.SetOutputOrigin(0, 0, 0)
            changeInfo.SetExtentTranslation((0, 0, -minZ))
            data = changeInfo.GetOutput()
        else:
            if n >= len(self.readers):
                n = 0
                raise Logging.GUIError(
                    "Attempt to read bad timepoint",
                    "Timepoint %d is not defined by the given filenames" % n)

            self.reader = self.readers[n]
            data = self.reader.GetOutput()

        if not self.voxelsize:
            size = data.GetSpacing()
            x, y, z = [size.GetElement(x) for x in range(0, 3)]
            self.voxelsize = (x, y, z)
            print "Read voxel size", self.voxelsize

        if onlyDims:
            return

        return data
Exemplo n.º 40
0
def getSlice(volume, zslice, startpos=None, endpos=None):
    """
	Extract a given slice from a volume
	"""
    voi = vtk.vtkExtractVOI()
    voi.SetInputConnection(volume.GetProducerPort())
    if startpos:
        startx, starty = startpos
        endx, endy = endpos
    else:
        #startx, starty = 0, 0
        #endx, endy = volume.GetDimensions()[0:2]
        startx, endx, starty, endy, a, b = volume.GetExtent()

    voi.SetVOI((int(startx), int(endx), int(starty), int(endy), int(zslice),
                int(zslice)))
    voi.Update()
    data = voi.GetOutput()
    return data
Exemplo n.º 41
0
 def _set_input (self):        
     """ This function tries its best to use an appropriate filter
     for the given input data."""        
     debug ("In ExtractGrid::_set_input ()")
     out = self.prev_fil.GetOutput ()
     dim = out.GetDimensions ()
     self.dim = [dim[0] -1, dim[1] -1, dim[2] -1]
     if out.IsA ('vtkStructuredGrid'):
         f = vtk.vtkExtractGrid()
     elif out.IsA ('vtkRectilinearGrid'):
         f = vtk.vtkExtractRectilinearGrid()
     elif out.IsA ('vtkStructuredPoints') or out.IsA('vtkImageData'):
         f = vtk.vtkExtractVOI()
     else:
         msg = "This module does not support the given "\
               "output - %s "%(out.GetClassName ())
         raise Base.Objects.ModuleException, msg
     if f.GetClassName() != self.fil.GetClassName():
         self.fil = f
     self.fil.SetInput (out)
Exemplo n.º 42
0
    def ExtractVOI(self):

        wholeExtent = self.Image.GetExtent()
        origin = self.Image.GetOrigin()
        spacing = self.Image.GetSpacing()

        newVOI = [0,0,0,0,0,0]
        newVOI[0] = max(wholeExtent[0],int(math.ceil((self.BoxBounds[0]-origin[0])/spacing[0])))
        newVOI[1] = min(wholeExtent[1],int(math.floor((self.BoxBounds[1]-origin[0])/spacing[0])))
        newVOI[2] = max(wholeExtent[2],int(math.ceil((self.BoxBounds[2]-origin[1])/spacing[1])))
        newVOI[3] = min(wholeExtent[3],int(math.floor((self.BoxBounds[3]-origin[1])/spacing[1])))
        newVOI[4] = max(wholeExtent[4],int(math.ceil((self.BoxBounds[4]-origin[2])/spacing[2])))
        newVOI[5] = min(wholeExtent[5],int(math.floor((self.BoxBounds[5]-origin[2])/spacing[2])))

        extractVOI = vtk.vtkExtractVOI()
        extractVOI.SetInputData(self.CroppedImage)
        extractVOI.SetVOI(newVOI)
        extractVOI.Update()

        self.CroppedImage.DeepCopy(extractVOI.GetOutput())
	def getTimepoint(self, n, onlyDims = 0):
		"""
		Return the nth timepoint
		"""
		if not self.readers:
			self.getReadersFromFilenames()

		if self.is3DImage():
			if not self.readers:
				raise Logging.GUIError("Attempt to read bad timepoint", "Timepoint %d is not defined by the given filenames" % n)
			self.reader = self.readers[0]
			minZ = n * self.slicesPerTimepoint
			maxZ = (n+1) * self.slicesPerTimepoint - 1
			extract = vtk.vtkExtractVOI()
			extract.SetInput(self.reader.GetOutput())
			extract.SetVOI(0, self.x - 1, 0, self.y - 1, minZ, maxZ)
			changeInfo = vtk.vtkImageChangeInformation()
			changeInfo.SetInput(extract.GetOutput())
			changeInfo.SetOutputOrigin(0, 0, 0)
			changeInfo.SetExtentTranslation((0,0,-minZ))
			data = changeInfo.GetOutput()
		else:
			if n >= len(self.readers):
				n = 0
				raise Logging.GUIError("Attempt to read bad timepoint", "Timepoint %d is not defined by the given filenames" % n)
			
			self.reader = self.readers[n]
			data = self.reader.GetOutput()

		if not self.voxelsize:
			size = data.GetSpacing()
			x, y, z = [size.GetElement(x) for x in range(0, 3)]
			self.voxelsize = (x, y, z)
			print "Read voxel size", self.voxelsize

		if onlyDims:
			return
		
		return data
Exemplo n.º 44
0
  def __init__(self, parent=None,type='small'):
    self.type = type
    self.nameSize = 24
    # the currentLayoutName is tag on the slice node that corresponds
    # view which should currently be shown in the DataProbe window.
    # Keeping track of this allows us to respond to non-interactor updates
    # to the slice (like from an external tracker) but only in the view where
    # the mouse has most recently entered.
    self.currentLayoutName = None

    self.CrosshairNode = None
    self.CrosshairNodeObserverTag = None

    self.frame = qt.QFrame(parent)
    self.frame.setLayout(qt.QVBoxLayout())

    modulePath = slicer.modules.dataprobe.path.replace("DataProbe.py","")
    self.iconsDIR = modulePath + '/Resources/Icons'

    self.imageCrop = vtk.vtkExtractVOI()
    self.imageZoom = 10
    self.showImage = False

    self.painter = qt.QPainter()
    self.pen = qt.QPen()

    if type == 'small':
      self.createSmall()


    #Helper class to calculate and display tensor scalars
    self.calculateTensorScalars = CalculateTensorScalars()

    # Observe the crosshair node to get the current cursor position
    self.CrosshairNode = slicer.mrmlScene.GetNthNodeByClass(0, 'vtkMRMLCrosshairNode')
    if self.CrosshairNode:
      self.CrosshairNodeObserverTag = self.CrosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, self.processEvent)
Exemplo n.º 45
0
# coefficients to the equations are set.
quadric = vtk.vtkQuadric()
quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0)

# The vtkSampleFunction uses the quadric function and evaluates function
# value over a regular lattice (i.e., a volume).
sample = vtk.vtkSampleFunction()
sample.SetSampleDimensions(30, 30, 30)
sample.SetImplicitFunction(quadric)
sample.ComputeNormalsOff()
sample.Update()

# Here a single slice (i.e., image) is extracted from the volume. (Note: in
# actuality the VOI request causes the sample function to operate on just the
# slice.)
extract = vtk.vtkExtractVOI()
extract.SetInputConnection(sample.GetOutputPort())
extract.SetVOI(0, 29, 0, 29, 15, 15)
extract.SetSampleRate(1, 2, 3)

# The image is contoured to produce contour lines. Thirteen contour values
# ranging from (0,1.2) inclusive are produced.
contours = vtk.vtkContourFilter()
contours.SetInputConnection(extract.GetOutputPort())
contours.GenerateValues(13, 0.0, 1.2)

# The contour lines are mapped to the graphics library.
contMapper = vtk.vtkPolyDataMapper()
contMapper.SetInputConnection(contours.GetOutputPort())
contMapper.SetScalarRange(0.0, 1.2)
Exemplo n.º 46
0
# to mark the origin
sphere = vtk.vtkSphereSource()
sphere.SetRadius(2.0)

sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereMapper.ImmediateModeRenderingOn()

sphereActor = vtk.vtkActor()
sphereActor.SetMapper(sphereMapper)

rt = vtk.vtkRTAnalyticSource()
rt.SetWholeExtent(-50, 50, -50, 50, 0, 0)

voi = vtk.vtkExtractVOI()
voi.SetInputConnection(rt.GetOutputPort())
voi.SetVOI(-11, 39, 5, 45, 0, 0)
voi.SetSampleRate(5, 5, 1)

# Get rid of ambiguous triagulation issues.
surf = vtk.vtkDataSetSurfaceFilter()
surf.SetInputConnection(voi.GetOutputPort())

tris = vtk.vtkTriangleFilter()
tris.SetInputConnection(surf.GetOutputPort())

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(tris.GetOutputPort())
mapper.ImmediateModeRenderingOn()
mapper.SetScalarRange(130, 280)
Exemplo n.º 47
0
    def init_cell_field_actors_borderless(self, actor_specs, drawing_params=None):

        hex_flag = False
        lattice_type_str = self.get_lattice_type_str()
        if lattice_type_str.lower() == 'hexagonal':
            hex_flag = True

        # todo 5 - check if this should be called earlier
        # self.extractCellFieldData() # initializes self.usedCellTypesList

        field_dim = self.currentDrawingParameters.bsd.fieldDim
        cell_type_image_data = vtk.vtkImageData()

        cell_type_image_data.SetDimensions(field_dim.x + 2, field_dim.y + 2,
                                           field_dim.z + 2)  # adding 1 pixel border around the lattice to make rendering smooth at lattice borders
        cell_type_image_data.GetPointData().SetScalars(self.cell_type_array)
        voi = vtk.vtkExtractVOI()

        if VTK_MAJOR_VERSION >= 6:
            voi.SetInputData(cell_type_image_data)
        else:
            voi.SetInput(cell_type_image_data)

        #        voi.SetVOI(1,self.dim[0]-1, 1,self.dim[1]-1, 1,self.dim[2]-1 )  # crop out the artificial boundary layer that we created
        voi.SetVOI(0, 249, 0, 189, 0, 170)

        # # todo 5- check if it is possible to call it once
        # self.usedCellTypesList = self.extractCellFieldData()

        number_of_actors = len(self.used_cell_types_list)

        # creating and initializing filters, smoothers and mappers - one for each cell type

        filterList = [vtk.vtkDiscreteMarchingCubes() for i in xrange(number_of_actors)]
        smootherList = [vtk.vtkSmoothPolyDataFilter() for i in xrange(number_of_actors)]
        normalsList = [vtk.vtkPolyDataNormals() for i in xrange(number_of_actors)]
        mapperList = [vtk.vtkPolyDataMapper() for i in xrange(number_of_actors)]

        # actorCounter=0
        # for i in usedCellTypesList:
        for actorCounter, actor_number in enumerate(self.used_cell_types_list):
            # for actorCounter in xrange(len(self.usedCellTypesList)):

            if VTK_MAJOR_VERSION >= 6:
                filterList[actorCounter].SetInputData(cell_type_image_data)
            else:
                filterList[actorCounter].SetInput(cell_type_image_data)

            #            filterList[actorCounter].SetInputConnection(voi.GetOutputPort())

            # filterList[actorCounter].SetValue(0, usedCellTypesList[actorCounter])
            filterList[actorCounter].SetValue(0, self.used_cell_types_list[actorCounter])
            smootherList[actorCounter].SetInputConnection(filterList[actorCounter].GetOutputPort())
            #            smootherList[actorCounter].SetNumberOfIterations(200)
            normalsList[actorCounter].SetInputConnection(smootherList[actorCounter].GetOutputPort())
            normalsList[actorCounter].SetFeatureAngle(45.0)
            mapperList[actorCounter].SetInputConnection(normalsList[actorCounter].GetOutputPort())
            mapperList[actorCounter].ScalarVisibilityOff()

            actors_dict = actor_specs.actors_dict

            cell_type_lut = self.get_type_lookup_table()
            cell_type_lut_max = cell_type_lut.GetNumberOfTableValues() - 1

            if actor_number in actors_dict.keys():
                actor = actors_dict[actor_number]
                actor.SetMapper(mapperList[actorCounter])

                actor.GetProperty().SetDiffuseColor(
                    cell_type_lut.GetTableValue(self.used_cell_types_list[actorCounter])[0:3])

                # actor.GetProperty().SetDiffuseColor(
                #     # self.celltypeLUT.GetTableValue(self.usedCellTypesList[actorCounter])[0:3])
                #     self.celltypeLUT.GetTableValue(actor_number)[0:3])
                if hex_flag:
                    actor.SetScale(self.xScaleHex, self.yScaleHex, self.zScaleHex)
Exemplo n.º 48
0
Arquivo: Coral.py Projeto: kriepy/SVVR
import vtk

reader = vtk.vtkDICOMImageReader()
reader.SetDirectoryName('../Data/1000_KORAALS1/20110617/00006_POLS_0_5_MM')
reader.Update()

imageData = vtk.vtkImageData()
imageData.DeepCopy(reader.GetOutput())

extractor = vtk.vtkExtractVOI()
extractor.SetInput(imageData)
extractor.SetVOI(0,300,0,300,0,300)
extractor.GetVOI()

opacityFunction = vtk.vtkPiecewiseFunction()
opacityFunction.AddPoint(1000, 0.0)
opacityFunction.AddPoint(1400, 0.4)
opacityFunction.AddPoint(1800, 0.0)
opacityFunction.AddPoint(2000, 0.1)
opacityFunction.AddPoint(2400, 0.4)
opacityFunction.AddPoint(2800, 0.0)
colorFunction = vtk.vtkColorTransferFunction()

colorFunction.AddRGBPoint(1400, 0.0, 1.0, 0.0)
colorFunction.AddRGBPoint(2000, 1.0, 0.0, 0.0)
colorFunction.AddRGBPoint(2400, 0.0, 0.0, 1.0)

volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorFunction)
volumeProperty.SetScalarOpacity(opacityFunction)
volumeProperty.SetInterpolationTypeToLinear()
      # colorbar
      # http://www.vtk.org/doc/release/5.8/html/c2_vtk_e_3.html#c2_vtk_e_vtkLookupTable
      scalarBar = vtk.vtkScalarBarActor()
      scalarBar.SetTitle("Temperature")
      scalarBar.SetNumberOfLabels(4)
      scalarBar.SetLookupTable(hueLut)
  
      ## # image viewer
      ## imageViewer.SetInput(vtkTempImage)
      ## imageViewer.SetSize(512,512)
      ## imageViewer.SetSlice(DisplaySlice)
      ## imageViewer.SetPosition(512,0)
      ## imageViewer.Render()

      # extract VOI to display
      extractVOI = vtk.vtkExtractVOI()
      extractVOI.SetInput(vtkTempImage) 
      extractVOI.SetVOI([0,fileHelper.MapDimensions[0],0,fileHelper.MapDimensions[1],DisplaySlice,DisplaySlice]) 
      extractVOI.Update()
      
      # mapper
      #mapper = vtk.vtkDataSetMapper()
      mapper = vtk.vtkImageMapToColors()
      mapper.SetInput(extractVOI.GetOutput())
      # set echo to display
      mapper.SetActiveComponent( options.speciesID )
      mapper.SetLookupTable(hueLut)
  
      # actor
      actor = vtk.vtkImageActor()
      actor.SetInput(mapper.GetOutput())
 def return_vtk_reader(self,data):
     self.reader=vtk.vtkExtractVOI()
     self.reader.SetInput(data)
     #self.reader.SetVOI(data.GetBounds())
     self.reader.Update()
     return self.reader
  def ComputeObjective(self,MRTIDataDirectory,VolumeOfInterest ):
    print self.SEMDataDirectory 
    ObjectiveFunction = 0.0
  
    # loop over time points of interest
    for idwrite,(SEMtimeID,MRTItimeID) in enumerate([(0,135),(0,136),(0,137),(0,138)]):
  
      mrtifilename = '%s/temperature.%04d.vtk' % (MRTIDataDirectory,MRTItimeID) 
      if MRTItimeID in self.DataDictionary:
        print "already loaded",  mrtifilename 
      else:
        print 'opening' , mrtifilename 
        # FIXME vtk needs to be loaded AFTER kernel is built
        import vtk
        import vtk.util.numpy_support as vtkNumPy 
        print "using vtk version", vtk.vtkVersion.GetVTKVersion()
        print "read SEM data"
        vtkImageReader = vtk.vtkDataSetReader() 
        vtkImageReader.SetFileName(mrtifilename )
        vtkImageReader.Update() 
        ## image_cells = vtkImageReader.GetOutput().GetPointData() 
        ## data_array = vtkNumPy.vtk_to_numpy(image_cells.GetArray('scalars')) 
        
        # extract voi for QOI
        vtkVOIExtract = vtk.vtkExtractVOI() 
        vtkVOIExtract.SetInput( vtkImageReader.GetOutput() ) 
        vtkVOIExtract.SetVOI( VolumeOfInterest  ) 
        vtkVOIExtract.Update()
        mrti_point_data= vtkVOIExtract.GetOutput().GetPointData() 
        mrti_array = vtkNumPy.vtk_to_numpy(mrti_point_data.GetArray('image_data')) 
        #print mrti_array
        #print type(mrti_array)
  
        print "project SEM onto MRTI for comparison"
        vtkResample = vtk.vtkCompositeDataProbeFilter()
        vtkResample.SetSource( vtkVOIExtract.GetOutput() )
        vtkResample.SetInput( self.SEMRegister.GetOutput() ) 
        vtkResample.Update()
  
        if ( self.DebugObjective ):
          roifileName = "%s/mrti.%04d.vtu" % (self.SEMDataDirectory,MRTItimeID)
          print "writing ", roifileName 
          start = time.clock()
          # setup mrti projection file
          vtkTemperatureWriter = vtk.vtkXMLUnstructuredGridWriter()
          vtkTemperatureWriter.SetFileName( roifileName )
          vtkTemperatureWriter.SetInput(vtkResample.GetOutput())
          vtkTemperatureWriter.Update()
          elapsed = (time.clock() - start)
          print "write output", elapsed
  
        print " accumulate objective function"
        fem_point_data= vtkResample.GetOutput().GetPointData() 
        self.DataDictionary[MRTItimeID] = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('image_data')) 
        #print fem_array 
        #print type(fem_array )

      h_mrti = self.DataDictionary[MRTItimeID] 
      mf = cl.mem_flags
      d_mrti = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=h_mrti )
      # TODO need to get cl buffer from brainNek
      d_fem  = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=h_mrti )

      # storage for output
      dest_buf = cl.Buffer(self.ctx, mf.WRITE_ONLY, h_mrti.nbytes)

      self.prg.diff_sq(self.queue, h_mrti.shape, None, d_mrti , d_fem , dest_buf)

      mrti_minus_fem_squared = numpy.empty_like(h_mrti)
      cl.enqueue_copy(self.queue, mrti_minus_fem_squared , dest_buf)
      ObjectiveFunction = ObjectiveFunction + mrti_minus_fem_squared.sum()

    return ObjectiveFunction 
Exemplo n.º 52
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """       
        
        if self.input() == None: 
            print>>sys.stderr, "Must supply 'volume' port input to Voxelizer"
            return
              
        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        
        cellData = self.input().GetCellData()  
        pointData = self.input().GetPointData()     
        vectorsArray = pointData.GetVectors()
        
        if vectorsArray == None: 
            print>>sys.stderr, "Must supply point vector data for 'volume' port input to Voxelizer"
            return

        self.setRangeBounds( list( vectorsArray.GetRange(-1) ) )
        self.nComponents = vectorsArray.GetNumberOfComponents()
#        for iC in range(-1,3): print "Value Range %d: %s " % ( iC, str( vectorsArray.GetRange( iC ) ) )
#        for iV in range(10): print "Value[%d]: %s " % ( iV, str( vectorsArray.GetTuple3( iV ) ) )
        
        self.initialOrigin = self.input().GetOrigin()
        self.initialExtent = self.input().GetExtent()
        self.initialSpacing = self.input().GetSpacing()
        self.dataBounds = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing, self.initialOrigin ) 
        metadata = self.getMetadata()  

        self.resample = vtk.vtkExtractVOI()
        self.resample.SetInput( self.input() ) 
        self.resample.SetVOI( self.initialExtent )
        sRate = [ int( round( self.sampleRate[0] )  ), int( round( self.sampleRate[1] ) ), int( round( self.sampleRate[2] ) )  ]
        print "Sample rate: %s " % str( sRate )
        self.resample.SetSampleRate( sRate[0], sRate[1], sRate[2] )

        self.resampled_data = self.resample.GetOutput()
        self.resampled_data.Update()        
        point_data = self.resampled_data.GetPointData() 
        input_variable_data = point_data.GetVectors()
        nComp = input_variable_data.GetNumberOfComponents()
        nTup = input_variable_data.GetNumberOfTuples()
        print "-- Got input data points: nComp=%d, nTup=%d" % ( nComp, nTup ) 
        for iComp in range(nComp):
            cName = input_variable_data.GetComponentName( iComp )        
            variable_point_data = vtk.vtkFloatArray() 
        variable_point_data = input_variable_data

        self.pointCloud = VtkPointCloud(1.0)
        for iPt in range(nTup):           
            point = variable_point_data.GetTuple( iPt )
            self.pointCloud.addPoint( point )
#        self.pointCloud.setPoints( variable_point_data )
        vars = metadata['vars']
        xbounds = metadata[ 'valueRange-'+vars[0] ]
        ybounds = metadata[ 'valueRange-'+vars[1] ]
        zbounds = metadata[ 'valueRange-'+vars[2] ]
        self.pointCloud.setScaling( xbounds, ybounds, zbounds )
        self.pointCloud.dbgprint()
        self.renderer.AddActor( self.pointCloud.vtkActor )
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) 
        self.set3DOutput ( wmod=self.wmod, name="pointcloud" )
 def cut_data_set(self,data_reader,bounds):
     self.cut_reader=vtk.vtkExtractVOI()
     self.cut_reader.SetInput(data_reader.get_data_set())
     self.cut_reader.SetVOI(bounds)
     self.cut_reader.Update()
Exemplo n.º 54
0
import Tkinter
import vtk
from vtk.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor
 
# Prepare to read the file
readerVolume = vtk.vtkImageReader()
readerVolume.SetDataScalarType( vtk.VTK_UNSIGNED_SHORT )
readerVolume.SetFileDimensionality( 3 )
readerVolume.SetDataExtent ( 0,255, 0,255, 0,576)
readerVolume.SetDataSpacing( 1,1,1 )
readerVolume.SetNumberOfScalarComponents( 1 )
readerVolume.SetDataByteOrderToBigEndian()
readerVolume.SetFileName( "./Female.raw" )
 
# Extract the region of interest
voiHead = vtk.vtkExtractVOI()
voiHead.SetInput( readerVolume.GetOutput() )
voiHead.SetVOI( 0,255, 60,255, 0,100 )
voiHead.SetSampleRate( 1,1,1 )
 
# Generate an isosurface
# UNCOMMENT THE FOLLOWING LINE FOR CONTOUR FILTER
# contourBoneHead = vtk.vtkContourFilter()
contourBoneHead = vtk.vtkMarchingCubes()
contourBoneHead.SetInput( voiHead.GetOutput() )
contourBoneHead.ComputeNormalsOn()
contourBoneHead.SetValue( 0, 1250 )  # Bone isovalue
 
# Take the isosurface data and create geometry
geoBoneMapper = vtk.vtkPolyDataMapper()
geoBoneMapper.SetInput( contourBoneHead.GetOutput() )
Exemplo n.º 55
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """       
        self.colorInputModule = self.wmod.forceGetInputFromPort( "colors", None )
        
        if self.input() == None: 
            print>>sys.stderr, "Must supply 'volume' port input to VectorCutPlane"
            return
              
        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        
        cellData = self.input().GetCellData()  
        pointData = self.input().GetPointData()     
        vectorsArray = pointData.GetVectors()
        
        if vectorsArray == None: 
            print>>sys.stderr, "Must supply point vector data for 'volume' port input to VectorVolume"
            return

        self.setRangeBounds( list( vectorsArray.GetRange(-1) ) )
        self.nComponents = vectorsArray.GetNumberOfComponents()
        for iC in range(-1,3): print "Value Range %d: %s " % ( iC, str( vectorsArray.GetRange( iC ) ) )
        for iV in range(10): print "Value[%d]: %s " % ( iV, str( vectorsArray.GetTuple3( iV ) ) )
        
        self.initialOrigin = self.input().GetOrigin()
        self.initialExtent = self.input().GetExtent()
        self.initialSpacing = self.input().GetSpacing()
        self.dataBounds = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing, self.initialOrigin ) 
        dataExtents = ( (self.dataBounds[1]-self.dataBounds[0])/2.0, (self.dataBounds[3]-self.dataBounds[2])/2.0, (self.dataBounds[5]-self.dataBounds[4])/2.0 )
        centroid = ( (self.dataBounds[0]+self.dataBounds[1])/2.0, (self.dataBounds[2]+self.dataBounds[3])/2.0, (self.dataBounds[4]+self.dataBounds[5])/2.0  )
        self.pos = [ self.initialSpacing[i]*self.initialExtent[2*i] for i in range(3) ]
        if ( (self.initialOrigin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0

        self.resample = vtk.vtkExtractVOI()
        self.resample.SetInput( self.input() ) 
        self.resample.SetVOI( self.initialExtent )
        self.ApplyGlyphDecimationFactor()
        lut = self.getLut()
        
        if self.colorInputModule <> None:
            colorInput = self.colorInputModule.getOutput()
            self.color_resample = vtk.vtkExtractVOI()
            self.color_resample.SetInput( colorInput ) 
            self.color_resample.SetVOI( self.initialExtent )
            self.color_resample.SetSampleRate( sampleRate, sampleRate, 1 )
#            self.probeFilter = vtk.vtkProbeFilter()
#            self.probeFilter.SetSourceConnection( self.resample.GetOutputPort() )           
#            colorInput = self.colorInputModule.getOutput()
#            self.probeFilter.SetInput( colorInput )
            resampledColorInput = self.color_resample.GetOutput()
            shiftScale = vtk.vtkImageShiftScale()
            shiftScale.SetOutputScalarTypeToFloat ()           
            shiftScale.SetInput( resampledColorInput ) 
            valueRange = self.getScalarRange()
            shiftScale.SetShift( valueRange[0] )
            shiftScale.SetScale ( (valueRange[1] - valueRange[0]) / 65535 )
            colorFloatInput = shiftScale.GetOutput() 
            colorFloatInput.Update()
            colorInput_pointData = colorFloatInput.GetPointData()     
            self.colorScalars = colorInput_pointData.GetScalars()
            self.colorScalars.SetName('color')
            lut.SetTableRange( valueRange ) 
        
        self.glyph = vtk.vtkGlyph3DMapper() 
#        if self.colorInputModule <> None:   self.glyph.SetColorModeToColorByScalar()            
#        else:                               self.glyph.SetColorModeToColorByVector()          
        scalarRange = self.getScalarRange()
        self.glyph.SetScaleModeToScaleByMagnitude()
        self.glyph.SetColorModeToMapScalars()     
        self.glyph.SetUseLookupTableScalarRange(1)
        self.glyph.SetOrient( 1 ) 
#        self.glyph.ClampingOn()
        self.glyph.SetRange( scalarRange[0:2] )
        self.glyph.SetInputConnection( self.resample.GetOutputPort()  )
        self.arrow = vtk.vtkArrowSource()
        self.glyph.SetSourceConnection( self.arrow.GetOutputPort() )
        self.glyph.SetLookupTable( lut )
        self.glyphActor = vtk.vtkActor() 
        self.glyphActor.SetMapper( self.glyph )
        self.renderer.AddActor( self.glyphActor )
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) 
        self.set3DOutput(wmod=self.wmod) 
Exemplo n.º 56
0
def ComputeObjective(SEMDataDirectory,MRTIDirectory):
  import vtk
  import vtk.util.numpy_support as vtkNumPy 
  print "using vtk version", vtk.vtkVersion.GetVTKVersion()

  ObjectiveFunction = 0.0
  # loop over time points of interest
  for (SEMtimeID,MRTItimeID) in [(1,58)]:
    # read SEM data
    vtkSEMReader = vtk.vtkXMLUnstructuredGridReader()
    vtufileName = "%s/%d.vtu" % (SEMDataDirectory,SEMtimeID)
    vtkSEMReader.SetFileName( vtufileName )
    vtkSEMReader.SetPointArrayStatus("Temperature",1)
    vtkSEMReader.Update()

    # get registration parameters
    variableDictionary = kwargs['cv']

    # register the SEM data to MRTI
    AffineTransform = vtk.vtkTransform()
    AffineTransform.Translate([ 
      variableDictionary['x_displace'],variableDictionary['y_displace'],variableDictionary['z_displace']
                              ])
    # FIXME  notice that order of operations is IMPORTANT
    # FIXME   translation followed by rotation will give different results
    # FIXME   than rotation followed by translation
    # FIXME  Translate -> RotateZ -> RotateY -> RotateX -> Scale seems to be the order of paraview
    AffineTransform.RotateZ(variableDictionary['z_rotate'  ] ) 
    AffineTransform.RotateY(variableDictionary['y_rotate'  ] )
    AffineTransform.RotateX(variableDictionary['x_rotate'  ] )
    AffineTransform.Scale([1.e3,1.e3,1.e3])
    SEMRegister = vtk.vtkTransformFilter()
    SEMRegister.SetInput(vtkSEMReader.GetOutput())
    SEMRegister.SetTransform(AffineTransform)
    SEMRegister.Update()

    # write output
    DebugObjective = True
    if ( DebugObjective ):
       vtkSEMWriter = vtk.vtkDataSetWriter()
       vtkSEMWriter.SetFileTypeToBinary()
       semfileName = "%s/semtransform%04d.vtk" % (SEMDataDirectory,SEMtimeID)
       print "writing ", semfileName 
       vtkSEMWriter.SetFileName( semfileName )
       vtkSEMWriter.SetInput(SEMRegister.GetOutput())
       vtkSEMWriter.Update()

    # load image 
    vtkImageReader = vtk.vtkDataSetReader() 
    vtkImageReader.SetFileName('%s/temperature.%04d.vtk' % (MRTIDirectory, MRTItimeID) )
    vtkImageReader.Update() 
    ## image_cells = vtkImageReader.GetOutput().GetPointData() 
    ## data_array = vtkNumPy.vtk_to_numpy(image_cells.GetArray('scalars')) 
    
    # extract voi for QOI
    vtkVOIExtract = vtk.vtkExtractVOI() 
    vtkVOIExtract.SetInput( vtkImageReader.GetOutput() ) 
    VOI = [110,170,70,120,0,0]
    vtkVOIExtract.SetVOI( VOI ) 
    vtkVOIExtract.Update()
    mrti_point_data= vtkVOIExtract.GetOutput().GetPointData() 
    mrti_array = vtkNumPy.vtk_to_numpy(mrti_point_data.GetArray('image_data')) 
    #print mrti_array
    #print type(mrti_array)

    # project SEM onto MRTI for comparison
    vtkResample = vtk.vtkCompositeDataProbeFilter()
    vtkResample.SetSource( SEMRegister.GetOutput() )
    vtkResample.SetInput( vtkVOIExtract.GetOutput() ) 
    vtkResample.Update()

    # write output
    if ( DebugObjective ):
       vtkTemperatureWriter = vtk.vtkDataSetWriter()
       vtkTemperatureWriter.SetFileTypeToBinary()
       roifileName = "%s/roi%04d.vtk" % (SEMDataDirectory,SEMtimeID)
       print "writing ", roifileName 
       vtkTemperatureWriter.SetFileName( roifileName )
       vtkTemperatureWriter.SetInput(vtkResample.GetOutput())
       vtkTemperatureWriter.Update()

    fem_point_data= vtkResample.GetOutput().GetPointData() 
    fem_array = vtkNumPy.vtk_to_numpy(fem_point_data.GetArray('Temperature')) 
    #print fem_array 
    #print type(fem_array )

    # accumulate objective function
    diff =  mrti_array-fem_array
    diffsq =  diff**2
    ObjectiveFunction = ObjectiveFunction + diffsq.sum()
  return ObjectiveFunction 
Exemplo n.º 57
0
    def Render(self, volumeReader):
        """
        This method attempts to tesselate the image data.
        
        :@type volumeReader: data.imageIO.base.VolumeImageReader
        :@param volumeReader: This object handles opening image data and 
                              passing it to the appropriate VTK image container
        :@rtype: 2-tuple
        :@return: The vtkActor created from tesselated image data and a 
                  vtkLocator for improving picking operations.
        """
        if self.imageSetID is None: return        
        
        self.volumeReader = volumeReader
        self.vtkReader = volumeReader.LoadVTKReader(self.dataSpacing)
        
        # Gaussian Smoothing
        self.gaussFilter = vtk.vtkImageGaussianSmooth()
        self.gaussFilter.SetDimensionality(3)
        self.gaussFilter.SetStandardDeviation(1)
        self.gaussFilter.SetRadiusFactors(1, 1, 1)
        self.gaussFilter.SetInput(self.vtkReader.GetOutput())
        
        # VOI Extractor
        self.voi = vtk.vtkExtractVOI()
        self.voi.SetInputConnection(self.gaussFilter.GetOutputPort())
#        self.voi.SetInputConnection(self.vtkReader.GetOutputPort())
        self.voi.SetVOI(self.volumeReader.VolumeExtents)
        
        # Surface rendering
        self.bactExtractor = vtk.vtkMarchingCubes()
        self.bactExtractor.GenerateValues(1, self.isocontourLevel)
        self.bactExtractor.ComputeNormalsOff()
        self.bactExtractor.SetInputConnection(self.voi.GetOutputPort())

        # surface rendering with dividing cubes
#        self.bactExtractor = vtk.vtkRecursiveDividingCubes()
#        self.bactExtractor.SetInputConnection(self.voi.GetOutputPort())
#        self.bactExtractor.SetValue(self.isocontourLevel[0])
#        self.bactExtractor.SetDistance(0.5)
#        self.bactExtractor.SetIncrement(2)

        # Smooth the mesh
        relaxedMesh = vtk.vtkSmoothPolyDataFilter()
        relaxedMesh.SetNumberOfIterations(50)
        relaxedMesh.SetInput(self.bactExtractor.GetOutput())

        # Calculate normals
        meshNormals = vtk.vtkPolyDataNormals()
        meshNormals.SetFeatureAngle(60.0)
        meshNormals.SetInput(relaxedMesh.GetOutput())

        # Restrip mesh after normal computation
        restrippedMesh = vtk.vtkStripper()
        restrippedMesh.SetInput(meshNormals.GetOutput())
        
        # Convert mesh to graphics primitives
        self.meshMapper = vtk.vtkPolyDataMapper()
        self.meshMapper.ScalarVisibilityOff()
        self.meshMapper.SetInput(restrippedMesh.GetOutput())
        
        # Finally create a renderable object "Actor" 
        # that can be passed to the render window
        self.ibcActor = vtk.vtkActor()
        self.ibcActor.SetMapper(self.meshMapper)
        ibcColor = DataStore.GetImageSet(self.imageSetID).color
        self.ibcActor.GetProperty().SetDiffuseColor(ibcColor.r, ibcColor.g, ibcColor.b)
        self.ibcActor.GetProperty().SetSpecular(.1)
        self.ibcActor.GetProperty().SetSpecularPower(5)
        self.ibcActor.GetProperty().SetOpacity(1)
        self.ibcActor.SetVisibility(boolInt(self.visible))
        
        self.renderer.AddActor(self.ibcActor)
        
        # Optional Locator to help the ray traced picker
        self.bactLocator = vtk.vtkCellLocator()
        self.bactLocator.SetDataSet(restrippedMesh.GetOutput())
        self.bactLocator.LazyEvaluationOn()
        
        return self.bactLocator
Exemplo n.º 58
0
    def init_concentration_field_actors(self, actor_specs, drawing_params=None):
        """
        initializes concentration field actors
        :param actor_specs:
        :param drawing_params:
        :return: None
        """

        actors_dict = actor_specs.actors_dict

        field_dim = self.currentDrawingParameters.bsd.fieldDim
        # dim_order = self.dimOrder(self.currentDrawingParameters.plane)
        # dim = self.planeMapper(dim_order, (field_dim.x, field_dim.y, field_dim.z))# [fieldDim.x, fieldDim.y, fieldDim.z]
        dim = [field_dim.x, field_dim.y, field_dim.z]
        field_name = drawing_params.fieldName
        scene_metadata = drawing_params.screenshot_data.metadata
        mdata = MetadataHandler(mdata=scene_metadata)

        try:
            isovalues = mdata.get('ScalarIsoValues',default=[])
            isovalues = list(map(lambda x: float(x), isovalues))
        except:
            print('Could not process isovalue list ')
            isovalues = []

        try:
            numIsos = mdata.get('NumberOfContourLines',default=3)
        except:
            print('could not process NumberOfContourLines setting')
            numIsos = 0

        hex_flag = False
        lattice_type_str = self.get_lattice_type_str()
        if lattice_type_str.lower() == 'hexagonal':
            hex_flag = True

        import PlayerPython

        types_invisible = PlayerPython.vectorint()
        for type_label in drawing_params.screenshot_data.invisible_types:
            types_invisible.append(int(type_label))

        # self.isovalStr = Configuration.getSetting("ScalarIsoValues", field_name)
        # if type(self.isovalStr) == QVariant:
        #     self.isovalStr = str(self.isovalStr.toString())
        # else:
        #     self.isovalStr = str(self.isovalStr)

        con_array = vtk.vtkDoubleArray()
        con_array.SetName("concentration")
        con_array_int_addr = extract_address_int_from_vtk_object(field_extractor=self.field_extractor, vtkObj=con_array)

        cell_type_con = vtk.vtkIntArray()
        cell_type_con.SetName("concelltype")
        cell_type_con_int_addr = extract_address_int_from_vtk_object(field_extractor=self.field_extractor,
                                                                     vtkObj=cell_type_con)

        field_type = drawing_params.fieldType.lower()
        if field_type == 'confield':
            fill_successful = self.field_extractor.fillConFieldData3D(con_array_int_addr, cell_type_con_int_addr,
                                                                      field_name, types_invisible)
        elif field_type == 'scalarfield':
            fill_successful = self.field_extractor.fillScalarFieldData3D(con_array_int_addr, cell_type_con_int_addr,
                                                                         field_name, types_invisible)
        elif field_type == 'scalarfieldcelllevel':
            fill_successful = self.field_extractor.fillScalarFieldCellLevelData3D(con_array_int_addr,
                                                                                  cell_type_con_int_addr, field_name,
                                                                                  types_invisible)

        if not fill_successful:
            return

        range_array = con_array.GetRange()
        min_con = range_array[0]
        max_con = range_array[1]
        field_max = range_array[1]
        #        print MODULENAME, '  initScalarFieldDataActors(): min,maxCon=',self.minCon,self.maxCon

        min_max_dict = self.get_min_max_metadata(scene_metadata=scene_metadata, field_name=field_name)
        min_range_fixed = min_max_dict['MinRangeFixed']
        max_range_fixed = min_max_dict['MaxRangeFixed']
        min_range = min_max_dict['MinRange']
        max_range = min_max_dict['MaxRange']

        # Note! should really avoid doing a getSetting with each step to speed up the rendering;
        # only update when changed in Prefs
        if min_range_fixed:
            min_con = min_range

        if max_range_fixed:
            max_con = max_range

        uGrid = vtk.vtkStructuredPoints()
        uGrid.SetDimensions(dim[0] + 2, dim[1] + 2, dim[
            2] + 2)  # only add 2 if we're filling in an extra boundary (rf. FieldExtractor.cpp)
        #        uGrid.SetDimensions(self.dim[0],self.dim[1],self.dim[2])
        #        uGrid.GetPointData().SetScalars(self.cellTypeCon)   # cellType scalar field
        uGrid.GetPointData().SetScalars(con_array)
        #        uGrid.GetPointData().AddArray(self.conArray)        # additional scalar field

        voi = vtk.vtkExtractVOI()
        ##        voi.SetInputConnection(uGrid.GetOutputPort())
        #        voi.SetInput(uGrid.GetOutput())

        if VTK_MAJOR_VERSION >= 6:
            voi.SetInputData(uGrid)
        else:
            voi.SetInput(uGrid)

        voi.SetVOI(1, dim[0] - 1, 1, dim[1] - 1, 1,
                   dim[2] - 1)  # crop out the artificial boundary layer that we created

        isoContour = vtk.vtkContourFilter()
        # skinExtractorColor = vtk.vtkDiscreteMarchingCubes()
        # skinExtractorColor = vtk.vtkMarchingCubes()
        #        isoContour.SetInput(uGrid)
        isoContour.SetInputConnection(voi.GetOutputPort())

        isoNum = 0
        for isoNum, isoVal in enumerate(isovalues):
            try:
                isoContour.SetValue(isoNum, isoVal)
            except:
                print MODULENAME, '  initScalarFieldDataActors(): cannot convert to float: ', self.isovalStr[idx]

        if isoNum > 0:
            isoNum += 1

        delIso = (max_con - min_con) / (numIsos + 1)  # exclude the min,max for isovalues
        isoVal = min_con + delIso
        for idx in xrange(numIsos):
            isoContour.SetValue(isoNum, isoVal)
            isoNum += 1
            isoVal += delIso

        # UGLY hack to NOT display anything since our attempt to RemoveActor (below) don't seem to work
        if isoNum == 0:
            isoVal = field_max + 1.0  # go just outside valid range
            isoContour.SetValue(isoNum, isoVal)

        #        concLut = vtk.vtkLookupTable()
        # concLut.SetTableRange(conc_vol.GetScalarRange())
        #        concLut.SetTableRange([self.minCon,self.maxCon])
        self.scalarLUT.SetTableRange([min_con, max_con])
        #        concLut.SetNumberOfColors(256)
        #        concLut.Build()
        # concLut.SetTableValue(39,0,0,0,0)

        #        skinColorMapper = vtk.vtkPolyDataMapper()
        # skinColorMapper.SetInputConnection(skinNormals.GetOutputPort())
        #        self.conMapper.SetInputConnection(skinExtractorColor.GetOutputPort())
        self.conMapper.SetInputConnection(isoContour.GetOutputPort())
        self.conMapper.ScalarVisibilityOn()
        self.conMapper.SetLookupTable(self.scalarLUT)
        # # # print " this is conc_vol.GetScalarRange()=",conc_vol.GetScalarRange()
        # self.conMapper.SetScalarRange(conc_vol.GetScalarRange())
        self.conMapper.SetScalarRange([min_con, max_con])
        # self.conMapper.SetScalarRange(0,1500)

        # rwh - what does this do?
        #        self.conMapper.SetScalarModeToUsePointFieldData()
        #        self.conMapper.ColorByArrayComponent("concentration",0)

        #        print MODULENAME,"initScalarFieldDataActors():  Plotting 3D Scalar field"
        # self.conMapper      = vtk.vtkPolyDataMapper()
        # self.conActor       = vtk.vtkActor()

        concentration_actor = actors_dict['concentration_actor']

        concentration_actor.SetMapper(self.conMapper)

        self.init_min_max_actor(min_max_actor=actors_dict['min_max_text_actor'], range_array=range_array)

        if hex_flag:
            concentration_actor.SetScale(self.xScaleHex, self.yScaleHex, self.zScaleHex)

        if actor_specs.metadata is None:
            actor_specs.metadata = {'mapper': self.conMapper}
        else:
            actor_specs.metadata['mapper'] = self.conMapper

        if mdata.get('LegendEnable',default=False):
            print 'Enabling legend'
            self.init_legend_actors(actor_specs=actor_specs, drawing_params=drawing_params)