コード例 #1
0
ファイル: ToolCursorMinc.py プロジェクト: top501/ToolCursor
volumeGradientOpacity = vtk.vtkPiecewiseFunction()
volumeGradientOpacity.AddPoint(0, 0.0)
volumeGradientOpacity.AddPoint(90, 0.5)
volumeGradientOpacity.AddPoint(100, 1.0)

volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(volumeColor)
volumeProperty.SetScalarOpacity(volumeScalarOpacity)
#volumeProperty.SetGradientOpacity(volumeGradientOpacity)
volumeProperty.SetInterpolationTypeToLinear()
volumeProperty.ShadeOff()
volumeProperty.SetAmbient(0.6)
volumeProperty.SetDiffuse(0.6)
volumeProperty.SetSpecular(0.1)

volume = vtk.vtkLODProp3D()
lod2D = volume.AddLOD(volumeMapper2D, volumeProperty, 0.01)
lod3D = volume.AddLOD(volumeMapper3D, volumeProperty, 0.1)
lodRC = volume.AddLOD(volumeMapper, volumeProperty, 1.0)
volume.SetLODLevel(lod2D, 2.0)
volume.SetLODLevel(lod3D, 1.0)
volume.SetLODLevel(lodRC, 0.0)
# disable ray casting
#volume.DisableLOD(lod3D)
volume.DisableLOD(lodRC)

cropOutlineSource = vtk.vtkVolumeOutlineSource()
cropOutlineSource.SetVolumeMapper(volumeMapper)
cropOutlineSource.GenerateScalarsOn()
cropOutlineSource.SetActivePlaneId(0)
コード例 #2
0
ファイル: ToolCursorMinc.py プロジェクト: Atamai/tactics
volumeGradientOpacity = vtk.vtkPiecewiseFunction()
volumeGradientOpacity.AddPoint(0,0.0)
volumeGradientOpacity.AddPoint(90,0.5)
volumeGradientOpacity.AddPoint(100,1.0)

volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(volumeColor)
volumeProperty.SetScalarOpacity(volumeScalarOpacity)
#volumeProperty.SetGradientOpacity(volumeGradientOpacity)
volumeProperty.SetInterpolationTypeToLinear()
volumeProperty.ShadeOff()
volumeProperty.SetAmbient(0.6)
volumeProperty.SetDiffuse(0.6)
volumeProperty.SetSpecular(0.1)

volume = vtk.vtkLODProp3D()
lod2D = volume.AddLOD(volumeMapper2D, volumeProperty, 0.01)
lod3D = volume.AddLOD(volumeMapper3D, volumeProperty, 0.1)
lodRC = volume.AddLOD(volumeMapper, volumeProperty, 1.0)
volume.SetLODLevel(lod2D, 2.0)
volume.SetLODLevel(lod3D, 1.0)
volume.SetLODLevel(lodRC, 0.0)
# disable ray casting
#volume.DisableLOD(lod3D)
volume.DisableLOD(lodRC)

cropOutlineSource = vtk.vtkVolumeOutlineSource()
cropOutlineSource.SetVolumeMapper(volumeMapper)
cropOutlineSource.GenerateScalarsOn()
cropOutlineSource.SetActivePlaneId(0)
コード例 #3
0
colorTransferFunction.SetColorSpaceToHSV()
# Create properties, mappers, volume actors, and ray cast function
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorTransferFunction)
volumeProperty.SetScalarOpacity(opacityTransferFunction)
volumeProperty.SetInterpolationTypeToLinear()
volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
volumeMapper.SetInputConnection(reader.GetOutputPort())
sphereSource = vtk.vtkSphereSource()
sphereSource.SetCenter(25, 25, 25)
sphereSource.SetRadius(30)
sphereSource.SetThetaResolution(15)
sphereSource.SetPhiResolution(15)
geoMapper = vtk.vtkPolyDataMapper()
geoMapper.SetInputConnection(sphereSource.GetOutputPort())
lod = vtk.vtkLODProp3D()
geoID = lod.AddLOD(geoMapper, 0.0)
volID = lod.AddLOD(volumeMapper, volumeProperty, 0.0)
property = vtk.vtkProperty()
property.SetColor(1, 0, 0)
lod.SetLODProperty(geoID, property)
# Okay now the graphics stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(256, 256)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
ren1.GetCullers().InitTraversal()
culler = ren1.GetCullers().GetNextItem()
culler.SetSortingStyleToBackToFront()
コード例 #4
0
ファイル: viz.viewCube.py プロジェクト: jiahao/openqube
def RenderCubeInVTK(filename = 'test.cube', mindatum = 0.0, maxdatum = 0.0):
    global renWin

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #######################
    # Read in Gaussian cube
    #######################

    CubeData = vtk.vtkGaussianCubeReader()
    CubeData.SetFileName(filename)

    CubeData.Update()

    #Get intrinsic scale from data
    scale = sum([x**2 for x in CubeData.GetTransform().GetScale()])

    CubeData.SetHBScale(scale) #scaling factor to compute bonds with hydrogens
    CubeData.SetBScale(scale)  #scaling factor for other bonds

    CubeData.Update()

    ###################
    #Calculate scalings

    #VTK only knows how to render integer data in the interval [0,255] or [0,65535]
    #Here, we calculate scaling factors to map the cube data to the interval.

    if mindatum == maxdatum == 0.0:
        if DEBUG:
            print "Autodetecting range"
            mindatum, maxdatum = CubeData.GetGridOutput().GetPointData().GetScalars().GetRange()

    # Find the remapped value that corresponds to zero
    zeropoint = int(2**ColorDepth*(-mindatum)/(maxdatum-mindatum))
    absmaxdatum = max(-mindatum, maxdatum)

    maxnegativeintensity = min(1.0, 1.0 - (absmaxdatum - abs(mindatum))/absmaxdatum)
    minnegativeintensity = 0.0
    if zeropoint < 0:
        minpositiveintensity = - zeropoint/(2**ColorDepth*absmaxdatum)
    else:
        minpositiveintensity = 0.0
        maxpositiveintensity = min(1.0, 1.0 - (absmaxdatum - abs(maxdatum))/absmaxdatum)
    if DEBUG:
        print "Range plotted = [%f,%f]" % (mindatum, maxdatum)
        print "Negative colors = [0,%d)" % max(0,zeropoint)
        print "Negative intensities = [%f,%f]" % (maxnegativeintensity,minnegativeintensity)
        print "Positive colors = (%d,%d)" % (max(0,zeropoint), 2**ColorDepth)
        print "Positive intensities = [%f,%f]" % (minpositiveintensity,maxpositiveintensity)
        print "On this scale, zero = %d" % zeropoint

    ################################
    # Calculate opacity transfer map

    #The code here differentiates between two cases:
    #1. the scalar data are all positive, so it's just a simple linear ramp
    #2. the scalar data are signed, so do two linear ramps

    opacityTransferFunction = vtk.vtkPiecewiseFunction()

    if zeropoint < 0:
        opacityTransferFunction.AddPoint(        0, minpositiveintensity)
    else:
        opacityTransferFunction.AddPoint(        0, maxnegativeintensity)
        opacityTransferFunction.AddPoint(zeropoint, 0.0)

    opacityTransferFunction.AddPoint(2**ColorDepth-1, maxpositiveintensity)
    opacityTransferFunction.ClampingOn()

    ###########################
    # Create color transfer map

    colorTransferFunction = vtk.vtkColorTransferFunction()

    r1, g1, b1 = NegativeColor
    r2, g2, b2 = PositiveColor
    r0, g0, b0 = BackgroundColor

    if zeropoint < 0:
        colorTransferFunction.AddRGBPoint(          0, r1, g1, b1)
    else:
        colorTransferFunction.AddRGBPoint(          0, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint-1, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint  , r0, g0, b0)
        colorTransferFunction.AddRGBPoint(zeropoint+1, r2, g2, b2)
    colorTransferFunction.AddRGBPoint(2**ColorDepth-1, r2, g2, b2)

    ########################
    # Now apply the scalings

    ScaledData = vtk.vtkImageShiftScale()
    ScaledData.SetInput(CubeData.GetGridOutput())
    ScaledData.SetShift(-mindatum)
    ScaledData.SetScale((2**ColorDepth-1)/(maxdatum-mindatum))

    if ColorDepth == 16:
        ScaledData.SetOutputScalarTypeToUnsignedShort()
    elif ColorDepth == 8:
        ScaledData.SetOutputScalarTypeToUnsignedChar()
    else:
        print
        print "Error! Unsupported color depth given"
        print
        print "valid values are 8 or 16"
        print
        raise ValueError

    ###############################
    # Form combined coloring scheme

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorTransferFunction)
    volumeProperty.SetScalarOpacity(opacityTransferFunction)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()

    # The mapper / ray cast function know how to render the data
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()

    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInput(ScaledData.GetOutput())

    #Create a coarse representation
    #Actually a fake - won't display anything

    compositeFunction2 = vtk.vtkVolumeRayCastIsosurfaceFunction()
    compositeFunction2.SetIsoValue(2**ColorDepth-1)

    volumeMapperCoarse = vtk.vtkVolumeRayCastMapper()
    volumeMapperCoarse.SetVolumeRayCastFunction(compositeFunction2)
    volumeMapperCoarse.SetInput(ScaledData.GetOutput())

    # Create volumetric object to be rendered
    # Use level of detail prop so that it won't take forever to look around

    volume = vtk.vtkLODProp3D()
    id1 = volume.AddLOD(volumeMapper, volumeProperty, 0.)
    volume.SetLODProperty(id1, volumeProperty)
    id2 = volume.AddLOD(volumeMapperCoarse, volumeProperty, 0.)
    volume.SetLODProperty(id2, volumeProperty)

    # At this point, we can position and orient the volume

    #################################
    # End of volumetric data pipeline
    #################################

    #########
    #Contours
    #########

    contour = vtk.vtkContourFilter()
    contour.SetInput(CubeData.GetGridOutput())
    contour.SetNumberOfContours(1)
    contour.SetValue(0, 0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInput(contour.GetOutput())
    contourMapper.SetScalarRange(0,0)
    contourMapper.GetLookupTable().SetNumberOfTableValues(1)
    r0, g0, b0 = NodeColor
    contourMapper.GetLookupTable().SetTableValue(0, r0, g0, b0, NodeAlpha)

    contourActor = vtk.vtkLODActor()
    contourActor.SetMapper(contourMapper)
    contourActor.GetProperty().SetOpacity(NodeAlpha)

    ##########################################
    # Create a wireframe outline of the volume
    ##########################################

    frame = vtk.vtkOutlineFilter()
    frame.SetInput(CubeData.GetGridOutput())

    frameMapper = vtk.vtkPolyDataMapper()
    frameMapper.SetInput(frame.GetOutput())

    frameActor = vtk.vtkLODActor()
    frameActor.SetMapper(frameMapper)
    frameActor.GetProperty().SetColor(FrameColor)
    frameActor.GetProperty().SetOpacity(FrameAlpha)

    ######################
    # Draw balls for atoms
    ######################

    Sphere = vtk.vtkSphereSource()
    Sphere.SetThetaResolution(16)
    Sphere.SetPhiResolution(16)
    Sphere.SetRadius(0.4)

    Glyph = vtk.vtkGlyph3D()
    Glyph.SetInput(CubeData.GetOutput())
    Glyph.SetColorMode(1)
    Glyph.SetColorModeToColorByScalar()
    Glyph.SetScaleModeToScaleByVectorComponents()
    Glyph.SetSource(Sphere.GetOutput())

    AtomsMapper = vtk.vtkPolyDataMapper()
    AtomsMapper.SetInput(Glyph.GetOutput())
    AtomsMapper.SetImmediateModeRendering(1)
    AtomsMapper.UseLookupTableScalarRangeOff()
    AtomsMapper.SetScalarVisibility(1)
    AtomsMapper.SetScalarModeToDefault()

    Atoms = vtk.vtkLODActor()
    Atoms.SetMapper(AtomsMapper)

    ############
    # Draw bonds
    ############

    Tube = vtk.vtkTubeFilter()
    Tube.SetInput(CubeData.GetOutput())

    BondsMapper = vtk.vtkPolyDataMapper()
    BondsMapper.SetInput(Tube.GetOutput())

    Bonds = vtk.vtkLODActor()
    Bonds.SetMapper(BondsMapper)

    #######################
    # Now compose the image
    #######################
    if DrawVolume:
        ren.AddVolume(volume)

    if DrawNodes:
        ren.AddActor(contourActor)

    if DrawFrame:
        ren.AddActor(frameActor)

    if DrawAtoms:
        ren.AddActor(Atoms)

    if DrawBonds:
        ren.AddActor(Bonds)

    ren.SetBackground(BackgroundColor)
    renWin.SetSize(OutputHeight, OutputWidth)


    ######################################
    # Let VTK do its magic and render away
    ######################################

    renWin.Render()

    ###################################
    # Now allow user to play with image
    ###################################

    def Keypress(obj, event):
        #This function handles keyboard interaction

        key = obj.GetKeySym()

        if key == 'd' or key == 'F13':
            WriteToPNG()
        elif key == 'h' or key == 'question' or key =='?':
            PrintHelp()
        elif key == 'c':
            camera = ren.GetActiveCamera()
            print "Camera info:"
            print "------------"
            print "Position is: ", camera.GetPosition()
            print "Focal point is:", camera.GetFocalPoint()
            print "Orientation is:", ren.GetActiveCamera().GetOrientation()
            print "WXYZ", ren.GetActiveCamera().GetOrientationWXYZ()
            print "View up direction is:", camera.GetViewUp()
            print "Direction of projection is:", camera.GetDirectionOfProjection()

        else:
            if DEBUG:
                print 'User pressed key:', key 

    if Interactive:
        iren.SetDesiredUpdateRate(25.0) #25 fps when camera is moving around
        iren.SetStillUpdateRate(0.0) #0 fps when camera is not moving

        iren.Initialize()

        #The default interaction style is joystick, which seems unnatural
        style = vtk.vtkInteractorStyleTrackballCamera()
        iren.SetInteractorStyle(style)

        iren.AddObserver("KeyPressEvent", Keypress)
        iren.Start()
    else:
        WriteToPNG()
コード例 #5
0
def RenderCubeInVTK(filename='test.cube', mindatum=0.0, maxdatum=0.0):
    global renWin

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #######################
    # Read in Gaussian cube
    #######################

    CubeData = vtk.vtkGaussianCubeReader()
    CubeData.SetFileName(filename)

    CubeData.Update()

    #Get intrinsic scale from data
    scale = sum([x**2 for x in CubeData.GetTransform().GetScale()])

    CubeData.SetHBScale(scale)  #scaling factor to compute bonds with hydrogens
    CubeData.SetBScale(scale)  #scaling factor for other bonds

    CubeData.Update()

    ###################
    #Calculate scalings

    #VTK only knows how to render integer data in the interval [0,255] or [0,65535]
    #Here, we calculate scaling factors to map the cube data to the interval.

    if mindatum == maxdatum == 0.0:
        if DEBUG:
            print "Autodetecting range"
            mindatum, maxdatum = CubeData.GetGridOutput().GetPointData(
            ).GetScalars().GetRange()

    # Find the remapped value that corresponds to zero
    zeropoint = int(2**ColorDepth * (-mindatum) / (maxdatum - mindatum))
    absmaxdatum = max(-mindatum, maxdatum)

    maxnegativeintensity = min(
        1.0, 1.0 - (absmaxdatum - abs(mindatum)) / absmaxdatum)
    minnegativeintensity = 0.0
    if zeropoint < 0:
        minpositiveintensity = -zeropoint / (2**ColorDepth * absmaxdatum)
    else:
        minpositiveintensity = 0.0
        maxpositiveintensity = min(
            1.0, 1.0 - (absmaxdatum - abs(maxdatum)) / absmaxdatum)
    if DEBUG:
        print "Range plotted = [%f,%f]" % (mindatum, maxdatum)
        print "Negative colors = [0,%d)" % max(0, zeropoint)
        print "Negative intensities = [%f,%f]" % (maxnegativeintensity,
                                                  minnegativeintensity)
        print "Positive colors = (%d,%d)" % (max(0, zeropoint), 2**ColorDepth)
        print "Positive intensities = [%f,%f]" % (minpositiveintensity,
                                                  maxpositiveintensity)
        print "On this scale, zero = %d" % zeropoint

    ################################
    # Calculate opacity transfer map

    #The code here differentiates between two cases:
    #1. the scalar data are all positive, so it's just a simple linear ramp
    #2. the scalar data are signed, so do two linear ramps

    opacityTransferFunction = vtk.vtkPiecewiseFunction()

    if zeropoint < 0:
        opacityTransferFunction.AddPoint(0, minpositiveintensity)
    else:
        opacityTransferFunction.AddPoint(0, maxnegativeintensity)
        opacityTransferFunction.AddPoint(zeropoint, 0.0)

    opacityTransferFunction.AddPoint(2**ColorDepth - 1, maxpositiveintensity)
    opacityTransferFunction.ClampingOn()

    ###########################
    # Create color transfer map

    colorTransferFunction = vtk.vtkColorTransferFunction()

    r1, g1, b1 = NegativeColor
    r2, g2, b2 = PositiveColor
    r0, g0, b0 = BackgroundColor

    if zeropoint < 0:
        colorTransferFunction.AddRGBPoint(0, r1, g1, b1)
    else:
        colorTransferFunction.AddRGBPoint(0, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint - 1, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint, r0, g0, b0)
        colorTransferFunction.AddRGBPoint(zeropoint + 1, r2, g2, b2)
    colorTransferFunction.AddRGBPoint(2**ColorDepth - 1, r2, g2, b2)

    ########################
    # Now apply the scalings

    ScaledData = vtk.vtkImageShiftScale()
    ScaledData.SetInput(CubeData.GetGridOutput())
    ScaledData.SetShift(-mindatum)
    ScaledData.SetScale((2**ColorDepth - 1) / (maxdatum - mindatum))

    if ColorDepth == 16:
        ScaledData.SetOutputScalarTypeToUnsignedShort()
    elif ColorDepth == 8:
        ScaledData.SetOutputScalarTypeToUnsignedChar()
    else:
        print
        print "Error! Unsupported color depth given"
        print
        print "valid values are 8 or 16"
        print
        raise ValueError

    ###############################
    # Form combined coloring scheme

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorTransferFunction)
    volumeProperty.SetScalarOpacity(opacityTransferFunction)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()

    # The mapper / ray cast function know how to render the data
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()

    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInput(ScaledData.GetOutput())

    #Create a coarse representation
    #Actually a fake - won't display anything

    compositeFunction2 = vtk.vtkVolumeRayCastIsosurfaceFunction()
    compositeFunction2.SetIsoValue(2**ColorDepth - 1)

    volumeMapperCoarse = vtk.vtkVolumeRayCastMapper()
    volumeMapperCoarse.SetVolumeRayCastFunction(compositeFunction2)
    volumeMapperCoarse.SetInput(ScaledData.GetOutput())

    # Create volumetric object to be rendered
    # Use level of detail prop so that it won't take forever to look around

    volume = vtk.vtkLODProp3D()
    id1 = volume.AddLOD(volumeMapper, volumeProperty, 0.)
    volume.SetLODProperty(id1, volumeProperty)
    id2 = volume.AddLOD(volumeMapperCoarse, volumeProperty, 0.)
    volume.SetLODProperty(id2, volumeProperty)

    # At this point, we can position and orient the volume

    #################################
    # End of volumetric data pipeline
    #################################

    #########
    #Contours
    #########

    contour = vtk.vtkContourFilter()
    contour.SetInput(CubeData.GetGridOutput())
    contour.SetNumberOfContours(1)
    contour.SetValue(0, 0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInput(contour.GetOutput())
    contourMapper.SetScalarRange(0, 0)
    contourMapper.GetLookupTable().SetNumberOfTableValues(1)
    r0, g0, b0 = NodeColor
    contourMapper.GetLookupTable().SetTableValue(0, r0, g0, b0, NodeAlpha)

    contourActor = vtk.vtkLODActor()
    contourActor.SetMapper(contourMapper)
    contourActor.GetProperty().SetOpacity(NodeAlpha)

    ##########################################
    # Create a wireframe outline of the volume
    ##########################################

    frame = vtk.vtkOutlineFilter()
    frame.SetInput(CubeData.GetGridOutput())

    frameMapper = vtk.vtkPolyDataMapper()
    frameMapper.SetInput(frame.GetOutput())

    frameActor = vtk.vtkLODActor()
    frameActor.SetMapper(frameMapper)
    frameActor.GetProperty().SetColor(FrameColor)
    frameActor.GetProperty().SetOpacity(FrameAlpha)

    ######################
    # Draw balls for atoms
    ######################

    Sphere = vtk.vtkSphereSource()
    Sphere.SetThetaResolution(16)
    Sphere.SetPhiResolution(16)
    Sphere.SetRadius(0.4)

    Glyph = vtk.vtkGlyph3D()
    Glyph.SetInput(CubeData.GetOutput())
    Glyph.SetColorMode(1)
    Glyph.SetColorModeToColorByScalar()
    Glyph.SetScaleModeToScaleByVectorComponents()
    Glyph.SetSource(Sphere.GetOutput())

    AtomsMapper = vtk.vtkPolyDataMapper()
    AtomsMapper.SetInput(Glyph.GetOutput())
    AtomsMapper.SetImmediateModeRendering(1)
    AtomsMapper.UseLookupTableScalarRangeOff()
    AtomsMapper.SetScalarVisibility(1)
    AtomsMapper.SetScalarModeToDefault()

    Atoms = vtk.vtkLODActor()
    Atoms.SetMapper(AtomsMapper)

    ############
    # Draw bonds
    ############

    Tube = vtk.vtkTubeFilter()
    Tube.SetInput(CubeData.GetOutput())

    BondsMapper = vtk.vtkPolyDataMapper()
    BondsMapper.SetInput(Tube.GetOutput())

    Bonds = vtk.vtkLODActor()
    Bonds.SetMapper(BondsMapper)

    #######################
    # Now compose the image
    #######################
    if DrawVolume:
        ren.AddVolume(volume)

    if DrawNodes:
        ren.AddActor(contourActor)

    if DrawFrame:
        ren.AddActor(frameActor)

    if DrawAtoms:
        ren.AddActor(Atoms)

    if DrawBonds:
        ren.AddActor(Bonds)

    ren.SetBackground(BackgroundColor)
    renWin.SetSize(OutputHeight, OutputWidth)

    ######################################
    # Let VTK do its magic and render away
    ######################################

    renWin.Render()

    ###################################
    # Now allow user to play with image
    ###################################

    def Keypress(obj, event):
        #This function handles keyboard interaction

        key = obj.GetKeySym()

        if key == 'd' or key == 'F13':
            WriteToPNG()
        elif key == 'h' or key == 'question' or key == '?':
            PrintHelp()
        elif key == 'c':
            camera = ren.GetActiveCamera()
            print "Camera info:"
            print "------------"
            print "Position is: ", camera.GetPosition()
            print "Focal point is:", camera.GetFocalPoint()
            print "Orientation is:", ren.GetActiveCamera().GetOrientation()
            print "WXYZ", ren.GetActiveCamera().GetOrientationWXYZ()
            print "View up direction is:", camera.GetViewUp()
            print "Direction of projection is:", camera.GetDirectionOfProjection(
            )

        else:
            if DEBUG:
                print 'User pressed key:', key

    if Interactive:
        iren.SetDesiredUpdateRate(25.0)  #25 fps when camera is moving around
        iren.SetStillUpdateRate(0.0)  #0 fps when camera is not moving

        iren.Initialize()

        #The default interaction style is joystick, which seems unnatural
        style = vtk.vtkInteractorStyleTrackballCamera()
        iren.SetInteractorStyle(style)

        iren.AddObserver("KeyPressEvent", Keypress)
        iren.Start()
    else:
        WriteToPNG()
コード例 #6
0
colorTransferFunction.SetColorSpaceToHSV()
# Create properties, mappers, volume actors, and ray cast function
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorTransferFunction)
volumeProperty.SetScalarOpacity(opacityTransferFunction)
volumeProperty.SetInterpolationTypeToLinear()
volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
volumeMapper.SetInputConnection(reader.GetOutputPort())
sphereSource = vtk.vtkSphereSource()
sphereSource.SetCenter(25,25,25)
sphereSource.SetRadius(30)
sphereSource.SetThetaResolution(15)
sphereSource.SetPhiResolution(15)
geoMapper = vtk.vtkPolyDataMapper()
geoMapper.SetInputConnection(sphereSource.GetOutputPort())
lod = vtk.vtkLODProp3D()
geoID = lod.AddLOD(geoMapper,0.0)
volID = lod.AddLOD(volumeMapper,volumeProperty,0.0)
property = vtk.vtkProperty()
property.SetColor(1,0,0)
lod.SetLODProperty(geoID,property)
# Okay now the graphics stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(256,256)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
ren1.GetCullers().InitTraversal()
culler = ren1.GetCullers().GetNextItem()
culler.SetSortingStyleToBackToFront()
コード例 #7
0
ファイル: VolumeFactory.py プロジェクト: mengde007/vtkAtamai
    def __init__(self):
        ActorFactory.ActorFactory.__init__(self)

        self._LookupTable = None  # lookup table is currently not used
        self._ColorTransferFunction = None
        self._OpacityTransferFunction = None
        self._RendererObserverList = {}

        # create a clipping cube to go with the volume
        self._ClippingCube = ClippingCubeFactory.ClippingCubeFactory()
        self.AddChild(self._ClippingCube)
        self._CubeClippingPlanes = vtk.vtkPlaneCollection()
        for i in range(6):
            self._CubeClippingPlanes.AddItem(vtk.vtkPlane())

        # corner clipping planes, in pairs with opposite normals
        self._CornerClippingPlanes = vtk.vtkPlaneCollection()
        for i in range(6):
            self._CornerClippingPlanes.AddItem(vtk.vtkPlane())

        # clipping planes for the volume, sorted for the
        # three chunks that will make up the final volume
        # (these are currently unused)
        self._ClippingPlanes = [vtk.vtkPlaneCollection(),
                                vtk.vtkPlaneCollection(),
                                vtk.vtkPlaneCollection()]

        for i in range(3):
            planes = self._ClippingPlanes[i]
            cplanes = self._CornerClippingPlanes
            bplanes = self._CubeClippingPlanes
            if i == 0:
                planes.AddItem(cplanes.GetItemAsObject(0))
                planes.AddItem(bplanes.GetItemAsObject(1))
                planes.AddItem(bplanes.GetItemAsObject(2))
                planes.AddItem(bplanes.GetItemAsObject(3))
                planes.AddItem(bplanes.GetItemAsObject(4))
                planes.AddItem(bplanes.GetItemAsObject(5))
            else:
                planes.AddItem(bplanes.GetItemAsObject(0))
                planes.AddItem(cplanes.GetItemAsObject(1))
                if i == 1:
                    planes.AddItem(cplanes.GetItemAsObject(2))
                    planes.AddItem(bplanes.GetItemAsObject(3))
                    planes.AddItem(bplanes.GetItemAsObject(4))
                    planes.AddItem(bplanes.GetItemAsObject(5))
                else:
                    planes.AddItem(bplanes.GetItemAsObject(2))
                    planes.AddItem(cplanes.GetItemAsObject(3))
                    if i == 2:
                        planes.AddItem(cplanes.GetItemAsObject(4))
                        planes.AddItem(bplanes.GetItemAsObject(5))
                    else:
                        planes.AddItem(bplanes.GetItemAsObject(4))
                        planes.AddItem(bplanes.GetItemAsObject(5))

        # generate the pipeline pieces
        self._Input = None

        # transform the full-resolution volume
        self._RayCastReslice = vtk.vtkImageReslice()
        self._RayCastReslice.SetInterpolationModeToLinear()

        # subsample the volume for low-res rendering
        self._ImagePrefilter1 = vtk.vtkImageShrink3D()

        self._ImagePrefilter2 = vtk.vtkImageShrink3D()

        # transform the subsampled volume
        self._ImageReslice1 = vtk.vtkImageReslice()
        self._ImageReslice1.SetInterpolationModeToLinear()

        self._ImageReslice2 = vtk.vtkImageReslice()
        self._ImageReslice2.SetInterpolationModeToLinear()

        # convert to RGBA for rendering (unused)
        self._ImageMapToColors = vtk.vtkImageMapToColors()
        self._ImageMapToColors.SetOutputFormatToRGBA()

        # strictly for VTK 3.2 compatibility
        self._ImageToStructuredPoints = vtk.vtkImageToStructuredPoints()

        # a transform to apply to the image
        self._ImageTransform = None
        self._TransformToGrid = vtk.vtkTransformToGrid()

        # the opacity pick threshold for the volume
        self._PickThreshold = 0.99
        # the implicit volume for finding the gradient
        self._ImplicitVolume = vtk.vtkImplicitVolume()

        # the texture dimensions (later this will be set automatically
        #    to provide the desired interactive rendering time)
        self._TextureSize = 128

        # the bounds of the volume
        self._VolumeBounds = None

        # vtkVolume specific stuff
        self._VolumeProperty = vtk.vtkVolumeProperty()
        self._VolumeProperty.SetInterpolationTypeToLinear()

        rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction()
        self._VolumeRayCastMapper = vtk.vtkVolumeRayCastMapper()
        self._VolumeRayCastMapper.SetVolumeRayCastFunction(rayCastFunction)
        self._VolumeRayCastMapper.SetClippingPlanes(
            self._ClippingCube.GetClippingPlanes())
        try:  # vtk 3.2 does not contain this function call:
            self._VolumeRayCastMapper.AutoAdjustSampleDistancesOff()
        except:
            pass

        self._VolumeTextureMapper1 = vtk.vtkVolumeTextureMapper2D()
        self._VolumeTextureMapper1.SetTargetTextureSize(old_div(self._TextureSize, 4),
                                                        old_div(self._TextureSize, 4))
        self._VolumeTextureMapper1.SetMaximumNumberOfPlanes(
            old_div(self._TextureSize, 2))
        self._VolumeTextureMapper1.SetClippingPlanes(
            self._ClippingCube.GetClippingPlanes())
        try:  # vtk 3.2 does not contain this function call:
            # set to the amount of available texture memory (24MB is a good
            # start)
            self._VolumeTextureMapper1.SetMaximumStorageSize(24 * 1024 * 1024)
        except:
            pass

        self._VolumeTextureMapper2 = vtk.vtkVolumeTextureMapper2D()
        self._VolumeTextureMapper2.SetTargetTextureSize(self._TextureSize,
                                                        self._TextureSize)
        self._VolumeTextureMapper2.SetMaximumNumberOfPlanes(self._TextureSize)
        self._VolumeTextureMapper2.SetClippingPlanes(
            self._ClippingCube.GetClippingPlanes())

        try:  # vtk 3.2 does not contain this function call:
            # set to the amount of available texture memory (24MB is a good
            # start)
            self._VolumeTextureMapper2.SetMaximumStorageSize(24 * 1024 * 1024)
        except:
            pass

        # set two levels of detail: texture and ray-casting
        self._Volume = vtk.vtkLODProp3D()
        self._Volume.PickableOff()
        idT1 = self._Volume.AddLOD(self._VolumeTextureMapper1,
                                   self._VolumeProperty,
                                   0.02)
        idT2 = self._Volume.AddLOD(self._VolumeTextureMapper2,
                                   self._VolumeProperty,
                                   0.1)

        # remember these LOD id numbers
        self._lod = [idT1, idT2]

#        idRC = self._Volume.AddLOD(self._VolumeRayCastMapper,
#                                   self._VolumeProperty,
#                                   2.0)
        self._Volume.SetLODLevel(idT1, 2.0)
        self._Volume.SetLODLevel(idT2, 1.0)