Example #1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageClip(), 'Processing.',
         ('vtkImageData',), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
  def captureImageFromView(self, view, filename):
    view.forceRender()
    # qt.QPixmap().grabWidget(...) would not grab the background
    rw = view.renderWindow()
    wti = vtk.vtkWindowToImageFilter()
    wti.SetInput(rw)
    wti.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(filename)
    outputImage = wti.GetOutput()
    imageSize = outputImage.GetDimensions()

    if imageSize[0]<2 or imageSize[1]<2:
      # image is too small, most likely it is invalid
      raise ValueError('Capture image from view failed')

    # Make sure image witdth and height is even, otherwise encoding may fail
    imageWidthOdd = (imageSize[0] & 1 == 1)
    imageHeightOdd = (imageSize[1] & 1 == 1)
    if imageWidthOdd or imageHeightOdd:
      imageClipper = vtk.vtkImageClip()
      imageClipper.SetInputConnection(wti.GetOutputPort())
      extent = outputImage.GetExtent()
      imageClipper.SetOutputWholeExtent(extent[0], extent[1]-1 if imageWidthOdd else extent[1],
                                        extent[2], extent[3]-1 if imageHeightOdd else extent[3],
                                        extent[4], extent[5])
      writer.SetInputConnection(imageClipper.GetOutputPort())
    else:
      writer.SetInputConnection(wti.GetOutputPort())

    writer.Write()
def BuildEditedImage(imagedata, points):
    """
    Editing the original image in accordance with the edit
    points in the editor, it is necessary to generate the
    vtkPolyData via vtkContourFilter
    """
    init_values = None
    for point in points:
        x, y, z = point
        colour = points[point]
        imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour)
        imagedata.Update()

        if not(init_values):
                xi = x
                xf = x
                yi = y
                yf = y
                zi = z
                zf = z
                init_values = 1

        if (xi > x):
            xi = x
        elif(xf < x):
            xf = x

        if (yi > y):
            yi = y
        elif(yf < y):
            yf = y

        if (zi > z):
            zi = z
        elif(zf < z):
            zf = z

    clip = vtk.vtkImageClip()
    clip.SetInput(imagedata)
    clip.SetOutputWholeExtent(xi, xf, yi, yf, zi, zf)
    clip.Update()

    gauss = vtk.vtkImageGaussianSmooth()
    gauss.SetInput(clip.GetOutput())
    gauss.SetRadiusFactor(0.6)
    gauss.Update()

    app = vtk.vtkImageAppend()
    app.PreserveExtentsOn()
    app.SetAppendAxis(2)
    app.SetInput(0, imagedata)
    app.SetInput(1, gauss.GetOutput())
    app.Update()

    return app.GetOutput()
    def RollMap( self, baseImage ):
#        baseImage.Update()
        if self.world_cut  == self.map_cut: return baseImage
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        newCut = self.NormalizeMapLon( self.world_cut )
        delCut = newCut - self.map_cut
#        print "  %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) )
        imageLen = x1 - x0 + 1
        sliceSize =  imageLen * ( delCut / 360.0 )
        sliceCoord = int( round( x0 + sliceSize) )        
        extent = list( baseExtent ) 
        
        extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
        clip0 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
        else:                           clip0.SetInputData( baseImage )                
        clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
        
        extent[0:2] = [ x0 + sliceCoord, x1 ]
        clip1 = vtk.vtkImageClip()
        if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
        else:                           clip1.SetInputData( baseImage )                
        clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
        
        append = vtk.vtkImageAppend()
        append.SetAppendAxis( 0 )
        append.SetInputConnection ( clip1.GetOutputPort() )
        append.AddInputConnection ( clip0.GetOutputPort() )           
        
        imageInfo = vtk.vtkImageChangeInformation()
        imageInfo.SetInputConnection( append.GetOutputPort() ) 
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        
        imageInfo.Update()
        result = imageInfo.GetOutput() 
        return result
Example #5
0
 def RollMap( self, baseImage ):
     baseImage.Update()
     if self.world_cut  == self.map_cut: return baseImage
     baseExtent = baseImage.GetExtent()
     baseSpacing = baseImage.GetSpacing()
     x0 = baseExtent[0]
     x1 = baseExtent[1]
     newCut = NormalizeLon( self.world_cut )
     delCut = NormalizeLon( self.map_cut - newCut )
     imageLen = x1 - x0 + 1
     sliceSize =  imageLen * ( delCut / 360.0 )
     sliceCoord = int( round( x0 + sliceSize) )        
     extent = list( baseExtent ) 
     
     extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
     clip0 = vtk.vtkImageClip()
     clip0.SetInput( baseImage )
     clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
     
     extent[0:2] = [ x0 + sliceCoord, x1 ]
     clip1 = vtk.vtkImageClip()
     clip1.SetInput( baseImage )
     clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
     
     append = vtk.vtkImageAppend()
     append.SetAppendAxis( 0 )
     append.AddInput( clip1.GetOutput() )          
     append.AddInput( clip0.GetOutput() )
     
     imageInfo = vtk.vtkImageChangeInformation()
     imageInfo.SetInputConnection( append.GetOutputPort() ) 
     imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
     imageInfo.SetOutputExtentStart( 0, 0, 0 )
     imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
     
     result = imageInfo.GetOutput() 
     result.Update()
     return result
def SplitIntoSlices(vtkImage):
    vtkImageClip = vtk.vtkImageClip()
    vtkImageClip.SetInput(vtkImage)
    vtkImageClip.ClipDataOn()
    dimensions = vtkImage.GetDimensions()
    slices = []
    for z in range(0, dimensions[2]):
        vtkImageClip.SetOutputWholeExtent(0, dimensions[0], 0, dimensions[1], z, z)
        slice = vtk.vtkImageData()
        vtkImageClip.Update()
        slice.DeepCopy(vtkImageClip.GetOutput())
        slices.append(slice)
    del vtkImageClip
    return slices
Example #7
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._clipper = vtk.vtkImageClip()

        module_utils.setup_vtk_object_progress(self, self._clipper,
                                           'Reading PNG images.')

        self._config.outputWholeExtent = (0,-1,0,-1,0,-1)

        configList = [
            ('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text',
             'The size of the clip volume.')]

        ScriptedConfigModuleMixin.__init__(self, configList)

        self._viewFrame = self._createViewFrame(
            {'Module (self)' : self,
             'vtkImageClip' : self._clipper})

        self.config_to_logic()
        self.syncViewWithLogic()
Example #8
0
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Simple example that used to crash when an UpdateExtent request
# from one algorithm is overwritten by a smaller UpdateExtent
# request from another algorithm.  The COMBINED_UPDATE_EXTENT
# key was added to vtkStreamingDemandDrivenPipeline to fix the
# bug that caused the crash.
# read an image that has an extent of 0 255 0 255 0 0
reader = vtk.vtkPNGReader()
reader.SetDataSpacing(0.8,0.8,1.5)
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png")
# Uncomment this to make the crash disappear
#reader Update
# clip the image down to 0 127 0 127 0 0
clip = vtk.vtkImageClip()
clip.SetInputConnection(reader.GetOutputPort())
clip.SetOutputWholeExtent(0,127,0,127,0,0)
# darken the background
darken = vtk.vtkImageShiftScale()
darken.SetInputConnection(reader.GetOutputPort())
darken.SetScale(0.2)
# do an operation on the clipped and unclipped data
blend = vtk.vtkImageBlend()
blend.SetInputConnection(darken.GetOutputPort())
blend.AddInputConnection(clip.GetOutputPort())
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(blend.GetOutputPort())
viewer.SetColorWindow(2000)
viewer.SetColorLevel(1000)
viewer.Render()
Example #9
0
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create pipeline
#
PIECE = 0
NUMBER_OF_PIECES = 8
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0,63,0,63,1,64)
reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter")
reader.SetDataMask(0x7fff)
reader.SetDataSpacing(1.6,1.6,1.5)
clipper = vtk.vtkImageClip()
clipper.SetInputConnection(reader.GetOutputPort())
clipper.SetOutputWholeExtent(30,36,30,36,30,36)
clipper2 = vtk.vtkImageClip()
clipper2.SetInputConnection(reader.GetOutputPort())
clipper2.SetOutputWholeExtent(30,36,30,36,30,36)
tris = vtk.vtkDataSetTriangleFilter()
tris.SetInputConnection(clipper.GetOutputPort())
tris2 = vtk.vtkDataSetTriangleFilter()
tris2.SetInputConnection(clipper2.GetOutputPort())
geom = vtk.vtkGeometryFilter()
geom.SetInputConnection(tris.GetOutputPort())
pf = vtk.vtkProgrammableFilter()
pf.SetInputConnection(tris2.GetOutputPort())
def remove_ghosts():
    input = pf.GetInput()
Example #10
0
    def testimageMCAll(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # create pipeline
        #
        slc = vtk.vtkStructuredPointsReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk")

        colors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"]

        types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"]

        i = 1
        c = 0
        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        colorWrapper = self.Colors()

        for idx, vtkType in enumerate(types):
            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5)
            i += 5
            cast.append(vtk.vtkImageCast())
            eval('cast[idx].SetOutputScalarTypeTo' + vtkType + '()')
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkMarchingContourFilter())
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].ScalarVisibilityOff()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
        #    actor[idx].Actor.GetProperty().SetDiffuseColor(lindex.colors.c.lindex.colors.c+1.lindex.colors.c+1)
            actor[idx].GetProperty().SetDiffuseColor(colorWrapper.GetRGBColor(colors[c]))
            actor[idx].GetProperty().SetSpecularPower(30)
            actor[idx].GetProperty().SetDiffuse(.7)
            actor[idx].GetProperty().SetSpecular(.5)
            c += 1
            ren.AddActor(actor[idx])


        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.SetBackground(0.9, .9, .9)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        renWin.SetSize(400, 400)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "imageMCAll.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
 def clipInput( self, extent ):
     self.clipper = vtk.vtkImageClip()
     self.clipper.AddInput( self._input )
     self.clipper.SetOutputWholeExtent( extent )
 def clipInput( self, extent ):
     self.clipper = vtk.vtkImageClip()
     if vtk.VTK_MAJOR_VERSION <= 5:  self.clipper.AddInput( self._input )
     else:                           self.clipper.AddInputData( self._input )
     self.clipper.SetOutputWholeExtent( extent )
Example #13
0
    def testContour3DAll(self):

        # On older Macs, 10 is too low. Due to what looks like a driver bug
        # spectral lighting behaves sort of weird and produces small differences
        threshold = 30

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # create pipeline
        #
        slc = vtk.vtkStructuredPointsReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk")

        actorColors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"]

        types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"]

        i = 1
        c = 0

        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        colors = self.Colors()

        for idx, vtkType in enumerate(types):
            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5)

            i += 5

            cast.append(vtk.vtkImageCast())
            eval("cast[idx].SetOutputScalarTypeTo" + vtkType)
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkContourFilter())
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)
            iso[idx].ComputeScalarsOff()
            iso[idx].ComputeGradientsOff()

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].ImmediateModeRenderingOn()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            eval('actor[idx].GetProperty().SetDiffuseColor(colors.GetRGBColor("' + actorColors[idx] + '"))')
            actor[idx].GetProperty().SetSpecularPower(30)
            actor[idx].GetProperty().SetDiffuse(.7)
            actor[idx].GetProperty().SetSpecular(.5)

            c += 3

            ren.AddActor(actor[idx])


        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.SetBackground(0.9, .9, .9)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        renWin.SetSize(400, 400)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()


        img_file = "contour3DAll.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Example #14
0
    def _BuildPipeline(self):
        """_BuildPipeline - Builds the visualization pipeline"""

        image = component.getUtility(ICurrentImage)

        # update image (VTK-6 compatible)
        image.Update()

        # image reslice object
        reslice = vtk.vtkImageReslice()
        reslice.SetInterpolationModeToCubic()
        reslice.ReleaseDataFlagOn()
        reslice.SetInputConnection(image.GetOutputPort())
        if self._transform:
            reslice.SetTransform(self._transform)

        # get extents, spacings, etc
        in_extent = image.GetExtent()
        in_spacing = image.GetSpacing()
        in_origin = image.GetOrigin()

        # get stencil data
        stencil_data = image.GetStencilData()

        # Set image resample factor
        f = self.gui.m_sliderSurfaceQuality.GetValue() / 100.0
        if f == 0.0:
            f = 0.001

        # Set surface decimation factor
        decf = self.gui.m_sliderDecimationFactor.GetValue() / 100.0

        # Enable/Disable stencil usage
        if self.gui.m_checkBoxClipping.GetValue() is True and stencil_data:
            if vtk.vtkVersion().GetVTKMajorVersion() > 5:
                reslice.SetStencilData(stencil_data)
            else:
                reslice.SetStencil(stencil_data)
            reslice.SetBackgroundLevel(image.GetScalarRange()[0])
            ext = stencil_data.GetExtent()
        else:
            ext = in_extent
            if vtk.vtkVersion().GetVTKMajorVersion() > 5:
                reslice.SetStencilData(None)
            else:
                reslice.SetStencil(None)

        # expand extent slightly - account for downsampling later too
        fudge = int(math.ceil(1.0 / f))
        ext = [ext[0] - fudge, ext[1] + fudge, ext[2] - fudge, ext[3] + fudge, ext[4] - fudge, ext[5] + fudge]

        reslice.SetOutputExtent(ext)

        # set default origin/spacing -- these two lines work...
        reslice.SetOutputSpacing(in_spacing)
        reslice.SetOutputOrigin(in_origin)

        # do we need to downsample the image?
        if f < 1.0:
            resample = vtk.vtkImageResample()
            resample.SetInputConnection(reslice.GetOutputPort())
            resample.ReleaseDataFlagOn()
            for i in range(3):
                resample.SetAxisMagnificationFactor(i, f)
            obj = resample
        else:
            obj = reslice

        # do we need to smooth the image?
        if self.gui.m_checkBoxImageSmoothing.GetValue() == True:
            smooth = vtk.vtkImageGaussianSmooth()
            smooth.SetStandardDeviation(1.0)
            smooth.ReleaseDataFlagOn()
            smooth.SetInputConnection(obj.GetOutputPort())
            obj = smooth

        clip = vtk.vtkImageClip()
        clip.SetInputConnection(obj.GetOutputPort())

        # setup contour filter
        cf = vtk.vtkMarchingCubes()
        cf.SetNumberOfContours(1)
        val = float(self.gui.m_textCtrlImageThreshold.GetValue())
        cf.SetValue(0, val)
        cf.SetComputeScalars(0)
        cf.SetComputeNormals(0)
        cf.SetInputConnection(clip.GetOutputPort())

        # decimate surface
        decimate = vtk.vtkDecimatePro()
        decimate.SetInputConnection(cf.GetOutputPort())
        decimate.PreserveTopologyOn()
        decimate.SetTargetReduction(decf)

        # To cut down on memory consumption, we use the clip object
        # to process the image a chunk at a time.  By default we
        # use 20 chunks -- but if the chunks are too small, we'll adjust this
        # number

        clip.UpdateInformation()
        ext = clip.GetInput().GetExtent()

        # main processing loop
        with wx.BusyCursor():
            event.notify(ProgressEvent("Generating surface...", 0.0))
            clip.SetOutputWholeExtent(ext[0], ext[1], ext[2], ext[3], ext[4], ext[5])
            decimate.Update()
            event.notify(ProgressEvent("Generating surface...", 1.0))

        # Create the rendered Geometry
        if not self._app_states[self._current_image_index].GetFactory():
            self._app_states[self._current_image_index].SetFactory(
                vtkAtamai.SurfaceObjectFactory.SurfaceObjectFactory()
            )
            self._app_states[self._current_image_index].GetFactory().SetInputConnection(decimate.GetOutputPort())
            self._app_states[self._current_image_index].GetFactory().SetBackfaceProperty(
                self._app_states[self._current_image_index].GetFactory().GetProperty()
            )
            self._app_states[self._current_image_index].GetFactory().NormalGenerationOn()
        self.SetSurfaceColor()

        self.GetMicroView().pane3D.ConnectActorFactory(self._app_states[self._current_image_index].GetFactory())
        self._app_states[self._current_image_index]._disconnected = False

        # Update math values
        self.UpdateMathValues()
Example #15
0
    def getBoundedMap( self, baseImage, dataLocation, map_cut_size ):
        baseImage.Update()
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        y0 = baseExtent[2]
        y1 = baseExtent[3]
        imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
        selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ]
        dataXLoc = NormalizeLon( dataLocation[0] ) 
        imageInfo = vtk.vtkImageChangeInformation()
        dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
        vertExtent = [ y0, y1 ]
        bounded_dims = None
        if dataYbounds[0] > -90.0:
            yOffset = dataYbounds[0] + 90.0
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[0] = y0 + extOffset
            self.y0 = dataYbounds[0]
        if dataYbounds[1] < 90.0:
            yOffset = 90.0 - dataYbounds[1]
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[1] = y1 - extOffset
                   
        if (( dataXLoc > selectionDim[0] ) and ( dataXLoc < ( 360 - selectionDim[0]) )):

            cut0 = dataXLoc - selectionDim[0] 
            sliceSize =  imageLen[0] * ( cut0 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0] = x0 + sliceCoord - 1
        
            cut1 = dataXLoc + selectionDim[0] 
            sliceSize =  imageLen[0] * ( cut1 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[1] = x0 + sliceCoord
            clip = vtk.vtkImageClip()
            clip.SetInput( baseImage )
            clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            self.x0 = cut0
            bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )

            imageInfo.SetInputConnection( clip.GetOutputPort() ) 
            
        else:
            cut0 = NormalizeLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( cut0 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
            clip0 = vtk.vtkImageClip()
            clip0.SetInput( baseImage )
            clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size0 = extent[1] - extent[0] + 1
        
            cut1 = NormalizeLon( dataLocation[0] - selectionDim[0] )
            sliceSize =  imageLen[0] * ( cut1 / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[0:2] = [ x0 + sliceCoord, x1 ]
            clip1 = vtk.vtkImageClip()
            clip1.SetInput( baseImage )
            clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size1 = extent[1] - extent[0] + 1
            self.x0 = cut1
        
            append = vtk.vtkImageAppend()
            append.SetAppendAxis( 0 )
            append.AddInput( clip1.GetOutput() )          
            append.AddInput( clip0.GetOutput() )
            bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
            
            imageInfo.SetInputConnection( append.GetOutputPort() ) 
            
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        
        result = imageInfo.GetOutput() 
        result.Update()
        return result, bounded_dims
Example #16
0
  def captureImageFromView(self, view, filename):

    slicer.app.processEvents()
    if view:
      view.forceRender()
    else:
      # force rendering of all views
      lm = slicer.app.layoutManager()
      for viewIndex in range(lm.threeDViewCount):
        lm.threeDWidget(0).threeDView().forceRender()
      for sliceViewName in lm.sliceViewNames():
        lm.sliceWidget(sliceViewName).sliceView().forceRender()

    if view is None:
      # no view is specified, capture the entire view layout

      # Simply using grabwidget on the view layout frame would grab the screen without background:
      # img = qt.QPixmap.grabWidget(slicer.app.layoutManager().viewport())

      # Grab the main window and use only the viewport's area
      allViews = slicer.app.layoutManager().viewport()
      topLeft = allViews.mapTo(slicer.util.mainWindow(),allViews.rect.topLeft())
      bottomRight = allViews.mapTo(slicer.util.mainWindow(),allViews.rect.bottomRight())
      imageSize = bottomRight - topLeft

      if imageSize.x()<2 or imageSize.y()<2:
        # image is too small, most likely it is invalid
        raise ValueError('Capture image from view failed')

      # Make sure image witdth and height is even, otherwise encoding may fail
      if (imageSize.x() & 1 == 1):
        imageSize.setX(imageSize.x()-1)
      if (imageSize.y() & 1 == 1):
        imageSize.setY(imageSize.y()-1)

      img = qt.QPixmap.grabWidget(slicer.util.mainWindow(), topLeft.x(), topLeft.y(), imageSize.x(), imageSize.y())
      img.save(filename)
      return

    rw = view.renderWindow()
    wti = vtk.vtkWindowToImageFilter()
    wti.SetInput(rw)
    wti.Update()
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(filename)
    outputImage = wti.GetOutput()
    imageSize = outputImage.GetDimensions()

    if imageSize[0]<2 or imageSize[1]<2:
      # image is too small, most likely it is invalid
      raise ValueError('Capture image from view failed')

    # Make sure image witdth and height is even, otherwise encoding may fail
    imageWidthOdd = (imageSize[0] & 1 == 1)
    imageHeightOdd = (imageSize[1] & 1 == 1)
    if imageWidthOdd or imageHeightOdd:
      imageClipper = vtk.vtkImageClip()
      imageClipper.SetInputConnection(wti.GetOutputPort())
      extent = outputImage.GetExtent()
      imageClipper.SetOutputWholeExtent(extent[0], extent[1]-1 if imageWidthOdd else extent[1],
                                        extent[2], extent[3]-1 if imageHeightOdd else extent[3],
                                        extent[4], extent[5])
      writer.SetInputConnection(imageClipper.GetOutputPort())
    else:
      writer.SetInputConnection(wti.GetOutputPort())

    writer.Write()
Example #17
0
    def testContour2DAll(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # create pipeline
        #
        slc = vtk.vtkSLCReader()
        slc.SetFileName(VTK_DATA_ROOT + "/Data/nut.slc")
        slc.Update()

        types = ["Char", "UnsignedChar", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"]

        i = 3

        clip = list()
        cast = list()
        iso = list()
        mapper = list()
        actor = list()

        for idx, vtkType in enumerate(types):

            clip.append(vtk.vtkImageClip())
            clip[idx].SetInputConnection(slc.GetOutputPort())
            clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i)

            i += 2

            cast.append(vtk.vtkImageCast())
            eval("cast[idx].SetOutputScalarTypeTo" + vtkType)
            cast[idx].SetInputConnection(clip[idx].GetOutputPort())
            cast[idx].ClampOverflowOn()

            iso.append(vtk.vtkContourFilter())
            iso[idx] = vtk.vtkContourFilter()
            iso[idx].SetInputConnection(cast[idx].GetOutputPort())
            iso[idx].GenerateValues(1, 30, 30)

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].SetColorModeToMapScalars()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            ren.AddActor(actor[idx])

        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(slc.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)
        outlineActor.VisibilityOff()
        #
        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(outlineActor)
        ren.ResetCamera()
        ren.GetActiveCamera().SetViewAngle(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Azimuth(20)
        ren.GetActiveCamera().Zoom(1.5)
        ren.ResetCameraClippingRange()

        ren.SetBackground(0.9, .9, .9)
        renWin.SetSize(200, 200)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "contour2DAll.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Example #18
0
    def getBoundedMap( self, baseImage, dataLocation ):
#        print " @@@ MapManager: getBoundedMap "
        baseExtent = baseImage.GetExtent()
        baseSpacing = baseImage.GetSpacing()
        x0 = baseExtent[0]
        x1 = baseExtent[1]
        y0 = baseExtent[2]
        y1 = baseExtent[3]
        imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
        selectionDim = [ self.map_cut_size[0]/2, self.map_cut_size[1]/2 ]
        dataXLoc = dataLocation[0]
        imageInfo = vtk.vtkImageChangeInformation()
        dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
        vertExtent = [ y0, y1 ]
        bounded_dims = None
        if dataYbounds[0] > -90.0:
            yOffset = dataYbounds[0] + 90.0
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[0] = y0 + extOffset
            self.y0 = dataYbounds[0]
        if dataYbounds[1] < 90.0:
            yOffset = 90.0 - dataYbounds[1]
            extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
            vertExtent[1] = y1 - extOffset
            
        overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) )
        if overlapsBorder:
            cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
            clip0 = vtk.vtkImageClip()
            clip0.ClipDataOn()
            clip0.SetInput( baseImage )
            clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size0 = extent[1] - extent[0] + 1
        
            self.x0 = dataLocation[0] - selectionDim[0]
            cut1 = self.NormalizeMapLon( self.x0 ) 
            sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[0:2] = [ x0 + sliceCoord, x1 ]
            clip1 = vtk.vtkImageClip()
            clip1.ClipDataOn()
            if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
            else:                           clip1.SetInputData( baseImage )
            clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            size1 = extent[1] - extent[0] + 1
#            print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) )
        
            append = vtk.vtkImageAppend()
            append.SetAppendAxis( 0 )
            append.AddInputConnection( clip1.GetOutputPort() )              
            append.AddInputConnection( clip0.GetOutputPort() )    
            bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
            
            imageInfo.SetInputConnection( append.GetOutputPort() ) 

        else:
                        
            self.x0 = dataXLoc - selectionDim[0]
            cut0 = self.NormalizeMapLon( self.x0 )
            sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )        
            extent = list( baseExtent )         
            extent[0] = x0 + sliceCoord - 1
        
            cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
            sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 )
            sliceCoord = int( round( x0 + sliceSize) )       
            extent[1] = x0 + sliceCoord
            clip = vtk.vtkImageClip()
            clip.ClipDataOn()
            if vtk.VTK_MAJOR_VERSION <= 5:  clip.SetInput( baseImage )
            else:                           clip.SetInputData( baseImage )
            clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
            bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )
#            print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) )
            clip.Update()
            imageInfo.SetInputConnection( clip.GetOutputPort() ) 
                       
        imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
        imageInfo.SetOutputExtentStart( 0, 0, 0 )
        imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
        imageInfo.Update()
        
        result = imageInfo.GetOutput() 
        return result, bounded_dims
    def Execute(self):

        if self.GaussFiltering:
            gauss = vtk.vtkImageGaussianSmooth()
            gauss.SetInput(self.Image)
            gauss.SetStandardDeviations(self.StandardDeviations)
            gauss.SetRadiusFactors(self.RadiusFactors)
            if self.Shape.find('2d') != -1:
                gauss.SetDimensionality(2)
            elif self.Shape.find('3d') != -1:
                gauss.SetDimensionality(3)
            else:
                gauss.SetDimensionality(3)
            gauss.Update()
            self.Image = gauss.GetOutput()

        scalarRange = [0.0,0.0]
        if self.FWHMRegion == 'image':
            scalarRange = self.Image.GetScalarRange()
        elif self.FWHMRegion == 'midline':
            extent = self.Image.GetWholeExtent()
            newYExtent = extent[2]+(extent[3]-extent[2])/2
            clip = vtk.vtkImageClip()
            clip.SetInput(self.Image)
            clip.SetOutputWholeExtent(extent[0],extent[1],newYExtent,newYExtent,extent[4],extent[5])
            clip.ClipDataOn()
            clip.Update()
            scalarRange = clip.GetOutput().GetScalarRange()

        self.FWHMLevel = (scalarRange[1] - scalarRange[0]) * self.FWHMRatio + scalarRange[0]
        if self.FWHMBackground != None:
            self.FWHMLevel = (scalarRange[1] - self.FWHMBackground) * self.FWHMRatio + self.FWHMBackground

        if self.Method == 'levelsets':
            if self.Shape.find('2d') != -1:
                gradientMagnitude = vtk.vtkImageGradientMagnitude()
                gradientMagnitude.SetDimensionality(2)
            elif self.Shape.find('3d') != -1:
                if self.FeatureImageType == 'gradient':
                    gradientMagnitude = vtkvmtk.vtkvmtkGradientMagnitudeImageFilter()
                elif self.FeatureImageType == 'upwind':
                    gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter()
                    gradientMagnitude.SetUpwindFactor(self.UpwindFactor)
                else:
                    self.PrintError('Unsupported feature image type: choices are "gradient", "upwind".')
                    return
            else:
                gradientMagnitude = vtk.vtkImageGradientMagnitude()
            gradientMagnitude.SetInput(self.Image)
            gradientMagnitude.Update()
            boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter()
            boundedReciprocal.SetInput(gradientMagnitude.GetOutput())
            boundedReciprocal.Update()
            self.FeatureImage = vtk.vtkImageData()
            self.FeatureImage.DeepCopy(boundedReciprocal.GetOutput())
            levelSetsFilter = None
            if self.Shape.find('2d') != -1:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSet2DImageFilter()
            elif self.Shape.find('3d') != -1:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter()
            else:
                levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter()
            levelSetsFilter.SetInput(self.Image)
            levelSetsFilter.SetFeatureImage(boundedReciprocal.GetOutput())
            levelSetsFilter.SetDerivativeSigma(0.0)
            levelSetsFilter.SetAutoGenerateSpeedAdvection(1)
            levelSetsFilter.SetNumberOfIterations(self.LevelSetsIterations)
            levelSetsFilter.SetPropagationScaling(0.0)
            levelSetsFilter.SetCurvatureScaling(self.CurvatureScaling)
            levelSetsFilter.SetAdvectionScaling(1.0)
            levelSetsFilter.SetIsoSurfaceValue(self.FWHMLevel)
            levelSetsFilter.SetInterpolateSurfaceLocation(1)
            levelSetsFilter.SetMaximumRMSError(1E-10)
            levelSetsFilter.Update()

            self.LevelSets = vtk.vtkImageData()
            self.LevelSets.DeepCopy(levelSetsFilter.GetOutput())

            contourFilter = vtk.vtkMarchingContourFilter()
            contourFilter.SetInput(self.LevelSets)
            contourFilter.SetValue(0,0.0)
            contourFilter.Update()

            self.Contour = contourFilter.GetOutput()

        elif self.Method == 'fwhm':
            contourFilter = vtk.vtkMarchingContourFilter()
            contourFilter.SetInput(self.Image)
            contourFilter.SetValue(0,self.FWHMLevel)
            contourFilter.Update()

            self.Contour = contourFilter.GetOutput()
        else:
            self.PrintError('Unsupported method: choices are "levelsets", "fwhm".')
            return


        if self.Smoothing:
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInput(self.Contour)
            smoothingFilter.SetNumberOfIterations(self.SmoothingIterations)
            smoothingFilter.SetPassBand(self.SmoothingPassBand)
            smoothingFilter.Update()
            self.Contour = smoothingFilter.GetOutput()

        measurementFilter = None

        if self.Shape is 'thickplane2d':
            measurementFilter = femri2DPlaneThickness()
        elif self.Shape is 'cylinder2d':
            measurementFilter = femri2DCylinderThickness()
        elif self.Shape is 'hollowcylinder2d':
            measurementFilter = femri2DHollowCylinderThickness()
        elif self.Shape is 'cylinder3d':
            measurementFilter = femri3DCylinderThickness()
        else:
            self.PrintError('Unsupported shape: choices are "thickplane2d", "cylinder2d", "hollowcylinder2d", "cylinder3d".')
            return

        measurementFilter.Contour = self.Contour
        measurementFilter.Center = self.Center
        measurementFilter.TiltingAngle = math.radians(self.TiltingAngle)
        measurementFilter.RotationAngle = math.radians(self.RotationAngle)
        measurementFilter.Execute()

        if self.Shape is 'hollowcylinder2d':
            measurementFilter.ComputeAreas()
            self.InnerArea = measurementFilter.InnerArea
            self.OuterArea = measurementFilter.OuterArea

        self.Thickness = measurementFilter.Thickness
        self.Thickness3D = measurementFilter.Thickness3D
        self.Locations = measurementFilter.Locations

        self.Contour = measurementFilter.Contour
  
        self.OutputText('\n')
        self.OutputText('Thickness: ' + str(self.Thickness) + '\n')
        self.OutputText('Thickness3D: ' + str(self.Thickness3D) + '\n')
        self.OutputText('Locations: ' + str(self.Locations) + '\n')
        if self.Shape is 'hollowcylinder2d':
            self.OutputText('InnerArea: ' + str(self.InnerArea) + '\n')
            self.OutputText('OuterArea: ' + str(self.OuterArea) + '\n')
        self.OutputText('\n')