CameraOrientationWidget1
Repository source: CameraOrientationWidget1
Description¶
This example demonstrates the usage and versatility of the vtkCameraOrientationWidget, also, for comparison, a vtkOrientationMarkerWidget is provided. The ability to automatically change axes labels and colors depending upon the object being viewed is demonstrated. To do this, just load any one of the following files from the vtk-examples testing data.
"Human.vtp", "Torso.vtp", "cow.vtp", "cowHead.vtp", "horse.vtp", "Bunny.vtp"
These files are found in vtk-examples/src/Testing/Data
.
The vtkCameraOrientationWidget has shafts and little spheres with text on them. The spheres alway follow the camera.
The widget representation's orientation is synchronized with the camera of the parent renderer.
To look down on any particular axis, simply click on a handle.
To rotate the camera and get a feel of the camera orientation, either move the mouse in the render window or click on a handle and move it around.
If no file name is entered, a cone is rendered.
Some history: - The vtkCameraOrientationWidget was introduced in the MR: !8156, 18 July, 2021. - Labelling of the vertices was introduced in the MR: !11665, 16 November, 2024. - Coloring of the vertices was introduced in the MR: !12489, 01 October, 2025
Other languages
See (Cxx)
Question
If you have a question about this example, please use the VTK Discourse Forum
Code¶
CameraOrientationWidget1.py
#!/usr/bin/env python3
# This example demonstrates how to use the vtkCameraOrientationWidget to control
# a renderer's camera orientation.
import math
from pathlib import Path
from sys import argv
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersSources import vtkConeSource
from vtkmodules.vtkIOGeometry import (
vtkBYUReader,
vtkOBJReader,
vtkSTLReader
)
from vtkmodules.vtkIOLegacy import vtkPolyDataReader
from vtkmodules.vtkIOPLY import vtkPLYReader
from vtkmodules.vtkIOXML import vtkXMLPolyDataReader
from vtkmodules.vtkInteractionWidgets import (
vtkCameraOrientationWidget,
vtkOrientationMarkerWidget
)
from vtkmodules.vtkRenderingAnnotation import vtkAxesActor
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def get_program_parameters():
import argparse
description = 'Demonstrates the use of the Camera Orientation Widget.'
epilogue = '''
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('fname', nargs='?', default=None, help='The path to the file to render e.g. Human.vtp.')
args = parser.parse_args()
return args.fname
def main():
colors = vtkNamedColors()
colors.SetColor('ParaViewBlueGrayBkg', 84, 89, 109, 255)
colors.SetColor('ParaViewWarmGrayBkg', 98, 93, 90, 255)
file_name = get_program_parameters()
path = None
if file_name:
path = Path(file_name)
if not path.is_file():
print(f'Unable to find: {path}')
return
poly_data = read_poly_data(path)
else:
# Use a cone as a source with the golden ratio (φ) for the height. Because we can!
# If the short side is one then φ = 2 × sin(54°) or φ = 1/2 + √5 / 2
cone_source = vtkConeSource(center=(0, 0, 0), radius=1, height=(1.0 + math.sqrt(5.0)) / 2.0, resolution=64,
direction=(0, 1, 0))
poly_data = cone_source.update().output
# Assign a category for the labels and colors.
category = 'xyz'
if path is not None:
if path.name in ['Human.vtp', 'Torso.vtp']:
category = 'lrsiap'
elif path.name in ['cow.vtp', 'cowHead.vtp', 'horse.vtp', 'Bunny.vtp']:
category = 'apdvlr'
axes_labels = {
# Labels are: Anterior, Posterior, Dorsal, Ventral, Left, Right
'apdvlr': {'+X': 'A', '-X': 'P', '+Y': 'D', '-Y': 'V', '+Z': 'L', '-Z': 'R'},
# Labels are: Left, Right, Superior, Inferior, Anterior, Posterior
'lrsiap': {'+X': 'L', '-X': 'R', '+Y': 'S', '-Y': 'I', '+Z': 'A', '-Z': 'P'},
# Default labels
'xyz': None
}
axes_colors = {
'apdvlr': {'+X': 'IndianRed', '-X': 'FireBrick', '+Y': 'LimeGreen', '-Y': 'DarkGreen', '+Z': 'Blue',
'-Z': 'SteelBlue'},
'lrsiap': {'+X': 'IndianRed', '-X': 'FireBrick', '+Y': 'LimeGreen', '-Y': 'DarkGreen', '+Z': 'Blue',
'-Z': 'SteelBlue'},
# Default colors .
'xyz': None
}
# Transform the polydata.
tran = vtkTransform()
tran.Identity()
if path is not None:
if path.name == 'Human.vtp':
tran.RotateX(-90)
tran.RotateZ(180)
if path.name == 'Torso.vtp':
tran = vtkTransform()
tran.RotateX(-90)
if path.name == 'Bunny.vtp':
tran = vtkTransform()
tran.RotateY(180)
if path.name == 'horse.vtp':
tran = vtkTransform()
tran.RotateX(-90)
tran.RotateZ(270)
tf = vtkTransformPolyDataFilter(transform=tran)
surf = poly_data >> tf
mapper = vtkPolyDataMapper()
surf >> mapper
actor = vtkActor(mapper=mapper)
actor.property.color = colors.GetColor3d('Tan')
ren = vtkRenderer(background=colors.GetColor3d('ParaViewBLueGrayBkg'))
if path is None:
ren_win = vtkRenderWindow(size=(600, 600), window_name=f'{Path(argv[0]).name:s}')
else:
ren_win = vtkRenderWindow(size=(600, 600), window_name=f'{Path(argv[0]).name:s} {path.name}')
ren_win.AddRenderer(ren)
iren = vtkRenderWindowInteractor()
# Important: The interactor must be set prior
# to enabling the Camera Orientation Widget.
iren.render_window = ren_win
# Since we import vtkmodules.vtkInteractionStyle we can do this
# because vtkInteractorStyleSwitch is automatically imported:
iren.interactor_style.SetCurrentStyleToTrackballCamera()
ren.AddActor(actor)
cow = make_camera_orientation_widget(ren, axes_labels[category], axes_colors[category])
omw = make_orientation_marker_widget(ren, iren, axes_labels[category], axes_colors[category])
ren.ResetCamera()
ren_win.Render()
iren.Initialize()
iren.Start()
def read_poly_data(path):
"""
Use a vtk file reader to get the polydata.
:param path: The pathlib Path to the file.
:return:
"""
if path is None:
print(f'No file name.')
return None
valid_suffixes = ['.g', '.obj', '.stl', '.ply', '.vtk', '.vtp']
ext = None
if path.suffix:
ext = path.suffix.lower()
if path.suffix not in valid_suffixes:
print(f'No reader for this file suffix: {ext}')
return None
reader = None
if ext == '.ply':
reader = vtkPLYReader(file_name=path)
elif ext == '.vtp':
reader = vtkXMLPolyDataReader(file_name=path)
elif ext == '.obj':
reader = vtkOBJReader(file_name=path)
elif ext == '.stl':
reader = vtkSTLReader(file_name=path)
elif ext == '.vtk':
reader = vtkPolyDataReader(file_name=path)
elif ext == '.g':
reader = vtkBYUReader(file_name=path)
if reader:
return reader.update().output
else:
return None
def make_camera_orientation_widget(ren, axis_labels, axis_colors):
"""
Make a camera orientation widget for a given renderer.
:param ren: The renderer.
:param axis_labels: A dictionary of labels for the axis.
:param axis_colors: A dictionary of colors for the axis.
:return: The labelled camera orientation widget
"""
colors = vtkNamedColors()
cow = vtkCameraOrientationWidget(parent_renderer=ren)
if axis_labels is None:
# Use the default vtkCameraOrientationWidget
pass
else:
rep = cow.representation
rep.SetXPlusLabelText(axis_labels['+X'])
rep.SetXMinusLabelText(axis_labels['-X'])
rep.SetYPlusLabelText(axis_labels['+Y'])
rep.SetYMinusLabelText(axis_labels['-Y'])
rep.SetZPlusLabelText(axis_labels['+Z'])
rep.SetZMinusLabelText(axis_labels['-Z'])
rep.SetXAxisColor(colors.GetColor3d(axis_colors['+X']))
rep.SetYAxisColor(colors.GetColor3d(axis_colors['+Y']))
rep.SetZAxisColor(colors.GetColor3d(axis_colors['+Z']))
cow.SetRepresentation(rep)
cow.On()
return cow
def make_axes_actor(axis_labels, axis_colors):
"""
Make an Axes actor.
:param axis_labels: A dictionary of labels for the axis.
:param axis_colors: A dictionary of colors for the axis.
:return: The axis actor.
"""
colors = vtkNamedColors()
axes = vtkAxesActor()
if axis_labels is None:
# Use the default vtkOrientationMarkerWidget
pass
else:
axes.SetXAxisLabelText(axis_labels['+X'])
axes.SetYAxisLabelText(axis_labels['+Y'])
axes.SetZAxisLabelText(axis_labels['+Z'])
x_shaft_prop = axes.x_axis_shaft_property
x_shaft_prop.color = colors.GetColor3d(axis_colors['+X'])
x_tip_prop = axes.x_axis_tip_property
x_tip_prop.color = colors.GetColor3d(axis_colors['+X'])
y_shaft_prop = axes.y_axis_shaft_property
y_shaft_prop.color = colors.GetColor3d(axis_colors['+Y'])
y_tip_prop = axes.y_axis_tip_property
y_tip_prop.color = colors.GetColor3d(axis_colors['+Y'])
z_shaft_prop = axes.z_axis_shaft_property
z_shaft_prop.color = colors.GetColor3d(axis_colors['+Z'])
z_tip_prop = axes.z_axis_tip_property
z_tip_prop.color = colors.GetColor3d(axis_colors['+Z'])
return axes
def make_orientation_marker_widget(ren, iren, axis_labels, axis_colors):
"""
Make an orientation marker widget.
:param iren: Interactor
:param ren: Renderer
:param axis_labels: A dictionary of labels for the axis.
:param axis_colors: A dictionary of colors for the axis.
:return: The orientation marker widget.
"""
colors = vtkNamedColors()
axes = make_axes_actor(axis_labels, axis_colors)
rgba = [0.0] * 4
colors.GetColor('Carrot', rgba)
rgb = tuple(rgba[:3])
widget = vtkOrientationMarkerWidget(orientation_marker=axes,
interactor=iren, default_renderer=ren,
outline_color=rgb, viewport=(0.0, 0.0, 0.2, 0.2),
enabled=True, interactive=True, zoom=1.0)
return widget
if __name__ == '__main__':
main()