Difference between revisions of "VTK/Examples/Python/Visualization/NamedColors"

From KitwarePublic
< VTK‎ | Examples‎ | Python
Jump to navigationJump to search
(Created page with "This example demonstrates the usage of the vtkNamedColors class. Some helper functions are also implemented. A cone is created and contoured using the BandedPolyDataContourFilter...")
 
Line 1: Line 1:
 +
==Description==
 
This example demonstrates the usage of the vtkNamedColors class. Some helper functions are also implemented.
 
This example demonstrates the usage of the vtkNamedColors class. Some helper functions are also implemented.
A cone is created and contoured using the BandedPolyDataContourFilter, it is then colored using a LookupTable where the colors have been assigned using color names.
+
A cone is created and contoured using the BandedPolyDataContourFilter, it is then colored using a lookuplable where the colors have been assigned using color names.
 +
 
 
A list of available color names and any synonyms are also output.
 
A list of available color names and any synonyms are also output.
  
Line 14: Line 16:
 
import string
 
import string
  
def CheckVTKVersion(requiredMajorVersion):
+
def FindSynonyms(nc, colorName):
 +
    '''
 +
    Find any synonyms for a specified color.
 +
    :param: nc: The vtkNamedColor class
 +
    :param: colorName: the name of the color to find the synonyms for.
 +
    :return: The synonyms for colorName.
 +
    '''
 +
    availableColors = nc.GetColorNames()
 +
    # Make a list
 +
    availableColors = availableColors.split('\n')
 +
    synonyms = []
 +
    # We use lower case for comparison and
 +
    # just the red, green, and blue components
 +
    # of the color.
 +
    lcolorName = colorName.lower()
 +
    myColor = nc.GetColor3ub(colorName)
 +
    for color in availableColors:
 +
        rgb = nc.GetColor3ub(color)
 +
        if list(myColor) == list(rgb):
 +
            synonyms.append(color)
 +
    return synonyms
 +
 
 +
 
 +
def DisplayCone(nc):
 
     '''
 
     '''
         Check the VTK version.
+
    Create a cone, contour it using the banded contour filter and
 +
         color it with the primary additive and subtractive colors.
 +
    :param: nc: The vtkNamedColor class
 +
    :return: The render window interactor.
 
     '''
 
     '''
     version = vtk.vtkVersion()
+
     # Create a cone
     if version.GetVTKMajorVersion() > requiredMajorVersion:
+
     coneSource = vtk.vtkConeSource()
        raise
+
     coneSource.SetCenter(0.0, 0.0, 0.0)
    else:
+
    coneSource.SetRadius(5.0)
        return
+
     coneSource.SetHeight(10)
   
+
    coneSource.SetDirection(0,1,0)
class NamedColors(object):
+
    coneSource.Update()
   
+
 
    def __init__(self):
+
     bounds = [1.0,-1.0,1.0,-1.0,1.0,-1.0]
        '''
+
    coneSource.GetOutput().GetBounds(bounds)
            Define a single instance of the NamedColors class here.
+
 
        '''
+
     elevation = vtk.vtkElevationFilter()
        self.namedColors = vtk.vtkNamedColors()
+
     elevation.SetInputConnection(coneSource.GetOutputPort())
       
+
    elevation.SetLowPoint(0,bounds[2],0)
     def GetRGBColor(self,colorName):
+
    elevation.SetHighPoint(0,bounds[3],0)
        '''
+
 
            Return the red, green and blue components for a
+
    bcf = vtk.vtkBandedPolyDataContourFilter()
            color as doubles.
+
    bcf.SetInputConnection(elevation.GetOutputPort())
        '''
+
    bcf.SetScalarModeToValue()
        rgb = [0.0,0.0,0.0] # black
+
     bcf.GenerateContourEdgesOn()
        self.namedColors.GetColorRGB(colorName,rgb)
+
     bcf.GenerateValues(7,elevation.GetScalarRange())
        return rgb
+
 
       
+
    # Build a simple lookup table of
     def GetRGBColorInt(self,colorName):
+
    # primary additive and subtractive colors.
        '''
+
    lut = vtk.vtkLookupTable()
            Return the red, green and blue components for a
+
    lut.SetNumberOfTableValues(7)
            color as integer.
+
    # Test setting and getting a color here.
        '''
+
     # We are also modifying alpha.
        rgb = [0,0,0] # black
+
 
        self.namedColors.GetColorRGB(colorName,rgb)
+
    # Convert to a list so that
        return rgb
+
    # SetColor(name,rgba) works.
       
+
    rgba = list(nc.GetColor4d("Red"))
     def GetRGBAColor(self,colorName):
+
    rgba[3] = 0.5
        '''
+
    nc.SetColor("My Red",rgba)
            Return the red, green, blue and alpha
+
    rgba = nc.GetColor4d("My Red")
            components for a color as doubles.
+
    lut.SetTableValue(0,rgba)
        '''
+
     # Does "My Red" match anything?
        rgba = [0.0,0.0,0.0,1.0] # black
+
     match = FindSynonyms(nc,"My Red")
        self.namedColors.GetColor(colorName,rgba)
+
    print "Matching colors to My Red:", match
        return rgba
+
 
      
+
    rgba = nc.GetColor4d("DarkGreen")
     def GetRGBAColorInt(self,colorName):
+
    rgba[3] = 0.3
        '''
+
    lut.SetTableValue(1,rgba)
            Return the red, green, blue and alpha
+
    # Alternatively we can use our wrapper functions:
            components for a color as integer.
+
    lut.SetTableValue(2,nc.GetColor4d("Blue"))
        '''
+
    lut.SetTableValue(3,nc.GetColor4d("Cyan"))
        rgba = [0,0,0,1] # black
+
    lut.SetTableValue(4,nc.GetColor4d("Magenta"))
        self.namedColors.GetColor(colorName,rgba)
+
    lut.SetTableValue(5,nc.GetColor4d("Yellow"))
        return rgba
+
    lut.SetTableValue(6,nc.GetColor4d("White"))
      
+
     lut.SetTableRange(elevation.GetScalarRange())
     def GetColorNames(self):
+
    lut.Build()
        '''
+
 
            Return a list of color names.
+
    mapper = vtk.vtkPolyDataMapper()
        '''
+
    mapper.SetInputConnection(bcf.GetOutputPort())
        colorsNames = self.namedColors.GetColorNames()
+
    mapper.SetLookupTable(lut)
        colorsNames = colorsNames.split('\n')
+
    mapper.SetScalarModeToUseCellData()
        return colorsNames
 
       
 
     def GetSynonyms(self):
 
        '''
 
            Return a list of synonyms.
 
        '''
 
        syn = self.namedColors.GetSynonyms()
 
        syn = syn.split('\n\n')
 
        synonyms = []
 
        for ele in syn:
 
            synonyms.append(ele.split('\n'))
 
        return synonyms
 
      
 
     def FindSynonyms(self,colorName):
 
        '''
 
            Find any synonyms for a specified color.
 
        '''
 
        availableColors = self.GetColorNames()
 
        synonyms = []
 
        # We use lower case for comparison and
 
        # just the red, green, and blue components
 
        # of the color.
 
        lcolorName = colorName.lower()
 
        myColor = self.GetRGBColorInt(colorName)
 
        for color in availableColors:
 
            rgb = self.GetRGBColorInt(color)
 
            if myColor == rgb:
 
                synonyms.append(color)
 
        return synonyms
 
       
 
       
 
     def DisplayCone(self):
 
        '''
 
            Create a cone, contour it using the banded contour filter and
 
                color it with the primary additive and subtractive colors.
 
        '''
 
        #print namedColors
 
       
 
        # 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]
+
    contourLineMapper = vtk.vtkPolyDataMapper()
        coneSource.GetOutput().GetBounds(bounds)
+
    contourLineMapper.SetInputData(bcf.GetContourEdgesOutput())
       
+
    contourLineMapper.SetScalarRange(elevation.GetScalarRange())
        elevation = vtk.vtkElevationFilter()
+
    contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset()
        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
+
    actor = vtk.vtkActor()
        # primary additive and subtractive colors.
+
    actor.SetMapper(mapper)
        lut = vtk.vtkLookupTable()
 
        lut.SetNumberOfTableValues(7)
 
        # Test setting and getting a color here.
 
        # We are also modifying alpha.
 
        rgba = self.GetRGBAColor("Red")
 
        rgba[3] = 0.5
 
        self.namedColors.SetColor("My Red",rgba)
 
        rgba = self.GetRGBAColor("My Red")
 
        lut.SetTableValue(0,rgba)
 
        # Does "My Red" match anything?
 
        match = self.FindSynonyms("My Red")
 
        print "Matching colors to My Red:", match
 
       
 
        rgba = self.GetRGBAColor("DarkGreen")
 
        rgba[3] = 0.3
 
        lut.SetTableValue(1,rgba)
 
        #  Alternatively we can use our wrapper functions:
 
        lut.SetTableValue(2,self.GetRGBAColor("Blue"))
 
        lut.SetTableValue(3,self.GetRGBAColor("Cyan"))
 
        lut.SetTableValue(4,self.GetRGBAColor("Magenta"))
 
        lut.SetTableValue(5,self.GetRGBAColor("Yellow"))
 
        lut.SetTableValue(6,self.GetRGBAColor("White"))
 
        lut.SetTableRange(elevation.GetScalarRange())
 
        lut.Build()
 
  
        mapper = vtk.vtkPolyDataMapper()
+
    contourLineActor = vtk.vtkActor()
        mapper.SetInputConnection(bcf.GetOutputPort())
+
    actor.SetMapper(mapper)
        mapper.SetLookupTable(lut)
+
    contourLineActor.SetMapper(contourLineMapper)
         mapper.SetScalarModeToUseCellData()
+
    contourLineActor.GetProperty().SetColor(
 +
         nc.GetColor3d("black"))
  
        contourLineMapper = vtk.vtkPolyDataMapper()
+
    renderer = vtk.vtkRenderer()
        contourLineMapper.SetInputData(bcf.GetContourEdgesOutput())
+
    renderWindow = vtk.vtkRenderWindow()
        contourLineMapper.SetScalarRange(elevation.GetScalarRange())
+
    renderWindow.AddRenderer(renderer)
        contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset()
+
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
       
+
    renderWindowInteractor.SetRenderWindow(renderWindow)
        actor = vtk.vtkActor()
 
        actor.SetMapper(mapper)
 
  
        contourLineActor = vtk.vtkActor()
+
    renderer.AddActor(actor)
        actor.SetMapper(mapper)
+
    renderer.AddActor(contourLineActor)
        contourLineActor.SetMapper(contourLineMapper)
+
    renderer.SetBackground(
         contourLineActor.GetProperty().SetColor(
+
         nc.GetColor3d("SteelBlue"))
            self.GetRGBColor("black"))
 
  
        renderer = vtk.vtkRenderer()
+
    renderWindow.Render()
        renderWindow = vtk.vtkRenderWindow()
 
        renderWindow.AddRenderer(renderer)
 
        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
 
        renderWindowInteractor.SetRenderWindow(renderWindow)
 
  
        renderer.AddActor(actor)
+
    fnsave = "TestNamedColorsIntegration.png"
        renderer.AddActor(contourLineActor)
+
    renLgeIm = vtk.vtkRenderLargeImage()
        renderer.SetBackground(
+
    imgWriter = vtk.vtkPNGWriter()
            self.GetRGBColor("SteelBlue"))
+
    renLgeIm.SetInput(renderer)
 +
    renLgeIm.SetMagnification(1)
 +
    imgWriter.SetInputConnection(renLgeIm.GetOutputPort())
 +
    imgWriter.SetFileName(fnsave)
 +
    imgWriter.Write()
  
        renderWindow.Render()
+
    return renderWindowInteractor
  
        fnsave = "TestNamedColorsIntegration.png"
+
def CheckVTKVersion(requiredMajorVersion):
        renLgeIm = vtk.vtkRenderLargeImage()
+
    '''
        imgWriter = vtk.vtkPNGWriter()
+
    Check the VTK version.
        renLgeIm.SetInput(renderer)
+
    :param: requiredMajorVersion e.g. 6
         renLgeIm.SetMagnification(1)
+
    '''
        imgWriter.SetInputConnection(renLgeIm.GetOutputPort())
+
    version = vtk.vtkVersion()
        imgWriter.SetFileName(fnsave)
+
    if version.GetVTKMajorVersion() > requiredMajorVersion:
         imgWriter.Write()
+
         raise
 +
    else:
 +
         return
  
         renderWindowInteractor.Start()
+
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()
  
 
if __name__ == "__main__":
 
if __name__ == "__main__":
Line 212: Line 173:
 
         print "The class vtkNamedColors is in VTK version 6 or greater."
 
         print "The class vtkNamedColors is in VTK version 6 or greater."
 
         exit(0)
 
         exit(0)
     nc = NamedColors()
+
     main()
    colorNames = nc.GetColorNames()
 
    print "There are", len(colorNames), "colors:"
 
    print colorNames
 
    synonyms = nc.GetSynonyms()
 
    print "There are", len(synonyms), "synonyms:"
 
    print synonyms
 
    nc.DisplayCone()
 
 
</source>
 
</source>

Revision as of 22:40, 27 June 2014

Description

This example demonstrates the usage of the vtkNamedColors class. Some helper functions are also implemented. A cone is created and contoured using the BandedPolyDataContourFilter, it is then colored using a lookuplable where the colors have been assigned using color names.

A list of available color names and any synonyms are also output.

NamedColors.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
    This example demonstrates the usage of the vtNamedColor class.
'''
import vtk
import string

def FindSynonyms(nc, colorName):
    '''
    Find any synonyms for a specified color.
    :param: nc: The vtkNamedColor class
    :param: colorName: the name of the color to find the synonyms for.
    :return: The synonyms for colorName.
    '''
    availableColors = nc.GetColorNames()
    # Make a list
    availableColors = availableColors.split('\n')
    synonyms = []
    # We use lower case for comparison and
    # just the red, green, and blue components
    # of the color.
    lcolorName = colorName.lower()
    myColor = nc.GetColor3ub(colorName)
    for color in availableColors:
        rgb = nc.GetColor3ub(color)
        if list(myColor) == list(rgb):
            synonyms.append(color)
    return synonyms


def DisplayCone(nc):
    '''
    Create a cone, contour it using the banded contour filter and
        color it with the primary additive and subtractive colors.
    :param: nc: The vtkNamedColor class
    :return: The render window interactor.
    '''
    # 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)
    # Test setting and getting a color here.
    # We are also modifying alpha.

    # Convert to a list so that
    # SetColor(name,rgba) works.
    rgba = list(nc.GetColor4d("Red"))
    rgba[3] = 0.5
    nc.SetColor("My Red",rgba)
    rgba = nc.GetColor4d("My Red")
    lut.SetTableValue(0,rgba)
    # Does "My Red" match anything?
    match = FindSynonyms(nc,"My Red")
    print "Matching colors to My Red:", match

    rgba = nc.GetColor4d("DarkGreen")
    rgba[3] = 0.3
    lut.SetTableValue(1,rgba)
    #  Alternatively we can use our wrapper functions:
    lut.SetTableValue(2,nc.GetColor4d("Blue"))
    lut.SetTableValue(3,nc.GetColor4d("Cyan"))
    lut.SetTableValue(4,nc.GetColor4d("Magenta"))
    lut.SetTableValue(5,nc.GetColor4d("Yellow"))
    lut.SetTableValue(6,nc.GetColor4d("White"))
    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()
    actor.SetMapper(mapper)
    contourLineActor.SetMapper(contourLineMapper)
    contourLineActor.GetProperty().SetColor(
        nc.GetColor3d("black"))

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

    renderer.AddActor(actor)
    renderer.AddActor(contourLineActor)
    renderer.SetBackground(
        nc.GetColor3d("SteelBlue"))

    renderWindow.Render()

    fnsave = "TestNamedColorsIntegration.png"
    renLgeIm = vtk.vtkRenderLargeImage()
    imgWriter = vtk.vtkPNGWriter()
    renLgeIm.SetInput(renderer)
    renLgeIm.SetMagnification(1)
    imgWriter.SetInputConnection(renLgeIm.GetOutputPort())
    imgWriter.SetFileName(fnsave)
    imgWriter.Write()

    return renderWindowInteractor

def CheckVTKVersion(requiredMajorVersion):
    '''
    Check the VTK version.
    :param: requiredMajorVersion e.g. 6
    '''
    version = vtk.vtkVersion()
    if version.GetVTKMajorVersion() > requiredMajorVersion:
        raise
    else:
        return

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()

if __name__ == "__main__":
    try:
        CheckVTKVersion(6)
    except:
        print "You need VTK Version 6 or greater."
        print "The class vtkNamedColors is in VTK version 6 or greater."
        exit(0)
    main()