def MakeLUT(tableSize):
    '''
    Make a lookup table from a set of named colors.
    :param: tableSize - The table size
    :return: The lookup table.
    '''
    nc = vtk.vtkNamedColors()

    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(tableSize)
    lut.Build()

    # Fill in a few known colors, the rest will be generated if needed
    lut.SetTableValue(0,nc.GetColor4d("Black"))
    lut.SetTableValue(1,nc.GetColor4d("Banana"))
    lut.SetTableValue(2,nc.GetColor4d("Tomato"))
    lut.SetTableValue(3,nc.GetColor4d("Wheat"))
    lut.SetTableValue(4,nc.GetColor4d("Lavender"))
    lut.SetTableValue(5,nc.GetColor4d("Flesh"))
    lut.SetTableValue(6,nc.GetColor4d("Raspberry"))
    lut.SetTableValue(7,nc.GetColor4d("Salmon"))
    lut.SetTableValue(8,nc.GetColor4d("Mint"))
    lut.SetTableValue(9,nc.GetColor4d("Peacock"))

    return lut
Ejemplo n.º 2
0
Archivo: cutLoop.py Proyecto: 0004c/VTK
def GetRGBColor(colorName):
    '''
        Return the red, green and blue components for a
        color as doubles.
    '''
    rgb = [0.0, 0.0, 0.0]  # black
    vtk.vtkNamedColors().GetColorRGB(colorName, rgb)
    return rgb
Ejemplo n.º 3
0
def main():
    nc = vtk.vtkNamedColors()
    colorNames = nc.GetColorNames().split('\n')
    print("There are", len(colorNames), "colors:")
    print(colorNames)
    syn = nc.GetSynonyms().split('\n\n')
    synonyms = []
    for ele in syn:
        synonyms.append(ele.split('\n'))
    print("There are", len(synonyms), "synonyms:")
    print(synonyms)
    iren = DisplayCone(nc)
    iren.Start()
Ejemplo n.º 4
0
def create_color(color):
    """ Creates VTK-compatible RGB color from a color string.

    :param color: color
    :type color: str
    :return: RGB color values
    :rtype: list
    """
    if color[0] == "#":
        # Convert hex string to RGB
        return [int(color[i:i + 2], 16) / 255 for i in range(1, 7, 2)]
    else:
        # Create a named colors instance
        nc = vtk.vtkNamedColors()
        return nc.GetColor3d(color)
Ejemplo n.º 5
0
def main():
    colors = vtk.vtkNamedColors()

    src_fn, tgt_fn = get_program_parameters()
    print('Loading source:', src_fn)
    sourcePolyData = ReadPolyData(src_fn)
    # Save the source polydata in case the align does not improve
    # segmentation
    originalSourcePolyData = vtk.vtkPolyData()
    originalSourcePolyData.DeepCopy(sourcePolyData)

    print('Loading target:', tgt_fn)
    targetPolyData = ReadPolyData(tgt_fn)

    # If the target orientation is markedly different,
    # you may need to apply a transform to orient the
    # target with the source.
    # For example, when using Grey_Nurse_Shark.stl as the source and
    # greatWhite.stl as the target, you need to uncomment the following
    # two rotations.
    trnf = vtk.vtkTransform()
    # trnf.RotateX(90)
    # trnf.RotateY(-90)
    tpd = vtk.vtkTransformPolyDataFilter()
    tpd.SetTransform(trnf)
    tpd.SetInputData(targetPolyData)
    tpd.Update()

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    distance = vtk.vtkHausdorffDistancePointSetFilter()
    distance.SetInputData(0, tpd.GetOutput())
    distance.SetInputData(1, sourcePolyData)
    distance.Update()

    distanceBeforeAlign = distance.GetOutput(0).GetFieldData().GetArray(
        'HausdorffDistance').GetComponent(0, 0)

    # Get initial alignment using oriented bounding boxes
    AlignBoundingBoxes(sourcePolyData, tpd.GetOutput())

    distance.SetInputData(0, tpd.GetOutput())
    distance.SetInputData(1, sourcePolyData)
    distance.Modified()
    distance.Update()
    distanceAfterAlign = distance.GetOutput(0).GetFieldData().GetArray(
        'HausdorffDistance').GetComponent(0, 0)

    bestDistance = min(distanceBeforeAlign, distanceAfterAlign)

    if distanceAfterAlign > distanceBeforeAlign:
        sourcePolyData.DeepCopy(originalSourcePolyData)

    # Refine the alignment using IterativeClosestPoint
    icp = vtk.vtkIterativeClosestPointTransform()
    icp.SetSource(sourcePolyData)
    icp.SetTarget(tpd.GetOutput())
    icp.GetLandmarkTransform().SetModeToRigidBody()
    icp.SetMaximumNumberOfLandmarks(100)
    icp.SetMaximumMeanDistance(.00001)
    icp.SetMaximumNumberOfIterations(500)
    icp.CheckMeanDistanceOn()
    icp.StartByMatchingCentroidsOn()
    icp.Update()

    #  print(icp)

    lmTransform = icp.GetLandmarkTransform()
    transform = vtk.vtkTransformPolyDataFilter()
    transform.SetInputData(sourcePolyData)
    transform.SetTransform(lmTransform)
    transform.SetTransform(icp)
    transform.Update()

    distance.SetInputData(0, tpd.GetOutput())
    distance.SetInputData(1, transform.GetOutput())
    distance.Update()

    distanceAfterICP = distance.GetOutput(0).GetFieldData().GetArray(
        'HausdorffDistance').GetComponent(0, 0)

    if distanceAfterICP < bestDistance:
        bestDistance = distanceAfterICP

    print(
        'Distance before, after align, after ICP, min: {:0.5f}, {:0.5f}, {:0.5f}, {:0.5f}'
        .format(distanceBeforeAlign, distanceAfterAlign, distanceAfterICP,
                bestDistance))
    # Select
    sourceMapper = vtk.vtkDataSetMapper()
    if bestDistance == distanceBeforeAlign:
        sourceMapper.SetInputData(originalSourcePolyData)
        print('Using original alignment')
    elif bestDistance == distanceAfterAlign:
        sourceMapper.SetInputData(sourcePolyData)
        print('Using alignment by OBB')
    else:
        sourceMapper.SetInputConnection(transform.GetOutputPort())
        print('Using alignment by ICP')
    sourceMapper.ScalarVisibilityOff()

    sourceActor = vtk.vtkActor()
    sourceActor.SetMapper(sourceMapper)
    sourceActor.GetProperty().SetOpacity(.6)
    sourceActor.GetProperty().SetDiffuseColor(colors.GetColor3d('White'))
    renderer.AddActor(sourceActor)

    targetMapper = vtk.vtkDataSetMapper()
    targetMapper.SetInputData(tpd.GetOutput())
    targetMapper.ScalarVisibilityOff()

    targetActor = vtk.vtkActor()
    targetActor.SetMapper(targetMapper)
    targetActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Tomato'))
    renderer.AddActor(targetActor)

    renderWindow.AddRenderer(renderer)
    renderer.SetBackground(colors.GetColor3d("sea_green_light"))
    renderer.UseHiddenLineRemovalOn()

    renderWindow.SetSize(640, 480)
    renderWindow.Render()
    renderWindow.SetWindowName('AlignTwoPolyDatas')
    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 6
0
    def OpenVTK(self):
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl = Qt.QVBoxLayout()
        self.vl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(
            self.ren)  # vtk widget에 렌더링할 ren을 넣어주고
        # 출력을 담당할 iren에 vtk widget정보를 입력
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # renWin = vtk.vtkRenderWindow()
        # renWin.AddRenderer(self.ren)
        # self.iren = vtk.vtkRenderWindowInteractor()
        # self.iren.SetRenderWindow(renWin)
        # self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) #vtk widget에 렌더링할 ren을 넣어주고
        # self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()#출력을 담당할 iren에 vtk widget정보를 입력

        # Create source
        colors = vtk.vtkNamedColors()
        colors.SetColor("SkinColor", [255, 125, 64, 255])
        colors.SetColor("BkgColor", [51, 77, 102, 255])

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName('FullHead.mhd')
        reader.Update()

        skinExtractor = vtk.vtkMarchingCubes()
        skinExtractor.SetInputConnection(reader.GetOutputPort())
        skinExtractor.SetValue(0, 500)
        skinExtractor.Update()

        skinStripper = vtk.vtkStripper()
        skinStripper.SetInputConnection(skinExtractor.GetOutputPort())
        skinStripper.Update()

        skinMapper = vtk.vtkPolyDataMapper()
        skinMapper.SetInputConnection(skinStripper.GetOutputPort())
        skinMapper.ScalarVisibilityOff()

        skin = vtk.vtkActor()
        skin.SetMapper(skinMapper)
        skin.GetProperty().SetDiffuseColor(colors.GetColor3d("SkinColor"))
        skin.GetProperty().SetSpecular(.3)
        skin.GetProperty().SetSpecularPower(20)

        # An isosurface, or contour value of 1150 is known to correspond to
        # the bone of the patient.
        # The triangle stripper is used to create triangle
        # strips from the isosurface these render much faster on may
        # systems.
        boneExtractor = vtk.vtkMarchingCubes()
        boneExtractor.SetInputConnection(reader.GetOutputPort())
        boneExtractor.SetValue(0, 1150)

        boneStripper = vtk.vtkStripper()
        boneStripper.SetInputConnection(boneExtractor.GetOutputPort())

        boneMapper = vtk.vtkPolyDataMapper()
        boneMapper.SetInputConnection(boneStripper.GetOutputPort())
        boneMapper.ScalarVisibilityOff()

        bone = vtk.vtkActor()
        bone.SetMapper(boneMapper)
        bone.GetProperty().SetDiffuseColor(colors.GetColor3d("Ivory"))

        # An outline provides context around the data.
        #
        outlineData = vtk.vtkOutlineFilter()
        outlineData.SetInputConnection(reader.GetOutputPort())
        outlineData.Update()

        mapOutline = vtk.vtkPolyDataMapper()
        mapOutline.SetInputConnection(outlineData.GetOutputPort())

        outline = vtk.vtkActor()
        outline.SetMapper(mapOutline)
        outline.GetProperty().SetColor(colors.GetColor3d("White"))

        # Now we are creating three orthogonal planes passing through the
        # volume. Each plane uses a different texture map and therefore has
        # different coloration.

        # Start by creating a black/white lookup table.
        value = int(self.horizontalSlider.value()) * 30
        print(2000 + value)
        bwLut = vtk.vtkLookupTable()
        bwLut.SetTableRange(0, 2000 + value)
        bwLut.SetSaturationRange(0, 0)
        bwLut.SetHueRange(0, 0)
        bwLut.SetValueRange(0, 1)
        bwLut.Build()  # effective built

        # Now create a lookup table that consists of the full hue circle
        # (from HSV).
        hueLut = vtk.vtkLookupTable()
        hueLut.SetTableRange(0, 2000)
        hueLut.SetHueRange(0, 0)
        hueLut.SetSaturationRange(1, 1)
        hueLut.SetValueRange(0, 1)
        hueLut.Build()  # effective built

        # Finally, create a lookup table with a single hue but having a range
        # in the saturation of the hue.

        satLut = vtk.vtkLookupTable()
        satLut.SetTableRange(0, 2000)
        satLut.SetHueRange(.6, .6)
        satLut.SetSaturationRange(0, 1)
        satLut.SetValueRange(1, 1)
        satLut.Build()  # effective built

        # Create the first of the three planes. The filter vtkImageMapToColors
        # maps the data through the corresponding lookup table created above.  The
        # vtkImageActor is a type of vtkProp and conveniently displays an image on
        # a single quadrilateral plane. It does this using texture mapping and as
        # a result is quite fast. (Note: the input image has to be unsigned char
        # values, which the vtkImageMapToColors produces.) Note also that by
        # specifying the DisplayExtent, the pipeline requests data of this extent
        # and the vtkImageMapToColors only processes a slice of data.
        sagittalColors = vtk.vtkImageMapToColors()
        sagittalColors.SetInputConnection(reader.GetOutputPort())
        sagittalColors.SetLookupTable(bwLut)
        sagittalColors.Update()

        sagittal = vtk.vtkImageActor()
        sagittal.GetMapper().SetInputConnection(sagittalColors.GetOutputPort())
        # 앞 두 파라미터로 Sagittal 의 위치조절
        sagittal.SetDisplayExtent(128, 128, 0, 255, 0, 92)

        # Create the second (axial) plane of the three planes. We use the
        # same approach as before except that the extent differs.
        axialColors = vtk.vtkImageMapToColors()
        axialColors.SetInputConnection(reader.GetOutputPort())
        axialColors.SetLookupTable(bwLut)
        axialColors.Update()
        axial = vtk.vtkImageActor()
        axial.GetMapper().SetInputConnection(axialColors.GetOutputPort())
        axial.SetDisplayExtent(0, 255, 0, 255, 46, 46)

        # Create the third (coronal) plane of the three planes. We use
        # the same approach as before except that the extent differs.
        coronalColors = vtk.vtkImageMapToColors()
        coronalColors.SetInputConnection(reader.GetOutputPort())
        coronalColors.SetLookupTable(bwLut)
        coronalColors.Update()

        coronal = vtk.vtkImageActor()
        coronal.GetMapper().SetInputConnection(coronalColors.GetOutputPort())
        coronal.SetDisplayExtent(0, 255, 128, 128, 0, 92)

        # It is convenient to create an initial view of the data. The
        # FocalPoint and Position form a vector direction. Later on
        # (ResetCamera() method) this vector is used to position the camera
        # to look at the data in this direction.
        aCamera = vtk.vtkCamera()
        aCamera.SetViewUp(0, 0, -1)
        aCamera.SetPosition(0, -1, 0)
        aCamera.SetFocalPoint(0, 0, 0)
        aCamera.ComputeViewPlaneNormal()
        aCamera.Azimuth(0.0)
        aCamera.Elevation(0.0)

        # Actors are added to the renderer.
        self.ren.AddActor(outline)
        self.ren.AddActor(sagittal)
        self.ren.AddActor(axial)
        self.ren.AddActor(coronal)
        # self.ren.AddActor(skin)
        # self.ren.AddActor(bone)

        # Turn off bone for this example.
        bone.VisibilityOn()

        # Set skin to semi-transparent.
        skin.GetProperty().SetOpacity(0.5)

        # An initial camera view is created.  The Dolly() method moves
        # the camera towards the FocalPoint, thereby enlarging the image.
        self.ren.SetActiveCamera(aCamera)

        # Calling Render() directly on a vtkRenderer is strictly forbidden.
        # Only calling Render() on the vtkRenderWindow is a valid call.
        # renWin.Render()
        self.show()

        self.ren.ResetCamera()
        self.frame.setLayout(self.vl)
        aCamera.Dolly(1.5)

        # Note that when camera movement occurs (as it does in the Dolly()
        # method), the clipping planes often need adjusting. Clipping planes
        # consist of two planes: near and far along the view direction. The
        # near plane clips out objects in front of the plane; the far plane
        # clips out objects behind the plane. This way only what is drawn
        # between the planes is actually rendered.
        self.ren.ResetCameraClippingRange()

        # Interact with the data.
        #     renWin.Render()
        self.show()
        self.iren.Initialize()
        self.iren.Start()
Ejemplo n.º 7
0
def main():
    colors = vtk.vtkNamedColors()

    renderer = vtk.vtkRenderer()

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)
    renderWindow.SetSize(640, 480)

    #
    # Create surface of implicit function.
    #

    # Sample quadric function.
    quadric = vtk.vtkQuadric()
    quadric.SetCoefficients(1, 2, 3, 0, 1, 0, 0, 0, 0, 0)

    sample = vtk.vtkSampleFunction()
    sample.SetSampleDimensions(25, 25, 25)
    sample.SetImplicitFunction(quadric)

    isoActor = vtk.vtkActor()
    CreateIsosurface(sample, isoActor)
    outlineIsoActor = vtk.vtkActor()
    CreateOutline(sample, outlineIsoActor)

    planesActor = vtk.vtkActor()
    CreatePlanes(sample, planesActor, 3)
    outlinePlanesActor = vtk.vtkActor()
    CreateOutline(sample, outlinePlanesActor)
    planesActor.AddPosition(isoActor.GetBounds()[0] * 2.0, 0, 0)
    outlinePlanesActor.AddPosition(isoActor.GetBounds()[0] * 2.0, 0, 0)

    contourActor = vtk.vtkActor()
    CreateContours(sample, contourActor, 3, 15)
    outlineContourActor = vtk.vtkActor()
    CreateOutline(sample, outlineContourActor)
    contourActor.AddPosition(isoActor.GetBounds()[0] * 4.0, 0, 0)
    outlineContourActor.AddPosition(isoActor.GetBounds()[0] * 4.0, 0, 0)

    renderer.AddActor(planesActor)
    renderer.AddActor(outlinePlanesActor)
    renderer.AddActor(contourActor)
    renderer.AddActor(outlineContourActor)
    renderer.AddActor(isoActor)
    renderer.AddActor(outlineIsoActor)

    renderer.TwoSidedLightingOn()

    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    # Try to set camera to match figure on book
    renderer.GetActiveCamera().SetPosition(0, -1, 0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 0, -1)
    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(20)
    renderer.GetActiveCamera().Azimuth(10)
    renderer.GetActiveCamera().Dolly(1.2)
    renderer.ResetCameraClippingRange()

    renderWindow.SetSize(640, 480)
    renderWindow.SetWindowName('QuadricVisualization');

    renderWindow.Render()

    # interact with data
    interactor.Start()
Ejemplo n.º 8
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()

    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(fileName)

    hhog = vtk.vtkHedgeHog()
    hhog.SetInputConnection(reader.GetOutputPort())
    hhog.SetScaleFactor(0.3)

    lut = vtk.vtkLookupTable()
    # lut.SetHueRange(.667, 0.0)
    lut.Build()

    hhogMapper = vtk.vtkPolyDataMapper()
    hhogMapper.SetInputConnection(hhog.GetOutputPort())
    hhogMapper.SetScalarRange(50, 550)
    hhogMapper.SetLookupTable(lut)

    hhogActor = vtk.vtkActor()
    hhogActor.SetMapper(hhogMapper)

    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(reader.GetOutputPort())

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    aRenderer = vtk.vtkRenderer()
    aRenderWindow = vtk.vtkRenderWindow()
    aRenderWindow.AddRenderer(aRenderer)
    anInteractor = vtk.vtkRenderWindowInteractor()
    anInteractor.SetRenderWindow(aRenderWindow)
    aRenderWindow.SetSize(640, 480)
    aRenderWindow.SetWindowName('ComplexV')

    aRenderer.AddActor(outlineActor)
    aRenderer.AddActor(hhogActor)

    aRenderer.SetBackground(colors.GetColor3d('SlateGray'))

    # Generate an interesting view.

    aRenderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    aRenderer.GetActiveCamera().SetPosition(1, 0, 0)
    aRenderer.GetActiveCamera().SetViewUp(0, 0, 1)
    aRenderer.ResetCamera()

    aRenderer.GetActiveCamera().Azimuth(60)
    aRenderer.GetActiveCamera().Elevation(30)
    aRenderer.GetActiveCamera().Dolly(1.1)
    aRenderer.ResetCameraClippingRange()

    aRenderWindow.Render()

    # Interact with the data.
    anInteractor.Start()
Ejemplo n.º 9
0
def main():
    fileName1, fileName2 = get_program_parameters()

    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor('BkgColor', [65, 99, 149, 255])

    # Read a vtk file
    #
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(fileName1)
    pl3d.SetQFileName(fileName2)
    pl3d.SetScalarFunctionNumber(100)  # Density
    pl3d.SetVectorFunctionNumber(202)  # Momentum
    pl3d.Update()

    pl3dOutput = pl3d.GetOutput().GetBlock(0)

    # What do we know about the data?
    # Get the extent of the data: imin,imax, jmin,jmax, kmin,kmax
    extent = pl3dOutput.GetExtent()
    scalarRange = pl3dOutput.GetScalarRange()

    # Planes are specified using a imin,imax, jmin,jmax, kmin,kmax coordinate
    # specification. Min and max i,j,k values are clamped to 0 and maximum value.
    # See the variable named extent for the values.
    #
    plane = vtk.vtkStructuredGridGeometryFilter()
    plane.SetInputData(pl3dOutput)
    plane.SetExtent(10, 10, 1, extent[3], 1, extent[5])

    plane2 = vtk.vtkStructuredGridGeometryFilter()
    plane2.SetInputData(pl3dOutput)
    plane2.SetExtent(30, 30, 1, extent[3], 1, extent[5])

    plane3 = vtk.vtkStructuredGridGeometryFilter()
    plane3.SetInputData(pl3dOutput)
    plane3.SetExtent(45, 45, 1, extent[3], 1, extent[5])

    # We use an append filter because that way we can do the warping, etc. just
    # using a single pipeline and actor.
    #
    appendF = vtk.vtkAppendPolyData()
    appendF.AddInputConnection(plane.GetOutputPort())
    appendF.AddInputConnection(plane2.GetOutputPort())
    appendF.AddInputConnection(plane3.GetOutputPort())

    # Warp
    warp = vtk.vtkWarpVector()
    warp.SetInputConnection(appendF.GetOutputPort())
    warp.SetScaleFactor(0.005)
    warp.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputData(warp.GetPolyDataOutput())
    normals.SetFeatureAngle(45)

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(normals.GetOutputPort())
    planeMapper.SetScalarRange(scalarRange)

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)

    # The outline provides context for the data and the planes.
    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(pl3dOutput)

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

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

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size
    #
    ren.AddActor(planeActor)
    ren.AddActor(outlineActor)
    ren.SetBackground(colors.GetColor3d('BkgColor'))

    renWin.SetSize(512, 512)
    renWin.SetWindowName('VelocityProfile')

    iren.Initialize()

    renWin.Render()

    ren.GetActiveCamera().SetPosition(19.8562, -31.8912, 47.0755)
    ren.GetActiveCamera().SetFocalPoint(8.255, 0.147815, 29.7631)
    ren.GetActiveCamera().SetViewUp(-0.0333325, 0.465756, 0.884285)
    ren.GetActiveCamera().SetClippingRange(17.3078, 64.6375)
    renWin.Render()

    iren.Start()
Ejemplo n.º 10
0
def main():
    fn = get_program_parameters()
    if fn:
        polyData = ReadPolyData(fn)
    else:
        # Use a sphere
        source = vtk.vtkSphereSource()
        source.SetThetaResolution(100)
        source.SetPhiResolution(100)
        source.Update()
        polyData = source.GetOutput()

    colors = vtk.vtkNamedColors()
    colors.SetColor('HighNoonSun', [255, 255, 251, 255])  # Color temp. 5400°K
    colors.SetColor('100W Tungsten',
                    [255, 214, 170, 255])  # Color temp. 2850°K

    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Silver'))

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(640, 480)
    renderWindow.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    light1 = vtk.vtkLight()
    light1.SetFocalPoint(0, 0, 0)
    light1.SetPosition(0, 1, 0.2)
    light1.SetColor(colors.GetColor3d('HighNoonSun'))
    light1.SetIntensity(0.3)
    renderer.AddLight(light1)

    light2 = vtk.vtkLight()
    light2.SetFocalPoint(0, 0, 0)
    light2.SetPosition(1.0, 1.0, 1.0)
    light2.SetColor(colors.GetColor3d('100W Tungsten'))
    light2.SetIntensity(0.8)
    renderer.AddLight(light2)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetAmbientColor(colors.GetColor3d('SaddleBrown'))
    actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Sienna'))
    actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    actor.GetProperty().SetSpecular(0.51)
    actor.GetProperty().SetDiffuse(0.7)
    actor.GetProperty().SetAmbient(0.7)
    actor.GetProperty().SetSpecularPower(30.0)
    actor.GetProperty().SetOpacity(1.0)
    renderer.AddActor(actor)

    # Add a plane
    bounds = polyData.GetBounds()

    rnge = [0] * 3
    rnge[0] = bounds[1] - bounds[0]
    rnge[1] = bounds[3] - bounds[2]
    rnge[2] = bounds[5] - bounds[4]
    print("range: ", ', '.join(["{0:0.6f}".format(i) for i in rnge]))
    expand = 1.0
    THICKNESS = rnge[2] * 0.1
    plane = vtk.vtkCubeSource()
    plane.SetCenter((bounds[1] + bounds[0]) / 2.0, bounds[2] + THICKNESS / 2.0,
                    (bounds[5] + bounds[4]) / 2.0)
    plane.SetXLength(bounds[1] - bounds[0] + (rnge[0] * expand))
    plane.SetYLength(THICKNESS)
    plane.SetZLength(bounds[5] - bounds[4] + (rnge[2] * expand))

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(plane.GetOutputPort())

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    renderer.AddActor(planeActor)

    renderWindow.SetMultiSamples(0)

    shadows = vtk.vtkShadowMapPass()

    seq = vtk.vtkSequencePass()

    passes = vtk.vtkRenderPassCollection()
    passes.AddItem(shadows.GetShadowMapBakerPass())
    passes.AddItem(shadows)
    seq.SetPasses(passes)

    cameraP = vtk.vtkCameraPass()
    cameraP.SetDelegatePass(seq)

    # Tell the renderer to use our render pass pipeline
    glrenderer = renderer
    glrenderer.SetPass(cameraP)

    renderer.GetActiveCamera().SetPosition(-0.2, 0.2, 1)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 1, 0)
    renderer.GetActiveCamera().OrthogonalizeViewUp()
    renderer.ResetCamera()
    renderer.GetActiveCamera().Dolly(2.25)
    renderer.ResetCameraClippingRange()
    renderWindow.SetWindowName('Shadows')
    renderWindow.Render()

    interactor.Start()
Ejemplo n.º 11
0
def main():
    # random.seed=1
    inputFilename = "Hulk.stl"  # , numberOfCuts = get_program_parameters()

    colors = vtk.vtkNamedColors()

    reader = vtk.vtkSTLReader()
    reader.SetFileName(inputFilename)
    reader.Update()

    slicerA = SlicerAlgorithm()
    slicerA.SetInputConnection(reader.GetOutputPort())

    slicerA.Update()

    slicerMapperA = vtk.vtkPolyDataMapper()
    slicerMapperA.SetInputConnection(slicerA.GetOutputPort())

    #create cutter actor
    slicerActorA = vtk.vtkActor()
    slicerActorA.GetProperty().SetColor(1.0, 1, 0)
    slicerActorA.GetProperty().SetLineWidth(2)
    slicerActorA.SetMapper(slicerMapperA)

    slicerB = SlicerAlgorithm()
    slicerB.SetInputConnection(0, reader.GetOutputPort())
    slicerB.Update()

    optimizer = SlicerOptimizer()
    optimizer.SetInputConnection(0, slicerA.GetOutputPort())
    optimizer.SetInputConnection(1, slicerB.GetOutputPort())
    optimizer.Update()

    slicerMapperB = vtk.vtkPolyDataMapper()
    slicerMapperB.SetInputConnection(optimizer.GetOutputPort())

    #create cutter actor
    slicerActorB = vtk.vtkActor()
    slicerActorB.GetProperty().SetColor(0, 1, 1)
    slicerActorB.GetProperty().SetLineWidth(2)
    slicerActorB.SetMapper(slicerMapperB)

    # Create the model actor
    modelMapper = vtk.vtkPolyDataMapper()
    modelMapper.SetInputConnection(reader.GetOutputPort())

    modelActor = vtk.vtkActor()
    modelActor.GetProperty().SetColor(colors.GetColor3d("Flesh"))
    modelActor.SetMapper(modelMapper)

    tfFilter = vtk.vtkTransformPolyDataFilter()
    tfFilter.SetInputData(reader.GetOutput())
    tfFilter.SetTransform(optimizer.icp)
    tfFilter.Update()

    modelMapper2 = vtk.vtkPolyDataMapper()
    modelMapper2.SetInputConnection(tfFilter.GetOutputPort())

    modelActor2 = vtk.vtkActor()
    modelActor2.GetProperty().SetColor(colors.GetColor3d("Flesh"))
    modelActor2.SetMapper(modelMapper2)

    # Create renderers and add the cutter and model actors.
    renderer = vtk.vtkRenderer()
    renderer.AddActor(slicerActorA)
    renderer.AddActor(slicerActorB)
    renderer.AddActor(modelActor)
    renderer.AddActor(modelActor2)

    # Add renderer to renderwindow and render
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(600, 600)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderer.SetBackground(colors.GetColor3d("Burlywood"))
    renderer.GetActiveCamera().SetParallelProjection(True)
    renderer.GetActiveCamera().SetPosition(-1, 0, 0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 0, 1)
    # renderer.GetActiveCamera().Azimuth(30)
    # renderer.GetActiveCamera().Elevation(30)

    renderer.ResetCamera()
    renderWindow.Render()

    interactor.Initialize()

    # Sign up to receive TimerEvent
    cb = vtkTimerCallback()
    cb.slicerActorA = slicerActorA
    cb.slicerActorB = slicerActorB
    cb.slicerA = slicerA
    cb.slicerB = slicerB
    cb.tfFilter = tfFilter
    cb.optimizer = optimizer
    interactor.AddObserver('TimerEvent', cb.execute)
    interactor.CreateRepeatingTimer(10)

    interactor.Start()
Ejemplo n.º 12
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a cube
    cube = vtk.vtkCubeSource()
    cube.SetXLength(40)
    cube.SetYLength(30)
    cube.SetZLength(20)
    cubeMapper = vtk.vtkPolyDataMapper()
    cubeMapper.SetInputConnection(cube.GetOutputPort())

    # create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
    plane = vtk.vtkPlane()
    plane.SetOrigin(10, 0, 0)
    plane.SetNormal(1, 0, 0)

    # create cutter
    cutter = vtk.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInputConnection(cube.GetOutputPort())
    cutter.Update()
    cutterMapper = vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection(cutter.GetOutputPort())

    # create plane actor
    planeActor = vtk.vtkActor()
    planeActor.GetProperty().SetColor(colors.GetColor3d('Yellow'))
    planeActor.GetProperty().SetLineWidth(2)
    planeActor.GetProperty().SetAmbient(1.0)
    planeActor.GetProperty().SetDiffuse(0.0)
    planeActor.SetMapper(cutterMapper)

    # create cube actor
    cubeActor = vtk.vtkActor()
    cubeActor.GetProperty().SetColor(colors.GetColor3d('Aquamarine'))
    cubeActor.GetProperty().SetOpacity(0.5)
    cubeActor.SetMapper(cubeMapper)

    # create renderers and add actors of plane and cube
    ren = vtk.vtkRenderer()
    ren.AddActor(planeActor)
    ren.AddActor(cubeActor)
    ren.SetBackground(colors.GetColor3d('Silver'))

    # Add renderer to renderwindow and render
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(600, 600)
    renWin.SetWindowName('Cutter')
    renWin.Render()

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    camera = ren.GetActiveCamera()
    camera.SetPosition(-37.2611, -86.2155, 44.841)
    camera.SetFocalPoint(0.569422, -1.65124, -2.49482)
    camera.SetViewUp(0.160129, 0.42663, 0.890138)
    camera.SetDistance(104.033)
    camera.SetClippingRange(55.2019, 165.753)

    renWin.Render()

    iren.Start()
Ejemplo n.º 13
0
def main(argv):
    colors = vtk.vtkNamedColors()

    #
    # Next we create an instance of vtkConeSource and set some of its
    # properties. The instance of vtkConeSource 'cone' is part of a
    # visualization pipeline (it is a source process object) it produces data
    # (output type is vtkPolyData) which other filters may process.
    #
    cone = vtk.vtkConeSource()
    cone.SetHeight(3.0)
    cone.SetRadius(1.0)
    cone.SetResolution(10)

    #
    # In this example we terminate the pipeline with a mapper process object.
    # (Intermediate filters such as vtkShrinkPolyData could be inserted in
    # between the source and the mapper.)  We create an instance of
    # vtkPolyDataMapper to map the polygonal data into graphics primitives. We
    # connect the output of the cone source to the input of this mapper.
    #
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    #
    # Create an actor to represent the cone. The actor orchestrates rendering
    # of the mapper's graphics primitives. An actor also refers to properties
    # via a vtkProperty instance, and includes an internal transformation
    # matrix. We set this actor's mapper to be coneMapper which we created
    # above.
    #
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    #
    # Create two renderers and assign actors to them. A renderer renders into
    # a viewport within the vtkRenderWindow. It is part or all of a window on
    # the screen and it is responsible for drawing the actors it has.  We also
    # set the background color here. In this example we are adding the same
    # actor to two different renderers it is okay to add different actors to
    # different renderers as well.
    #
    ren1 = vtk.vtkRenderer()
    ren1.AddActor(coneActor)
    ren1.SetBackground(colors.GetColor3d('RoyalBlue'))

    ren1.SetViewport(0.0, 0.0, 0.5, 1.0)

    ren2 = vtk.vtkRenderer()
    ren2.AddActor(coneActor)
    ren2.SetBackground(colors.GetColor3d('DodgerBlue'))
    ren2.SetViewport(0.5, 0.0, 1.0, 1.0)

    #
    # Finally we create the render window which will show up on the screen.
    # We put our renderer into the render window using AddRenderer. We also
    # set the size to be 300 pixels by 300.
    #
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    renWin.AddRenderer(ren2)
    renWin.SetSize(600, 300)
    renWin.SetWindowName('Tutorial_Step3')

    #
    # Make one view 90 degrees from other.
    #
    ren1.ResetCamera()
    ren1.GetActiveCamera().Azimuth(90)

    #
    # Now we loop over 360 degrees and render the cones each time.
    #
    for i in range(0, 360):  # render the image
        renWin.Render()
        # rotate the active camera by one degree
        ren1.GetActiveCamera().Azimuth(1)
        ren2.GetActiveCamera().Azimuth(1)
Ejemplo n.º 14
0
    def __init__(self):
        self.cn = {
            'Red':['IndianRed', 'LightCoral', 'Salmon', 'DarkSalmon',\
                   'LightSalmon', 'Red', 'Crimson', 'FireBrick', 'DarkRed'],
            'Pink':['Pink', 'LightPink', 'HotPink', 'DeepPink',\
                    'MediumVioletRed', 'PaleVioletRed'],
            'Orange':['LightSalmon', 'Coral', 'Tomato', 'OrangeRed',\
                      'DarkOrange', 'Orange'],
            'Yellow':['Gold', 'Yellow', 'LightYellow', 'LemonChiffon',\
                      'LightGoldenrodYellow', 'PapayaWhip', 'Moccasin',\
                      'PeachPuff', 'PaleGoldenrod', 'Khaki', 'DarkKhaki'],
            'Purple':['Lavender', 'Thistle', 'Plum', 'Violet', 'Orchid',\
                      'Fuchsia', 'Magenta', 'MediumOrchid', 'MediumPurple',\
                      'BlueViolet', 'DarkViolet', 'DarkOrchid', 'DarkMagenta',\
                      'Purple', 'Indigo', 'DarkSlateBlue', 'SlateBlue',\
                      'MediumSlateBlue'],
            'Green':['GreenYellow', 'Chartreuse', 'LawnGreen', 'Lime',\
                     'LimeGreen', 'PaleGreen', 'LightGreen',\
                     'MediumSpringGreen', 'SpringGreen', 'MediumSeaGreen',\
                     'SeaGreen', 'ForestGreen', 'Green', 'DarkGreen',\
                     'YellowGreen', 'OliveDrab', 'Olive', 'DarkOliveGreen',\
                     'MediumAquamarine', 'DarkSeaGreen', 'LightSeaGreen',\
                     'DarkCyan', 'Teal'],
            'Blue/Cyan':['Aqua', 'Cyan', 'LightCyan', 'PaleTurquoise',\
                         'Aquamarine', 'Turquoise', 'MediumTurquoise',\
                         'DarkTurquoise', 'CadetBlue', 'SteelBlue',\
                         'LightSteelBlue', 'PowderBlue', 'LightBlue',\
                         'SkyBlue', 'LightSkyBlue', 'DeepSkyBlue',\
                         'DodgerBlue', 'CornflowerBlue', 'RoyalBlue', 'Blue',\
                         'MediumBlue', 'DarkBlue', 'Navy', 'MidnightBlue'],
            'Brown':['Cornsilk', 'BlanchedAlmond', 'Bisque', 'NavajoWhite',\
                     'Wheat', 'BurlyWood', 'Tan', 'RosyBrown', 'SandyBrown',\
                     'Goldenrod', 'DarkGoldenrod', 'Peru', 'Chocolate',\
                     'SaddleBrown', 'Sienna', 'Brown', 'Maroon'],
            'White':['White', 'Snow', 'Honeydew', 'MintCream', 'Azure',\
                     'AliceBlue', 'GhostWhite', 'WhiteSmoke', 'Seashell',\
                     'Beige', 'OldLace', 'FloralWhite', 'Ivory',\
                     'AntiqueWhite', 'Linen',\
                     'LavenderBlush', 'MistyRose'],
            'Gray':['Gainsboro', 'LightGrey', 'Silver', 'DarkGray', 'Gray',\
                    'DimGray', 'LightSlateGray', 'SlateGray', 'DarkSlateGray',\
                    'Black']
            }
        # Ordering of the tables and when to start and end a column of tables
        # in the layout.
        self.cnOrder = ['Red', 'Pink', 'Orange', 'Yellow', 'Purple', 'Green',\
                        'Blue/Cyan', 'Brown', 'White', 'Gray']
        self.cnStartTable = ['Red', 'Green', 'Brown']
        self.cnEndTable = ['Purple', 'Blue/Cyan', 'Gray']

        self.vtkcn = {
            'Whites':['antique_white', 'azure', 'bisque', 'blanched_almond',\
                      'cornsilk', 'eggshell', 'floral_white', 'gainsboro',\
                      'ghost_white', 'honeydew', 'ivory', 'lavender',\
                      'lavender_blush', 'lemon_chiffon', 'linen', 'mint_cream',\
                      'misty_rose', 'moccasin', 'navajo_white', 'old_lace',\
                      'papaya_whip',  'peach_puff', 'seashell', 'snow',\
                      'thistle', 'titanium_white', 'wheat', 'white',\
                      'white_smoke', 'zinc_white'],
            'Greys':['cold_grey', 'dim_grey', 'grey', 'light_grey',\
                     'slate_grey', 'slate_grey_dark', 'slate_grey_light',\
                     'warm_grey'],
            'Blacks':['black', 'ivory_black', 'lamp_black'],
            'Reds':['alizarin_crimson', 'brick', 'cadmium_red_deep', 'coral',\
                    'coral_light', 'deep_pink', 'english_red', 'firebrick',\
                    'geranium_lake', 'hot_pink', 'indian_red', 'light_salmon',\
                    'madder_lake_deep', 'maroon', 'pink', 'pink_light',\
                    'raspberry', 'red', 'rose_madder', 'salmon', 'tomato',\
                    'venetian_red'],
            'Browns':['beige', 'brown', 'brown_madder', 'brown_ochre',\
                      'burlywood', 'burnt_sienna', 'burnt_umber', 'chocolate',\
                      'deep_ochre', 'flesh', 'flesh_ochre', 'gold_ochre',\
                      'greenish_umber', 'khaki', 'khaki_dark', 'light_beige',\
                      'peru', 'rosy_brown', 'raw_sienna', 'raw_umber', 'sepia',\
                      'sienna', 'saddle_brown', 'sandy_brown', 'tan',\
                      'van_dyke_brown'],
            'Oranges':['cadmium_orange', 'cadmium_red_light', 'carrot',\
                       'dark_orange', 'mars_orange', 'mars_yellow', 'orange',\
                       'orange_red', 'yellow_ochre'],
            'Yellows':['aureoline_yellow', 'banana', 'cadmium_lemon',\
                       'cadmium_yellow', 'cadmium_yellow_light', 'gold',\
                       'goldenrod', 'goldenrod_dark', 'goldenrod_light',\
                       'goldenrod_pale', 'light_goldenrod', 'melon',\
                       'naples_yellow_deep', 'yellow', 'yellow_light'],
            'Greens':['chartreuse', 'chrome_oxide_green', 'cinnabar_green',\
                      'cobalt_green', 'emerald_green', 'forest_green', 'green',\
                      'green_dark', 'green_pale', 'green_yellow', 'lawn_green',\
                      'lime_green', 'mint', 'olive', 'olive_drab',\
                      'olive_green_dark', 'permanent_green', 'sap_green',\
                      'sea_green', 'sea_green_dark', 'sea_green_medium',\
                      'sea_green_light', 'spring_green', 'spring_green_medium',\
                      'terre_verte', 'viridian_light', 'yellow_green'],
            'Cyans':['aquamarine', 'aquamarine_medium', 'cyan', 'cyan_white',\
                     'turquoise', 'turquoise_dark', 'turquoise_medium',\
                     'turquoise_pale'],
            'Blues':['alice_blue', 'blue', 'blue_light', 'blue_medium',\
                     'cadet', 'cobalt', 'cornflower', 'cerulean', 'dodger_blue',\
                     'indigo', 'manganese_blue', 'midnight_blue', 'navy',\
                     'peacock',  'powder_blue', 'royal_blue', 'slate_blue',\
                     'slate_blue_dark', 'slate_blue_light',\
                     'slate_blue_medium', 'sky_blue', 'sky_blue_deep',\
                     'sky_blue_light', 'steel_blue', 'steel_blue_light',\
                     'turquoise_blue', 'ultramarine'],
            'Magentas':['blue_violet', 'cobalt_violet_deep', 'magenta',\
                        'orchid', 'orchid_dark', 'orchid_medium',\
                        'permanent_red_violet', 'plum', 'purple',\
                        'purple_medium', 'ultramarine_violet', 'violet',\
                        'violet_dark', 'violet_red', 'violet_red_medium',\
                        'violet_red_pale']
            }
        # Ordering of the tables and when to start and end a column of tables
        # in the layout.
        self.vtkcnOrder = ['Whites', 'Greys', 'Blacks', 'Reds', 'Oranges',\
                           'Browns', 'Yellows', 'Greens', 'Cyans', 'Blues',\
                           'Magentas']
        self.vtkcnStartTable = ['Whites', 'Browns', 'Cyans']
        self.vtkcnEndTable = ['Oranges', 'Greens', 'Magentas']
        # The vtkNamedColors class.
        self.nc = vtk.vtkNamedColors()
Ejemplo n.º 15
0
    def test(self):
        '''
          Create a cone, contour it using the banded contour filter and
              color it with the primary additive and subtractive colors.
        '''
        namedColors = vtk.vtkNamedColors()
        # Test printing of the object
        # Uncomment if desired
        #print namedColors

        # How to get a list of colors
        colors = namedColors.GetColorNames()
        colors = colors.split('\n')
        # Uncomment if desired
        #print 'Number of colors:', len(colors)
        #print colors

        # How to get a list of a list of synonyms.
        syn = namedColors.GetSynonyms()
        syn = syn.split('\n\n')
        synonyms = []
        for ele in syn:
            synonyms.append(ele.split('\n'))
        # Uncomment if desired
        #print 'Number of synonyms:', len(synonyms)
        #print synonyms

        # Create a cone
        coneSource = vtk.vtkConeSource()
        coneSource.SetCenter(0.0, 0.0, 0.0)
        coneSource.SetRadius(5.0)
        coneSource.SetHeight(10)
        coneSource.SetDirection(0,1,0)
        coneSource.Update();

        bounds = [1.0,-1.0,1.0,-1.0,1.0,-1.0]
        coneSource.GetOutput().GetBounds(bounds)

        elevation = vtk.vtkElevationFilter()
        elevation.SetInputConnection(coneSource.GetOutputPort());
        elevation.SetLowPoint(0,bounds[2],0);
        elevation.SetHighPoint(0,bounds[3],0);

        bcf = vtk.vtkBandedPolyDataContourFilter()
        bcf.SetInputConnection(elevation.GetOutputPort());
        bcf.SetScalarModeToValue();
        bcf.GenerateContourEdgesOn();
        bcf.GenerateValues(7,elevation.GetScalarRange());

        # Build a simple lookup table of
        # primary additive and subtractive colors.
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(7);
        rgba = [0.0,0.0,0.0,1.0]
        # Test setting and getting a color here.
        namedColors.GetColor("Red",rgba);
        namedColors.SetColor("My Red",rgba)
        namedColors.GetColor("My Red",rgba);
        lut.SetTableValue(0,rgba);
        namedColors.GetColor("DarkGreen",rgba);
        lut.SetTableValue(1,rgba);
        namedColors.GetColor("Blue",rgba);
        lut.SetTableValue(2,rgba);
        namedColors.GetColor("Cyan",rgba);
        lut.SetTableValue(3,rgba);
        namedColors.GetColor("Magenta",rgba);
        lut.SetTableValue(4,rgba);
        namedColors.GetColor("Yellow",rgba);
        lut.SetTableValue(5,rgba);
        namedColors.GetColor("White",rgba);
        lut.SetTableValue(6,rgba);
        lut.SetTableRange(elevation.GetScalarRange());
        lut.Build();

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(bcf.GetOutputPort());
        mapper.SetLookupTable(lut);
        mapper.SetScalarModeToUseCellData();

        contourLineMapper = vtk.vtkPolyDataMapper()
        contourLineMapper.SetInputData(bcf.GetContourEdgesOutput());
        contourLineMapper.SetScalarRange(elevation.GetScalarRange());
        contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset();

        actor = vtk.vtkActor()
        actor.SetMapper(mapper);

        contourLineActor = vtk.vtkActor()
        contourLineActor.SetMapper(contourLineMapper);
        rgb = [0.0,0.0,0.0]
        namedColors.GetColorRGB("black",rgb)
        contourLineActor.GetProperty().SetColor(rgb);

        renderer = vtk.vtkRenderer()
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer);
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renderWindow);

        renderer.AddActor(actor);
        renderer.AddActor(contourLineActor);
        namedColors.GetColorRGB("SteelBlue",rgb)
        renderer.SetBackground(rgb);

        renderWindow.Render();
        img_file = "TestNamedColorsIntegration.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Ejemplo n.º 16
0
def main(args):
    img_fn_array = []

    if args.dir:
        normpath = os.path.normpath("/".join([args.dir, '**', '*']))
        for img_fn in glob.iglob(normpath, recursive=True):
            if os.path.isfile(img_fn) and True in [ext in img_fn for ext in [".json"]]:
                img_fn_array.append(img_fn)

    L_json_path = []
    img_fn_array = sorted(img_fn_array)
    for i in range(0, len(img_fn_array), 2):
        L_tmp = [img_fn_array[i], img_fn_array[i+1]]
        L_json_path.append(L_tmp)

    
    for json_obj in L_json_path:
        vtk_landmarks = vtk.vtkAppendPolyData()

        for file in json_obj:
            json_file = pd.read_json(file)
            json_file.head()
            markups = json_file.loc[0,'markups']
            controlPoints = markups['controlPoints']
            number_landmarks = len(controlPoints)

            L_landmark_position = []
            for i in range(number_landmarks):
                L_landmark_position.append(controlPoints[i]["position"])

            for i in range(number_landmarks):
                # Create a sphere
                sphereSource = vtk.vtkSphereSource()
                sphereSource.SetCenter(L_landmark_position[i][0],L_landmark_position[i][1],L_landmark_position[i][2])
                sphereSource.SetRadius(args.radius_sphere)

                # Make the surface smooth.
                sphereSource.SetPhiResolution(100)
                sphereSource.SetThetaResolution(100)
                sphereSource.Update()

                vtk_landmarks.AddInputData(sphereSource.GetOutput())
                vtk_landmarks.Update()

        basename = os.path.basename(json_obj[0]).split("_")[0]
        filename = basename + "_landmarks.vtk"
        output = os.path.join(args.out, filename)
        Write(vtk_landmarks.GetOutput(), output)


    if args.visualize:
        colors = vtk.vtkNamedColors()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(vtk_landmarks.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk"))

        renderer = vtk.vtkRenderer()
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetWindowName("Sphere")
        renderWindow.AddRenderer(renderer)
        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        renderWindowInteractor.SetRenderWindow(renderWindow)

        renderer.AddActor(actor)
        renderer.SetBackground(colors.GetColor3d("DarkGreen"))

        renderWindow.Render()
        renderWindowInteractor.Start()
Ejemplo n.º 17
0
def main():
    colors = vtk.vtkNamedColors()

    points = vtk.vtkPoints()
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(2.0, 0.0, 0.0)
    points.InsertNextPoint(3.0, 0.0, 0.0)
    points.InsertNextPoint(4.0, 0.0, 0.0)

    lines = vtk.vtkCellArray()
    line = vtk.vtkLine()
    line.GetPointIds().SetId(0, 0)
    line.GetPointIds().SetId(1, 1)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 1)
    line.GetPointIds().SetId(1, 2)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 2)
    line.GetPointIds().SetId(1, 3)
    lines.InsertNextCell(line)
    line.GetPointIds().SetId(0, 3)
    line.GetPointIds().SetId(1, 4)
    lines.InsertNextCell(line)

    warpData = vtk.vtkDoubleArray()
    warpData.SetNumberOfComponents(3)
    warpData.SetName("warpData")
    warp = [0.0, 0.0, 0.0]
    warp[1] = 0.0
    warpData.InsertNextTuple(warp)
    warp[1] = 0.1
    warpData.InsertNextTuple(warp)
    warp[1] = 0.3
    warpData.InsertNextTuple(warp)
    warp[1] = 0.0
    warpData.InsertNextTuple(warp)
    warp[1] = 0.1
    warpData.InsertNextTuple(warp)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(lines)
    polydata.GetPointData().AddArray(warpData)
    polydata.GetPointData().SetActiveVectors(warpData.GetName())

    # WarpVector will use the array marked as active vector in polydata
    # it has to be a 3 component array
    # with the same number of tuples as points in polydata
    warpVector = vtk.vtkWarpVector()
    warpVector.SetInputData(polydata)
    warpVector.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(warpVector.GetPolyDataOutput())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('cobalt_green'))

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('WarpVector')

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindow.Render()
    renderWindowInteractor.Start()
Ejemplo n.º 18
0
    def build_jpeg_preview(
        self,
        file_path: str,
        preview_name: str,
        cache_path: str,
        page_id: int,
        extension: str = ".jpg",
        size: ImgDims = None,
        mimetype: str = "",
    ) -> None:
        if not size:
            size = self.default_size

        tmp_filename = "{}.png".format(str(uuid.uuid4()))
        if tempfile.tempdir:
            tmp_filepath = os.path.join(tempfile.tempdir, tmp_filename)
        else:
            tmp_filepath = tmp_filename

        colors = vtkNamedColors()

        reader = vtkSTLReader()  # TODO analyse wich file format is use
        reader.SetFileName(file_path)

        mapper = vtkPolyDataMapper()
        mapper.SetInputConnection(reader.GetOutputPort())

        actor = vtkActor()
        actor.SetMapper(mapper)

        rotation = (-70, 0, 45)
        R_x, R_y, R_z = rotation  # TODO set a good looking default orientation
        actor.RotateX(R_x)
        actor.RotateY(R_y)
        actor.RotateZ(R_z)

        # Create a rendering window and renderer
        ren = vtkRenderer()
        renWin = vtkRenderWindow()
        renWin.OffScreenRenderingOn()
        renWin.AddRenderer(ren)
        ren.SetBackground(colors.GetColor3d("white"))

        # Assign actor to the renderer
        ren.AddActor(actor)

        renWin.Render()

        # Write image
        windowto_image_filter = vtkWindowToImageFilter()
        windowto_image_filter.SetInput(renWin)
        # windowto_image_filter.SetScale(scale)  # image scale
        windowto_image_filter.SetInputBufferTypeToRGBA()
        writer = vtkPNGWriter()
        writer.SetFileName(tmp_filepath)
        writer.SetInputConnection(windowto_image_filter.GetOutputPort())
        writer.Write()

        return ImagePreviewBuilderPillow().build_jpeg_preview(
            tmp_filepath, preview_name, cache_path, page_id, extension, size,
            mimetype)
def main():
    '''
    :return: The render window interactor.
    '''

    nc = vtk.vtkNamedColors()

    # Provide some geometry
    resolution = 3

    plane11 = vtk.vtkPlaneSource()
    plane11.SetXResolution(resolution)
    plane11.SetYResolution(resolution)

    plane12 = vtk.vtkPlaneSource()
    plane12.SetXResolution(resolution)
    plane12.SetYResolution(resolution)

    tableSize = max(resolution * resolution + 1, 10)

    #  Force an update so we can set cell data
    plane11.Update()
    plane12.Update()

    #  Get the lookup tables mapping cell data to colors
    lut1 = MakeLUT(tableSize)
    lut2 = MakeLUTFromCTF(tableSize)

    colorData1 = vtk.vtkUnsignedCharArray()
    colorData1.SetName('colors') # Any name will work here.
    colorData1.SetNumberOfComponents(3)
    print('Using a lookup table from a set of named colors.')
    MakeCellData(tableSize, lut1, colorData1)
    # Then use SetScalars() to add it to the vtkPolyData structure,
    # this will then be interpreted as a color table.
    plane11.GetOutput().GetCellData().SetScalars(colorData1)

    colorData2 = vtk.vtkUnsignedCharArray()
    colorData2.SetName('colors') # Any name will work here.
    colorData2.SetNumberOfComponents(3)
    print('Using a lookup table created from a color transfer function.')
    MakeCellData(tableSize, lut2, colorData2)
    plane12.GetOutput().GetCellData().SetScalars(colorData2)

    # Set up actor and mapper
    mapper11 = vtk.vtkPolyDataMapper()
    mapper11.SetInputConnection(plane11.GetOutputPort())
    # Now, instead of doing this:
    # mapper11.SetScalarRange(0, tableSize - 1)
    # mapper11.SetLookupTable(lut1)
    # We can just use the color data that we created from the lookup table and
    # assigned to the cells:
    mapper11.SetScalarModeToUseCellData()
    mapper11.Update()

    mapper12 = vtk.vtkPolyDataMapper()
    mapper12.SetInputConnection(plane12.GetOutputPort())
    mapper12.SetScalarModeToUseCellData()
    mapper12.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName('pdlut.vtp')
    writer.SetInputData(mapper11.GetInput())
    # This is set so we can see the data in a text editor.
    writer.SetDataModeToAscii()
    writer.Write()
    writer.SetFileName('pdctf.vtp')
    writer.SetInputData(mapper12.GetInput())
    writer.Write()

    actor11 = vtk.vtkActor()
    actor11.SetMapper(mapper11)
    actor12 = vtk.vtkActor()
    actor12.SetMapper(mapper12)

    # Let's read in the data we wrote out.
    reader1 = vtk.vtkXMLPolyDataReader()
    reader1.SetFileName("pdlut.vtp")

    reader2 = vtk.vtkXMLPolyDataReader()
    reader2.SetFileName("pdctf.vtp")

    mapper21 = vtk.vtkPolyDataMapper()
    mapper21.SetInputConnection(reader1.GetOutputPort())
    mapper21.SetScalarModeToUseCellData()
    mapper21.Update()
    actor21 = vtk.vtkActor()
    actor21.SetMapper(mapper11)

    mapper22 = vtk.vtkPolyDataMapper()
    mapper22.SetInputConnection(reader2.GetOutputPort())
    mapper22.SetScalarModeToUseCellData()
    mapper22.Update()
    actor22 = vtk.vtkActor()
    actor22.SetMapper(mapper22)

    # Define viewport ranges.
    # (xmin, ymin, xmax, ymax)
    viewport11 = [0.0, 0.0, 0.5, 0.5]
    viewport12 = [0.0, 0.5, 0.5, 1.0]
    viewport21 = [0.5, 0.0, 1.0, 0.5]
    viewport22 = [0.5, 0.5, 1.0, 1.0]

    # Set up the renderers.
    ren11 = vtk.vtkRenderer()
    ren12 = vtk.vtkRenderer()
    ren21 = vtk.vtkRenderer()
    ren22 = vtk.vtkRenderer()

    # Setup the render windows
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(800, 800)
    renWin.AddRenderer(ren11)
    renWin.AddRenderer(ren12)
    renWin.AddRenderer(ren21)
    renWin.AddRenderer(ren22)
    ren11.SetViewport(viewport11)
    ren12.SetViewport(viewport12)
    ren21.SetViewport(viewport21)
    ren22.SetViewport(viewport22)
    ren11.SetBackground(nc.GetColor3d('MidnightBlue'))
    ren12.SetBackground(nc.GetColor3d('MidnightBlue'))
    ren21.SetBackground(nc.GetColor3d('MidnightBlue'))
    ren22.SetBackground(nc.GetColor3d('MidnightBlue'))
    ren11.AddActor(actor11)
    ren12.AddActor(actor12)
    ren21.AddActor(actor21)
    ren22.AddActor(actor22)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    renWin.Render()

    return iren
Ejemplo n.º 20
0
def main():
    colors = vtk.vtkNamedColors()

    # colors.SetColor('bkg', [0.1, 0.2, 0.4, 1.0])

    # Create the RenderWindow, Renderer and both Actors

    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('MidnightBlue'))

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('ContourWidget')
    renderWindow.SetSize(600, 600)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    contourRep = vtk.vtkOrientedGlyphContourRepresentation()
    contourRep.GetLinesProperty().SetColor(colors.GetColor3d('Red'))

    contourWidget = vtk.vtkContourWidget()
    contourWidget.SetInteractor(interactor)
    contourWidget.SetRepresentation(contourRep)
    contourWidget.On()

    for arg in sys.argv:
        if '-Shift' == arg:
            contourWidget.GetEventTranslator().RemoveTranslation(
                vtk.vtkCommand.LeftButtonPressEvent)
            contourWidget.GetEventTranslator().SetTranslation(
                vtk.vtkCommand.LeftButtonPressEvent,
                vtk.vtkWidgetEvent.Translate)
        elif '-Scale' == arg:
            contourWidget.GetEventTranslator().RemoveTranslation(
                vtk.vtkCommand.LeftButtonPressEvent)
            contourWidget.GetEventTranslator().SetTranslation(
                vtk.vtkCommand.LeftButtonPressEvent, vtk.vtkWidgetEvent.Scale)

    pd = vtk.vtkPolyData()

    points = vtk.vtkPoints()

    num_pts = 21
    for i in range(0, num_pts):
        angle = 2.0 * math.pi * i / 20.0
        points.InsertPoint(i, 0.1 * math.cos(angle), 0.1 * math.sin(angle),
                           0.0)
        # lines.InsertNextCell(i)
    vertex_indices = list(range(0, num_pts))
    vertex_indices.append(0)
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(num_pts + 1, vertex_indices)

    pd.SetPoints(points)
    pd.SetLines(lines)

    # contourWidget.Initialize(pd, 1)
    contourWidget.Initialize(pd, 1)
    contourWidget.Render()
    renderer.ResetCamera()
    renderWindow.Render()

    interactor.Initialize()
    interactor.Start()
Ejemplo n.º 21
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor("BkgColor", [51, 77, 102, 255])

    sourceObjects = list()
    sourceObjects.append(vtk.vtkSphereSource())
    sourceObjects[-1].SetPhiResolution(21)
    sourceObjects[-1].SetThetaResolution(21)

    sourceObjects.append(vtk.vtkConeSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCylinderSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCubeSource())
    sourceObjects.append(vtk.vtkPlaneSource())
    sourceObjects.append(vtk.vtkTextSource())
    sourceObjects[-1].SetText("Hello")
    sourceObjects[-1].BackingOff()

    sourceObjects.append(vtk.vtkPointSource())
    sourceObjects[-1].SetNumberOfPoints(500)

    sourceObjects.append(vtk.vtkDiskSource())
    sourceObjects[-1].SetCircumferentialResolution(51)

    sourceObjects.append(vtk.vtkLineSource())

    renderers = list()
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

    # Create one text property for all.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d("Red"))

    # Create a source, renderer, mapper, and actor
    # for each object.
    for i in range(0, len(sourceObjects)):
        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d("Seashell"))
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(sourceObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)
        renderers.append(vtk.vtkRenderer())

    gridDimensions = 3

    # We need a renderer even if there is no actor.
    for i in range(len(sourceObjects), gridDimensions ** 2):
        renderers.append(vtk.vtkRenderer())

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Source Objects Demo")
    rendererSize = 300
    renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions)

    for row in range(0, gridDimensions):
        for col in range(0, gridDimensions):
            index = row * gridDimensions + col
            x0 = float(col) / gridDimensions
            y0 = float(gridDimensions - row - 1) / gridDimensions
            x1 = float(col + 1) / gridDimensions
            y1 = float(gridDimensions - row) / gridDimensions
            renderWindow.AddRenderer(renderers[index])
            renderers[index].SetViewport(x0, y0, x1, y1)

            if index > (len(sourceObjects) - 1):
                continue

            renderers[index].AddActor(actors[index])
            renderers[index].AddActor(textactors[index])
            renderers[index].SetBackground(colors.GetColor3d("BkgColor"))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(30)
            renderers[index].GetActiveCamera().Zoom(0.8)
            renderers[index].ResetCameraClippingRange()

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 22
0
def main():
    file_name, color_scheme = get_program_parameters()

    color_scheme = abs(color_scheme)
    if color_scheme > 2:
        color_scheme = 0;

    colors = vtk.vtkNamedColors()
    # Set the background color. Match those in VTKTextbook.pdf.
    bkg = map(lambda x: x / 256.0, [25, 51, 102])
    colors.SetColor("BkgColor", *bkg)

    # Read a vtk file
    #
    hawaii = vtk.vtkPolyDataReader()
    hawaii.SetFileName(file_name)
    hawaii.Update()
    bounds = [0.0] * 6
    hawaii.GetOutput().GetBounds(bounds)

    elevation = vtk.vtkElevationFilter()
    elevation.SetInputConnection(hawaii.GetOutputPort())
    elevation.SetLowPoint(0, 0, 0)
    elevation.SetHighPoint(0, 0, 1000)
    elevation.SetScalarRange(0, 1000)

    lut = MakeLUT(color_scheme)

    hawaiiMapper = vtk.vtkDataSetMapper()
    hawaiiMapper.SetInputConnection(elevation.GetOutputPort())
    hawaiiMapper.SetScalarRange(0, 1000)
    hawaiiMapper.ScalarVisibilityOn()
    hawaiiMapper.SetLookupTable(lut)

    hawaiiActor = vtk.vtkActor()
    hawaiiActor.SetMapper(hawaiiMapper)

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

    # Add the actors to the renderer, set the background and size
    #
    ren.AddActor(hawaiiActor)
    # Match the window shape to the object.
    # renWin.SetSize(500, int(500 * bounds[1] / bounds[3]))
    renWin.SetSize(500, 500)

    iren.Initialize()

    # Render the image.
    # Centered on Honolulu.
    # Diamond Head is the crater lower left.
    # Punchbowl is the crater in the centre.
    renWin.Render()
    ren.SetBackground(colors.GetColor3d("BkgColor"))
    ren.GetActiveCamera().Zoom(1.5)
    ren.GetActiveCamera().Roll(-90)

    renWin.Render()
    iren.Start()
Ejemplo n.º 23
0
def viewportBorder(renderer, last, color=None):
    '''
    renderer:vtkRenderer
    last:boool
    color:array [0] * 3
    '''
    # points start at upper right and proceed anti-clockwise
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points.InsertPoint(0, 1, 1, 0)
    points.InsertPoint(1, 0, 1, 0)
    points.InsertPoint(2, 0, 0, 0)
    points.InsertPoint(3, 1, 0, 0)

    # create cells, and lines
    cells = vtk.vtkCellArray()
    cells.Initialize()

    lines = vtk.vtkPolyLine()

    # only draw last line if this is the last viewport
    # this prevents double vertical lines at right border
    # if different colors are used for each border, then do
    # not specify last
    if last:
        lines.GetPointIds().SetNumberOfIds(5)
    else:
        lines.GetPointIds().SetNumberOfIds(4)
    for i in range(4):
        lines.GetPointIds().SetId(i, i)
    if last:
        lines.GetPointIds().SetId(4, 0)

    cells.InsertNextCell(lines)

    # now make tge polydata and display it
    poly = vtk.vtkPolyData()
    poly.Initialize()
    poly.SetPoints(points)
    poly.SetLines(cells)

    # use normalized viewport coordinates since
    # they are independent of window size
    coordinate = vtk.vtkCoordinate()
    coordinate.SetCoordinateSystemToNormalizedViewport()

    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputData(poly)
    mapper.SetTransformCoordinate(coordinate)

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)
    if color != None:
        actor.GetProperty().SetColor(color)
    else:
        actor.GetProperty().SetColor(
            vtk.vtkNamedColors().GetColor3d("SlateGray"))

    # line width should be at least 2 to be visible at extremes
    actor.GetProperty().SetLineWidth(4.0)  # Line Width

    renderer.AddViewProp(actor)
Ejemplo n.º 24
0
 def __init__(self):
     self.cs = ColorStructures()
     self.nc = vtk.vtkNamedColors()
     self.htmlRGBA = HTMLToFromRGBAColor()
Ejemplo n.º 25
0
def main():
    colors = vtk.vtkNamedColors()

    # colors.SetColor('leftBkg', [0.6, 0.5, 0.4, 1.0])
    # colors.SetColor('centreBkg', [0.3, 0.1, 0.4, 1.0])
    # colors.SetColor('rightBkg', [0.4, 0.5, 0.6, 1.0])

    sphereSource = vtk.vtkSphereSource()
    sphereSource.Update()

    print('There are %s input points' % sphereSource.GetOutput().GetNumberOfPoints())
    print('There are %s input cells' % sphereSource.GetOutput().GetNumberOfCells())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    # Specify that we want to extract cells 10 through 19
    i = 10
    while i < 20:
        ids.InsertNextValue(i)
        i += 1

    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selectionNode.SetSelectionList(ids)

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    extractSelection = vtk.vtkExtractSelection()
    extractSelection.SetInputConnection(0, sphereSource.GetOutputPort())
    extractSelection.SetInputData(1, selection)
    extractSelection.Update()

    # In selection
    selected = vtk.vtkUnstructuredGrid()
    selected.ShallowCopy(extractSelection.GetOutput())

    print('There are %s points in the selection' % selected.GetNumberOfPoints())
    print('There are %s cells in the selection' % selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)  # invert the selection
    extractSelection.Update()

    notSelected = vtk.vtkUnstructuredGrid()
    notSelected.ShallowCopy(extractSelection.GetOutput())

    print('There are %s points NOT in the selection' % notSelected.GetNumberOfPoints())
    print('There are %s cells NOT in the selection' % notSelected.GetNumberOfCells())

    backfaces = vtk.vtkProperty()
    backfaces.SetColor(colors.GetColor3d('Gold'))

    inputMapper = vtk.vtkDataSetMapper()
    inputMapper.SetInputConnection(sphereSource.GetOutputPort())
    inputActor = vtk.vtkActor()
    inputActor.SetMapper(inputMapper)
    inputActor.SetBackfaceProperty(backfaces)
    inputActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    selectedMapper = vtk.vtkDataSetMapper()
    selectedMapper.SetInputData(selected)

    selectedActor = vtk.vtkActor()
    selectedActor.SetMapper(selectedMapper)
    selectedActor.SetBackfaceProperty(backfaces)
    selectedActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    notSelectedMapper = vtk.vtkDataSetMapper()
    notSelectedMapper.SetInputData(notSelected)

    notSelectedActor = vtk.vtkActor()
    notSelectedActor.SetMapper(notSelectedMapper)
    notSelectedActor.SetBackfaceProperty(backfaces)
    notSelectedActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    # There will be one render window
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(900, 300)
    renderWindow.SetWindowName('ExtractSelectionCells')

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    leftViewport = [0.0, 0.0, 0.33, 1.0]
    centerViewport = [0.33, 0.0, 0.66, 1.0]
    rightViewport = [0.66, 0.0, 1.0, 1.0]

    # Create a camera for all renderers
    camera = vtk.vtkCamera()

    # Setup the renderers
    leftRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(leftRenderer)
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(colors.GetColor3d('BurlyWood'))
    leftRenderer.SetActiveCamera(camera)

    centerRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(centerRenderer)
    centerRenderer.SetViewport(centerViewport)
    centerRenderer.SetBackground(colors.GetColor3d('orchid_dark'))
    centerRenderer.SetActiveCamera(camera)

    rightRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(rightRenderer)
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(colors.GetColor3d('CornflowerBlue'))
    rightRenderer.SetActiveCamera(camera)

    leftRenderer.AddActor(inputActor)
    centerRenderer.AddActor(selectedActor)
    rightRenderer.AddActor(notSelectedActor)

    leftRenderer.ResetCamera()

    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 26
0
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor('leftBkg', [0.6, 0.5, 0.4, 1.0])
    colors.SetColor('centreBkg', [0.1, 0.5, 0.4, 1.0])
    colors.SetColor('rightBkg', [0.4, 0.5, 0.6, 1.0])

    # Create image 1
    source1 = vtk.vtkImageMandelbrotSource()
    source1.SetWholeExtent(0, 255, 0, 255, 0, 0)
    source1.Update()

    source1Double = vtk.vtkImageCast()
    source1Double.SetInputConnection(0, source1.GetOutputPort())
    source1Double.SetOutputScalarTypeToDouble()

    # Create image 2
    source2 = vtk.vtkImageSinusoidSource()
    source2.SetWholeExtent(0, 255, 0, 255, 0, 0)
    source2.Update()

    # Do the sum
    sumFilter = vtk.vtkImageWeightedSum()
    sumFilter.SetWeight(0, 0.8)
    sumFilter.SetWeight(1, 0.2)
    sumFilter.AddInputConnection(source1Double.GetOutputPort())
    sumFilter.AddInputConnection(source2.GetOutputPort())
    sumFilter.Update()

    # Display the images
    source1CastFilter = vtk.vtkImageCast()
    source1CastFilter.SetInputConnection(source1.GetOutputPort())
    source1CastFilter.SetOutputScalarTypeToUnsignedChar()
    source1CastFilter.Update()

    source2CastFilter = vtk.vtkImageCast()
    source2CastFilter.SetInputConnection(source2.GetOutputPort())
    source2CastFilter.SetOutputScalarTypeToUnsignedChar()
    source2CastFilter.Update()

    summedCastFilter = vtk.vtkImageCast()
    summedCastFilter.SetInputConnection(sumFilter.GetOutputPort())
    summedCastFilter.SetOutputScalarTypeToUnsignedChar()
    summedCastFilter.Update()

    # Create actors
    source1Actor = vtk.vtkImageActor()
    source1Actor.GetMapper().SetInputConnection(
        source1CastFilter.GetOutputPort())

    source2Actor = vtk.vtkImageActor()
    source2Actor.GetMapper().SetInputConnection(
        source2CastFilter.GetOutputPort())

    summedActor = vtk.vtkImageActor()
    summedActor.GetMapper().SetInputConnection(
        summedCastFilter.GetOutputPort())

    # There will be one render window
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(600, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    leftViewport = [0.0, 0.0, 0.33, 1.0]
    centerViewport = [0.33, 0.0, .66, 1.0]
    rightViewport = [0.66, 0.0, 1.0, 1.0]

    # Setup renderers
    leftRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(leftRenderer)
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(colors.GetColor3d('leftBkg'))

    centerRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(centerRenderer)
    centerRenderer.SetViewport(centerViewport)
    centerRenderer.SetBackground(colors.GetColor3d('centreBkg'))

    rightRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(rightRenderer)
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(colors.GetColor3d('rightBkg'))

    leftRenderer.AddActor(source1Actor)
    centerRenderer.AddActor(source2Actor)
    rightRenderer.AddActor(summedActor)

    leftRenderer.ResetCamera()
    centerRenderer.ResetCamera()
    rightRenderer.ResetCamera()

    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 27
0
def main():
    file_name, figure = get_program_parameters()

    colors = vtk.vtkNamedColors()
    # Set the background color. Match those in VTKTextbook.pdf.
    bkg1 = map(lambda x: x / 256.0, [60, 93, 144])
    bkg2 = map(lambda x: x / 256.0, [25, 51, 102])
    colors.SetColor("BkgColor1", *bkg1)
    colors.SetColor("BkgColor2", *bkg2)

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # The cow pipeline.
    cow = vtk.vtkBYUReader()
    cow.SetGeometryFileName(file_name)
    cow.Update()

    cowMapper = vtk.vtkPolyDataMapper()
    cowMapper.SetInputConnection(cow.GetOutputPort())
    cowMapper.ScalarVisibilityOff()

    cowActor = vtk.vtkActor()
    cowActor.SetMapper(cowMapper)
    cowActor.GetProperty().SetColor(colors.GetColor3d("Wheat"))

    ren.AddActor(cowActor)

    # Axes pipeline.
    cowAxesSource = vtk.vtkAxes()
    cowAxesSource.SetScaleFactor(10.0)
    cowAxesSource.SetOrigin(0, 0, 0)

    cowAxesMapper = vtk.vtkPolyDataMapper()
    cowAxesMapper.SetInputConnection(cowAxesSource.GetOutputPort())

    cowAxes = vtk.vtkActor()
    cowAxes.SetMapper(cowAxesMapper)
    cowAxes.VisibilityOff()

    ren.AddActor(cowAxes)

    ren.SetBackground(colors.GetColor3d("BkgColor1"))
    renWin.SetSize(600, 480)

    iren.Initialize()
    cowAxes.VisibilityOn()
    renWin.Render()

    # Activate this if you want to see the Position and Focal point.
    # ren.GetActiveCamera().AddObserver('ModifiedEvent', CameraModifiedCallback)

    # These four walks use the same camera position.
    Rotate_X(cowActor, ren, renWin)
    Rotate_Y(cowActor, ren, renWin)
    Rotate_Z(cowActor, ren, renWin)
    Rotate_XY(cowActor, ren, renWin)

    ren.SetBackground(colors.GetColor3d("BkgColor2"))
    if figure == 1:
        Rotate_V_0(cowActor, ren, renWin)
    elif figure == 2:
        Rotate_V_V(cowActor, ren, renWin)
    else:
        Rotate_V_0(cowActor, ren, renWin)
        Rotate_V_V(cowActor, ren, renWin)
        # Walk() needs to go after Rotate_V_0() or Rotate_V_V().
        Walk(cowActor, ren, renWin)

    # Interact with data.
    renWin.EraseOff()
    iren.Start()
Ejemplo n.º 28
0
def main():
    titles = list()
    textMappers = list()
    textActors = list()

    uGrids = list()
    mappers = list()
    actors = list()
    renderers = list()

    uGrids.append(MakeVertex())
    titles.append('VTK_VERTEX (=1)')
    uGrids.append(MakePolyVertex())
    titles.append('VTK_POLY_VERTEX (=2)')
    uGrids.append(MakeLine())
    titles.append('VTK_LINE (=3)')
    uGrids.append(MakePolyLine())
    titles.append('VTK_POLY_LINE (=4)')
    uGrids.append(MakeTriangle())
    titles.append('VTK_TRIANGLE (=5)')
    uGrids.append(MakeTriangleStrip())
    titles.append('VTK_TRIANGLE_STRIP (=6)')
    uGrids.append(MakePolygon())
    titles.append('VTK_POLYGON (=7)')
    uGrids.append(MakePixel())
    titles.append('VTK_PIXEL (=8)')
    uGrids.append(MakeQuad())
    titles.append('VTK_QUAD (=9)')
    uGrids.append(MakeTetra())
    titles.append('VTK_TETRA (=10)')
    uGrids.append(MakeVoxel())
    titles.append('VTK_VOXEL (=11)')
    uGrids.append(MakeHexahedron())
    titles.append('VTK_HEXAHEDRON (=12)')
    uGrids.append(MakeWedge())
    titles.append('VTK_WEDGE (=13)')
    uGrids.append(MakePyramid())
    titles.append('VTK_PYRAMID (=14)')
    uGrids.append(MakePentagonalPrism())
    titles.append('VTK_PENTAGONAL_PRISM (=15)')
    uGrids.append(MakeHexagonalPrism())
    titles.append('VTK_HEXAGONAL_PRISM (=16)')

    colors = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.SetWindowName('LinearCellDemo')

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

    # Create one sphere for all
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(.08)

    # Create one text property for all
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(10)
    textProperty.SetJustificationToCentered()


    # Create and link the mappers actors and renderers together.
    for i in range(0, len(uGrids)):
        print('Creating:', titles[i])
        textMappers.append(vtk.vtkTextMapper())
        textActors.append(vtk.vtkActor2D())

        mappers.append(vtk.vtkDataSetMapper())
        actors.append(vtk.vtkActor())
        renderers.append(vtk.vtkRenderer())
        mappers[i].SetInputData(uGrids[i])
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d('Tomato'))
        actors[i].GetProperty().EdgeVisibilityOn()
        actors[i].GetProperty().SetLineWidth(3)
        actors[i].GetProperty().SetOpacity(.5)
        renderers[i].AddViewProp(actors[i])

        textMappers[i].SetInput(titles[i])
        textActors[i].SetMapper(textMappers[i])
        textActors[i].SetPosition(50, 10)
        renderers[i].AddViewProp(textActors[i])

        # Label the points
        labelMapper = vtk.vtkLabeledDataMapper()
        labelMapper.SetInputData(uGrids[i])
        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        renderers[i].AddViewProp(labelActor)

        # Glyph the points
        pointMapper = vtk.vtkGlyph3DMapper()
        pointMapper.SetInputData(uGrids[i])
        pointMapper.SetSourceConnection(sphere.GetOutputPort())
        pointMapper.ScalingOff()
        pointMapper.ScalarVisibilityOff()

        pointActor = vtk.vtkActor()
        pointActor.SetMapper(pointMapper)
        pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
        pointActor.GetProperty().SetSpecular(.6)
        pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
        pointActor.GetProperty().SetSpecularPower(100)
        renderers[i].AddViewProp(pointActor)

        renWin.AddRenderer(renderers[i])

    # Setup the viewports
    xGridDimensions = 4
    yGridDimensions = 4
    rendererSize = 240
    renWin.SetSize(rendererSize * xGridDimensions, rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(0, xGridDimensions):
            index = row * xGridDimensions + col

            # (xmin, ymin, xmax, ymax)
            viewport = [float(col) / xGridDimensions,
                        float(yGridDimensions - (row + 1)) / yGridDimensions,
                        float(col + 1) / xGridDimensions,
                        float(yGridDimensions - row) / yGridDimensions]

            if index > (len(actors) - 1):
                # Add a renderer even if there is no actor.
                # This makes the render window background all the same color.
                ren = vtk.vtkRenderer()
                ren.SetBackground(colors.GetColor3d('SlateGray'))
                ren.SetViewport(viewport)
                renWin.AddRenderer(ren)
                continue

            renderers[index].SetViewport(viewport)
            renderers[index].SetBackground(colors.GetColor3d('SlateGray'))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(-30)
            if index == 0:
                renderers[index].GetActiveCamera().Dolly(0.1)
                renderers[index].ResetCameraClippingRange()
            if index == 4:
                renderers[index].GetActiveCamera().Dolly(0.8)
                renderers[index].ResetCameraClippingRange()
            renderers[index].ResetCameraClippingRange()

    renWin.Render()
    iRen.Initialize()
    iRen.Start()
Ejemplo n.º 29
0
def main():
    colors = vtk.vtkNamedColors()

    # The Wavelet Source is nice for generating a test vtkImageData set
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-2, 2, -2, 2, 0, 0)

    # Take the gradient of the only scalar 'RTData' to get a vector attribute
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())

    # Elevation just to generate another scalar attribute that varies nicely over the data range
    elev = vtk.vtkElevationFilter()
    # Elevation values will range from 0 to 1 between the Low and High Points
    elev.SetLowPoint(-2, -2, 0)
    elev.SetHighPoint(2, 2, 0)
    elev.SetInputConnection(grad.GetOutputPort())

    # Create simple PolyData for glyph table
    cs = vtk.vtkCubeSource()
    cs.SetXLength(0.5)
    cs.SetYLength(1)
    cs.SetZLength(2)
    ss = vtk.vtkSphereSource()
    ss.SetRadius(0.25)
    cs2 = vtk.vtkConeSource()
    cs2.SetRadius(0.25)
    cs2.SetHeight(0.5)

    # Set up the glyph filter
    glyph = vtk.vtkGlyph3D()
    glyph.SetInputConnection(elev.GetOutputPort())

    # Here is where we build the glyph table
    # that will be indexed into according to the IndexMode
    glyph.SetSourceConnection(0, cs.GetOutputPort())
    glyph.SetSourceConnection(1, ss.GetOutputPort())
    glyph.SetSourceConnection(2, cs2.GetOutputPort())

    glyph.ScalingOn()
    glyph.SetScaleModeToScaleByScalar()
    glyph.SetVectorModeToUseVector()
    glyph.OrientOn()
    glyph.SetScaleFactor(1)  # Overall scaling factor
    glyph.SetRange(0, 1)  # Default is (0,1)

    # Tell it to index into the glyph table according to scalars
    glyph.SetIndexModeToScalar()

    # Tell glyph which attribute arrays to use for what
    glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation')  # scalars
    glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient')  # vectors

    coloring_by = 'Elevation'
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())
    mapper.SetScalarModeToUsePointFieldData()
    mapper.SetColorModeToMapScalars()
    mapper.ScalarVisibilityOn()

    # GetRange() call doesn't work because attributes weren't copied to glyphs
    # as they should have been...
    # mapper.SetScalarRange(glyph.GetOutputDataObject(0).GetPointData().GetArray(coloring_by).GetRange())

    mapper.SelectColorArray(coloring_by)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()
    iren.Start()
Ejemplo n.º 30
0
def getColor(rgb=None, hsv=None):
    """
    Convert a color or list of colors to (r,g,b) format from many different input formats.

    :param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value).

    Example:
         - RGB    = (255, 255, 255), corresponds to white
         - rgb    = (1,1,1) is white
         - hex    = #FFFF00 is yellow
         - string = 'white'
         - string = 'w' is white nickname
         - string = 'dr' is darkred
         - int    =  7 picks color nr. 7 in a predefined color list
         - int    = -7 picks color nr. 7 in a different predefined list

    |colorcubes| |colorcubes.py|_
    """
    # recursion, return a list if input is list of colors:
    if _isSequence(rgb) and (len(rgb) > 3 or _isSequence(rgb[0])):
        seqcol = []
        for sc in rgb:
            seqcol.append(getColor(sc))
        return seqcol

    if str(rgb).isdigit():
        rgb = int(rgb)

    if hsv:
        c = hsv2rgb(hsv)
    else:
        c = rgb

    if _isSequence(c):
        if c[0] <= 1 and c[1] <= 1 and c[2] <= 1:
            return c  # already rgb
        else:
            if len(c) == 3:
                return list(np.array(c) / 255.0)  # RGB
            else:
                return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3])  # RGBA

    elif isinstance(c, str):  # is string
        c = c.replace("grey", "gray").replace(" ", "")
        if 0 < len(c) < 3:  # single/double letter color
            if c.lower() in color_nicks.keys():
                c = color_nicks[c.lower()]
            else:
                print("Unknown color nickname:", c)
                print("Available abbreviations:", color_nicks)
                return (0.5, 0.5, 0.5)

        if c.lower() in colors.keys():  # matplotlib name color
            c = colors[c.lower()]
        else:  # vtk name color
            namedColors = vtk.vtkNamedColors()
            rgba = [0, 0, 0, 0]
            namedColors.GetColor(c, rgba)
            return list(np.array(rgba[0:3]) / 255.0)

        if "#" in c:  # hex to rgb
            h = c.lstrip("#")
            rgb255 = list(int(h[i:i + 2], 16) for i in (0, 2, 4))
            rgbh = np.array(rgb255) / 255.0
            if np.sum(rgbh) > 3:
                print("Error in getColor(): Wrong hex color", c)
                return (0.5, 0.5, 0.5)
            return tuple(rgbh)

    elif isinstance(c, int):  # color number
        if c >= 0:
            return colors1[c % 10]
        else:
            return colors2[-c % 10]

    elif isinstance(c, float):
        if c >= 0:
            return colors1[int(c) % 10]
        else:
            return colors2[int(-c) % 10]

    # print("Unknown color:", c)
    return (0.5, 0.5, 0.5)
import vtk
# https://pyscience.wordpress.com/2014/11/16/volume-rendering-with-python-and-vtk/
# https://kitware.github.io/vtk-examples/site/Python/Tutorial/Tutorial_Step1/

colors = vtk.vtkNamedColors()

reader = vtk.vtkNrrdReader()
reader.SetFileName(
    r'F:\Xiaotang\uCT\P0_20201003\screen_Man3\12hr_P0_brain_recon.nrrd')

alphaFunc = vtk.vtkPiecewiseFunction()
alphaFunc.AddPoint(0, 0.0)
alphaFunc.AddPoint(50, 0.0)
alphaFunc.AddPoint(128, 0.3)
alphaFunc.AddPoint(191, 0.4)
alphaFunc.AddPoint(255, 0.6)

colorFunc = vtk.vtkColorTransferFunction()
colorFunc.AddRGBPoint(0, 0.75, 0.75, 0.75)
colorFunc.AddRGBPoint(128, 0.75, 0.75, 0.75)
colorFunc.AddRGBPoint(255, 0.5, 0.5, 0.5)

volProp = vtk.vtkVolumeProperty()
volProp.SetColor(colorFunc)
volProp.ShadeOn()
volProp.SetAmbient(0.25)
volProp.SetDiffuse(0.75)
volProp.SetSpecular(0)
volProp.SetScalarOpacity(alphaFunc)
volProp.SetInterpolationTypeToLinear()
Ejemplo n.º 32
0
def main():
    colors = vtk.vtkNamedColors()

    x = [-1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, -0.911458, -0.859375, -0.807292, -0.755208,
         -0.703125, -0.651042, -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, -0.286458, -0.234375,
         -0.182292, -0.130209, -0.078125, -0.026042, 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458,
         0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, 0.651042, 0.703125, 0.755208, 0.807292, 0.859375,
         0.911458, 0.963542, 1.01562, 1.06771, 1.11979, 1.17188]
    y = [-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, -0.78125, -0.703125, -0.625, -0.546875, -0.46875,
         -0.390625, -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, 0.15625, 0.234375, 0.3125, 0.390625, 0.46875,
         0.546875, 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, 1.09375, 1.17188, 1.25]
    z = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.75, 1.8, 1.9, 2,
         2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9]
    print(len(x), len(y), len(z))

    # Create a rectilinear grid by defining three arrays specifying the
    # coordinates in the x-y-z directions.
    xCoords = vtk.vtkDoubleArray()
    for i in range(0, len(x)):
        xCoords.InsertNextValue(x[i])
    yCoords = vtk.vtkDoubleArray()
    for i in range(0, len(y)):
        yCoords.InsertNextValue(y[i])
    zCoords = vtk.vtkDoubleArray()
    for i in range(0, len(z)):
        zCoords.InsertNextValue(z[i])

    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    #
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(len(x), len(y), len(z))
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(zCoords)

    # Extract a plane from the grid to see what we've got.
    plane = vtk.vtkRectilinearGridGeometryFilter()
    plane.SetInputData(rgrid)
    plane.SetExtent(0, len(x) - 1, 16, 16, 0, len(z) - 1)

    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(plane.GetOutputPort())

    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    wireActor.GetProperty().EdgeVisibilityOn()

    # Create the usual rendering stuff.
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderer.AddActor(wireActor)
    renderer.SetBackground(colors.GetColor3d("Beige"))
    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(60.0)
    renderer.GetActiveCamera().Azimuth(30.0)
    renderer.GetActiveCamera().Zoom(1.0)

    renWin.SetSize(640, 480)

    # Interact with the data.
    renWin.Render()
    iren.Start()
Ejemplo n.º 33
0
def main():
    colors = vtk.vtkNamedColors()

    fileName = get_program_parameters()

    polyData = ReadPolyData(fileName)

    # A renderer.
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d("White"))

    # Create background colors for each viewport.
    backgroundColors = list()
    backgroundColors.append(colors.GetColor3d("Cornsilk"))
    backgroundColors.append(colors.GetColor3d("NavajoWhite"))
    backgroundColors.append(colors.GetColor3d("Tan"))

    # Create a renderer for each view port.
    ren = list()
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren.append(vtk.vtkRenderer())
    ren[0].SetViewport(0, 0, 1.0 / 3.0, 1)  # Input
    ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1)  # Normals (no split)
    ren[2].SetViewport(2.0 / 3.0, 0, 1, 1)  # Normals (split)

    # Shared camera.
    camera = vtk.vtkCamera()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputData(polyData)
    normals.SetFeatureAngle(30.0)
    for i in range(0, 3):
        if i == 0:
            normals.ComputePointNormalsOff()
        elif i == 1:
            normals.ComputePointNormalsOn()
            normals.SplittingOff()
        else:
            normals.ComputePointNormalsOn()
            normals.SplittingOn()

        normals.Update()

        normalsPolyData = vtk.vtkPolyData()
        normalsPolyData.DeepCopy(normals.GetOutput())

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(normalsPolyData)
        mapper.ScalarVisibilityOff()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Peacock"))
        actor.GetProperty().SetDiffuse(.7)
        actor.GetProperty().SetSpecularPower(20)
        actor.GetProperty().SetSpecular(.5)

        # add the actor
        ren[i].SetBackground(backgroundColors[i])
        ren[i].SetActiveCamera(camera)
        ren[i].AddActor(actor)

    # Render window.
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(ren[0])
    renwin.AddRenderer(ren[1])
    renwin.AddRenderer(ren[2])

    # An interactor.
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    renwin.SetSize(900, 300)
    ren[0].GetActiveCamera().SetFocalPoint(0, 0, 0)
    ren[0].GetActiveCamera().SetPosition(1, 0, 0)
    ren[0].GetActiveCamera().SetViewUp(0, 0, -1)
    ren[0].ResetCamera()

    ren[0].GetActiveCamera().Azimuth(120)
    ren[0].GetActiveCamera().Elevation(30)
    ren[0].GetActiveCamera().Dolly(1.1)
    ren[0].ResetCameraClippingRange()

    renwin.Render()
    ren[0].ResetCamera()
    renwin.Render()

    # Start.
    interactor.Initialize()
    interactor.Start()
Ejemplo n.º 34
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor("BkgColor", [51, 77, 102, 255])

    # Create container to hold the 3D object generators (sources)
    geometricObjectSources = list()

    # Populate the container with the various object sources to be demonstrated
    geometricObjectSources.append(vtk.vtkArrowSource())
    geometricObjectSources.append(vtk.vtkConeSource())
    geometricObjectSources.append(vtk.vtkCubeSource())
    geometricObjectSources.append(vtk.vtkCylinderSource())
    geometricObjectSources.append(vtk.vtkDiskSource())
    geometricObjectSources.append(vtk.vtkLineSource())
    geometricObjectSources.append(vtk.vtkRegularPolygonSource())
    geometricObjectSources.append(vtk.vtkSphereSource())

    # Create containers for the remaining nodes of each pipeline
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

    # Create a common text property.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()

    # Create a mapper and actor for each object and the corresponding text label
    for i in range(0, len(geometricObjectSources)):
        geometricObjectSources[i].Update()

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(geometricObjectSources[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(
            colors.GetColor3d("Seashell"))

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(
            geometricObjectSources[i].GetClassName())  # set text label to the name of the object source
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)  # Note: the position of an Actor2D is specified in display coordinates

    # Define size of the grid that will hold the objects
    gridCols = 3
    gridRows = 3
    # Define side length (in pixels) of each renderer square
    rendererSize = 300

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Geometric Objects Demo")
    renderWindow.SetSize(rendererSize * gridCols, rendererSize * gridRows)

    # Set up a grid of viewports for each renderer
    for row in range(0, gridRows):
        for col in range(0, gridCols):
            index = row * gridCols + col

            # Create a renderer for this grid cell
            renderer = vtk.vtkRenderer()
            renderer.SetBackground(colors.GetColor3d("BkgColor"))

            # Set the renderer's viewport dimensions (xmin, ymin, xmax, ymax) within the render window.
            # Note that for the Y values, we need to subtract the row index from gridRows
            # because the viewport Y axis points upwards, but we want to draw the grid from top to down
            viewport = [
                float(col) / gridCols,
                float(gridRows - row - 1) / gridRows,
                float(col + 1) / gridCols,
                float(gridRows - row) / gridRows
            ]
            renderer.SetViewport(viewport)

            # Add the corresponding actor and label for this grid cell, if they exist
            if index < len(geometricObjectSources):
                renderer.AddActor(actors[index])
                renderer.AddActor(textactors[index])
                renderer.ResetCameraClippingRange()

            renderWindow.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    interactor.Start()
Ejemplo n.º 35
0
def main():
    filePath = get_program_parameters()

    # Define colors
    colors = vtk.vtkNamedColors()
    backgroundColor = colors.GetColor3d("steel_blue")
    boundaryColor = colors.GetColor3d("Banana")
    clipColor = colors.GetColor3d("Tomato")

    if filePath and os.path.isfile(filePath):
        polyData = ReadPolyData(filePath)
        if not polyData:
            polyData = GetSpherePD()
    else:
        polyData = GetSpherePD()

    plane = vtk.vtkPlane()
    plane.SetOrigin(polyData.GetCenter())
    plane.SetNormal(1.0, -1.0, -1.0)

    clipper = vtk.vtkClipPolyData()
    clipper.SetInputData(polyData)
    clipper.SetClipFunction(plane)
    clipper.SetValue(0)
    clipper.Update()

    polyData = clipper.GetOutput()

    clipMapper = vtk.vtkDataSetMapper()
    clipMapper.SetInputData(polyData)

    clipActor = vtk.vtkActor()
    clipActor.SetMapper(clipMapper)
    clipActor.GetProperty().SetDiffuseColor(clipColor)
    clipActor.GetProperty().SetInterpolationToFlat()
    clipActor.GetProperty().EdgeVisibilityOn()

    # Now extract feature edges
    boundaryEdges = vtk.vtkFeatureEdges()
    boundaryEdges.SetInputData(polyData)
    boundaryEdges.BoundaryEdgesOn()
    boundaryEdges.FeatureEdgesOff()
    boundaryEdges.NonManifoldEdgesOff()
    boundaryEdges.ManifoldEdgesOff()

    boundaryStrips = vtk.vtkStripper()
    boundaryStrips.SetInputConnection(boundaryEdges.GetOutputPort())
    boundaryStrips.Update()

    # Change the polylines into polygons
    boundaryPoly = vtk.vtkPolyData()
    boundaryPoly.SetPoints(boundaryStrips.GetOutput().GetPoints())
    boundaryPoly.SetPolys(boundaryStrips.GetOutput().GetLines())

    boundaryMapper = vtk.vtkPolyDataMapper()
    boundaryMapper.SetInputData(boundaryPoly)

    boundaryActor = vtk.vtkActor()
    boundaryActor.SetMapper(boundaryMapper)
    boundaryActor.GetProperty().SetDiffuseColor(boundaryColor)

    # create renderer render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # set background color and size
    renderer.SetBackground(backgroundColor)
    renderWindow.SetSize(640, 480)

    # add our actor to the renderer
    renderer.AddActor(clipActor)
    renderer.AddActor(boundaryActor)

    # Generate an interesting view
    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.GetActiveCamera().Dolly(1.2)
    renderer.ResetCameraClippingRange()

    renderWindow.Render()
    renderWindow.SetWindowName('CapClip')
    renderWindow.Render()

    interactor.Start()
Ejemplo n.º 36
0
def main(data_folder, slice_number):
    colors = vtk.vtkNamedColors()

    path = Path(data_folder)
    if path.is_dir():
        s = ''
        fn_1 = path.joinpath('frog').with_suffix('.mhd')
        if not fn_1.is_file():
            s += 'The file: {:s} does not exist.\n'.format(str(fn_1))
            print(s)
        fn_2 = path.joinpath('frogtissue').with_suffix('.mhd')
        if not fn_2.is_file():
            s += 'The file: {:s} does not exist.'.format(str(fn_2))
        if s:
            print(s)
            return
    else:
        print('Expected a path to frog.mhs and frogtissue.mhd')
        return

    so = SliceOrder()

    # Now create the RenderWindow, Renderer and Interactor
    #
    ren1 = vtk.vtkRenderer()
    ren2 = vtk.vtkRenderer()
    ren3 = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren1)
    ren_win.AddRenderer(ren2)
    ren_win.AddRenderer(ren3)
    ren_win.SetWindowName('FrogSlice')

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    grey_reader = vtk.vtkMetaImageReader()
    grey_reader.SetFileName(str(fn_1))
    grey_reader.Update()

    grey_padder = vtk.vtkImageConstantPad()
    grey_padder.SetInputConnection(grey_reader.GetOutputPort())
    grey_padder.SetOutputWholeExtent(0, 511, 0, 511, slice_number,
                                     slice_number)
    grey_padder.SetConstant(0)

    grey_plane = vtk.vtkPlaneSource()

    grey_transform = vtk.vtkTransformPolyDataFilter()
    grey_transform.SetTransform(so.get('hfsi'))
    grey_transform.SetInputConnection(grey_plane.GetOutputPort())

    grey_normals = vtk.vtkPolyDataNormals()
    grey_normals.SetInputConnection(grey_transform.GetOutputPort())
    grey_normals.FlipNormalsOff()

    wllut = vtk.vtkWindowLevelLookupTable()
    wllut.SetWindow(255)
    wllut.SetLevel(128)
    wllut.SetTableRange(0, 255)
    wllut.Build()

    grey_mapper = vtk.vtkPolyDataMapper()
    grey_mapper.SetInputConnection(grey_plane.GetOutputPort())

    grey_texture = vtk.vtkTexture()
    grey_texture.SetInputConnection(grey_padder.GetOutputPort())
    grey_texture.SetLookupTable(wllut)
    grey_texture.SetColorModeToMapScalars()
    grey_texture.InterpolateOn()

    grey_actor = vtk.vtkActor()
    grey_actor.SetMapper(grey_mapper)
    grey_actor.SetTexture(grey_texture)

    segment_reader = vtk.vtkMetaImageReader()
    segment_reader.SetFileName(str(fn_2))
    segment_reader.Update()

    segment_padder = vtk.vtkImageConstantPad()
    segment_padder.SetInputConnection(segment_reader.GetOutputPort())
    segment_padder.SetOutputWholeExtent(0, 511, 0, 511, slice_number,
                                        slice_number)
    segment_padder.SetConstant(0)

    segment_plane = vtk.vtkPlaneSource()

    segment_transform = vtk.vtkTransformPolyDataFilter()
    segment_transform.SetTransform(so.get('hfsi'))
    segment_transform.SetInputConnection(segment_plane.GetOutputPort())

    segment_normals = vtk.vtkPolyDataNormals()
    segment_normals.SetInputConnection(segment_transform.GetOutputPort())
    segment_normals.FlipNormalsOn()

    lut = create_frog_lut(colors)

    segment_mapper = vtk.vtkPolyDataMapper()
    segment_mapper.SetInputConnection(segment_plane.GetOutputPort())

    segment_texture = vtk.vtkTexture()
    segment_texture.SetInputConnection(segment_padder.GetOutputPort())
    segment_texture.SetLookupTable(lut)
    segment_texture.SetColorModeToMapScalars()
    segment_texture.InterpolateOff()

    segment_actor = vtk.vtkActor()
    segment_actor.SetMapper(segment_mapper)
    segment_actor.SetTexture(segment_texture)

    segment_overlay_actor = vtk.vtkActor()
    segment_overlay_actor.SetMapper(segment_mapper)
    segment_overlay_actor.SetTexture(segment_texture)

    segment_overlay_actor.GetProperty().SetOpacity(.5)
    ren1.SetBackground(0, 0, 0)
    ren1.SetViewport(0, 0.5, 0.5, 1)
    ren_win.SetSize(640, 480)
    ren1.AddActor(grey_actor)

    ren2.SetBackground(0, 0, 0)
    ren2.SetViewport(0.5, 0.5, 1, 1)
    ren2.AddActor(segment_actor)

    cam1 = vtk.vtkCamera()
    cam1.SetViewUp(0, -1, 0)
    cam1.SetPosition(0, 0, -1)
    ren1.SetActiveCamera(cam1)
    ren1.ResetCamera()
    cam1.SetViewUp(0, -1, 0)
    cam1.SetPosition(0.0554068, -0.0596001, -0.491383)
    cam1.SetFocalPoint(0.0554068, -0.0596001, 0)
    ren1.ResetCameraClippingRange()

    ren3.AddActor(grey_actor)
    ren3.AddActor(segment_overlay_actor)
    segment_overlay_actor.SetPosition(0, 0, -0.01)

    ren1.SetBackground(colors.GetColor3d('SlateGray'))
    ren2.SetBackground(colors.GetColor3d('SlateGray'))
    ren3.SetBackground(colors.GetColor3d('SlateGray'))

    ren3.SetViewport(0, 0, 1, 0.5)

    ren2.SetActiveCamera(ren1.GetActiveCamera())
    ren3.SetActiveCamera(ren1.GetActiveCamera())

    ren_win.Render()
    iren.Start()
Ejemplo n.º 37
0
 def __init__(self):
     '''
         Define a single instance of the NamedColors class here.
     '''
     self.namedColors = vtk.vtkNamedColors()
Ejemplo n.º 38
0
def main():
    # vtkFlyingEdges3D was introduced in VTK >= 8.2
    use_flying_edges = vtk_version_ok(8, 2, 0)

    colors = vtk.vtkNamedColors()

    file_name = get_program_parameters()

    colors.SetColor('SkinColor', [240, 184, 160, 255])
    colors.SetColor('BackfaceColor', [255, 229, 200, 255])
    colors.SetColor('BkgColor', [51, 77, 102, 255])

    # Create the renderer, the render window, and the interactor. The renderer
    # draws into the render window, the interactor enables mouse- and
    # keyboard-based interaction with the data within the render window.
    #
    a_renderer = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(a_renderer)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(file_name)

    # An isosurface, or contour value of 500 is known to correspond to the
    # skin of the patient.
    if use_flying_edges:
        try:
            skin_extractor = vtk.vtkFlyingEdges3D()
        except AttributeError:
            skin_extractor = vtk.vtkMarchingCubes()
    else:
        skin_extractor = vtk.vtkMarchingCubes()
    skin_extractor.SetInputConnection(reader.GetOutputPort())
    skin_extractor.SetValue(0, 500)

    skin_mapper = vtk.vtkPolyDataMapper()
    skin_mapper.SetInputConnection(skin_extractor.GetOutputPort())
    skin_mapper.ScalarVisibilityOff()

    skin = vtk.vtkActor()
    skin.SetMapper(skin_mapper)
    skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor'))

    back_prop = vtk.vtkProperty()
    back_prop.SetDiffuseColor(colors.GetColor3d('BackfaceColor'))
    skin.SetBackfaceProperty(back_prop)

    # An outline provides context around the data.
    #
    outline_data = vtk.vtkOutlineFilter()
    outline_data.SetInputConnection(reader.GetOutputPort())

    map_outline = vtk.vtkPolyDataMapper()
    map_outline.SetInputConnection(outline_data.GetOutputPort())

    outline = vtk.vtkActor()
    outline.SetMapper(map_outline)
    outline.GetProperty().SetColor(colors.GetColor3d('Black'))

    # It is convenient to create an initial view of the data. The FocalPoint
    # and Position form a vector direction. Later on (ResetCamera() method)
    # this vector is used to position the camera to look at the data in
    # this direction.
    a_camera = vtk.vtkCamera()
    a_camera.SetViewUp(0, 0, -1)
    a_camera.SetPosition(0, -1, 0)
    a_camera.SetFocalPoint(0, 0, 0)
    a_camera.ComputeViewPlaneNormal()
    a_camera.Azimuth(30.0)
    a_camera.Elevation(30.0)

    # Actors are added to the renderer. An initial camera view is created.
    # The Dolly() method moves the camera towards the FocalPoint,
    # thereby enlarging the image.
    a_renderer.AddActor(outline)
    a_renderer.AddActor(skin)
    a_renderer.SetActiveCamera(a_camera)
    a_renderer.ResetCamera()
    a_camera.Dolly(1.5)

    # Set a background color for the renderer and set the size of the
    # render window (expressed in pixels).
    a_renderer.SetBackground(colors.GetColor3d('BkgColor'))
    ren_win.SetSize(640, 480)
    ren_win.SetWindowName('MedicalDemo1')

    # Note that when camera movement occurs (as it does in the Dolly()
    # method), the clipping planes often need adjusting. Clipping planes
    # consist of two planes: near and far along the view direction. The
    # near plane clips out objects in front of the plane the far plane
    # clips out objects behind the plane. This way only what is drawn
    # between the planes is actually rendered.
    a_renderer.ResetCameraClippingRange()

    # Initialize the event loop and then start it.
    iren.Initialize()
    iren.Start()