VTK/Examples/Cxx
These are fully independent, compilable examples. There is significant overlap in the examples, but they are each intended to illustrate a different concept and be fully stand alone compilable.
Please add examples in your areas of expertise!
Contents
- 1 Simple Operations
- 2 Input and Output
- 3 Geometric Objects
- 4 Implicit Functions and Iso-surfaces
- 5 Working with 3D Data
- 6 Utilities
- 7 CMake Techniques
- 8 Math Operations
- 9 Graphs
- 10 Data Structures
- 11 VTK Concepts
- 12 Lighting
- 13 Visualization
- 14 Volume Rendering
- 15 User Interaction
- 16 Working with Images
- 17 Image Processing
- 18 Widgets
- 19 Plotting
- 20 Animation
- 21 Geographic Visualization (Geovis)
- 22 Information Visualization (Infovis)
- 23 Qt
- 24 Matlab
- 25 Databases
- 26 Broken/Missing Examples (Please write/fix me!)
Simple Operations
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Distance between a point and a line | vtkLine | |
Distance between two points | vtkMath::Distance2BetweenPoints | Computes the distance between two points |
Random number (uniform distribution) | vtkMath | Generates uniform random numbers |
Random number (Gaussian distribution) | vtkMath | Generates Gaussian random numbers |
Random sequence | vtkMinimalStandardRandomSequence | This is the preferred way to generate random numbers. |
Project a point onto a plane | vtkPlane | Project a point onto a plane |
Floating Point Exceptions | vtkFloatingPointExceptions | Floating Point Exceptions |
Apply a perspective transformation to a point | vtkPerspectiveTransform |
Input and Output
Graph Formats
3D File Formats
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Convert a file from one type to another | ||
Read a .gml file | vtkXGMLReader |
Standard Formats
Input
Output
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Write a simple ".xyz" file | vtkSimplePointsWriter | |
Write stereo lithography STL (.stl) files | vtkSTLWriter | |
Write PLY (.ply) files | vtkPLYWriter | |
Write data to a delimited file | vtkDelimitedTextWriter |
VTK Formats
Input
Output
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Write a .vtu file | vtkXMLUnstructuredGridWriter | VTU is an "Unstructured Grid". This format allows for 3D data to be stored. |
Write a .vtp file | vtkXMLPolyDataWriter | VTP is a "PolyData". This format allows for the most complex geometric objects to be stored. |
Write a .vti file | vtkXMLImageDataWriter | VTI is an "ImageData". |
Write a .vts file from a vtkStructuredGrid | vtkXMLStructuredGridWriter |
Legacy VTK Formats
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Read any type of legacy .vtk file | vtkGenericDataObjectReader | |
Read a structured grid (.vtk) file | vtkStructuredGridReader | |
StructuredPointsReader | vtkStructuredPointsReader |
Image Formats
Input
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Read BMP (.bmp) files | vtkBMPReader | |
Read a JPG image | vtkJPEGReader | |
Read a PNG image | vtkPNGReader | |
Read PNM (.pnm) files | vtkPNMReader | |
Read TIFF (.tif) files | vtkTIFFReader | |
Read .mha files | vtkMetaImageReader | |
Read most standard image formats. | vtkImageReader2Factory | This class tries to find an appropriate reader. It is very convenient to use this when you don't know what kind of file to expect. |
Output
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Write a BMP (.bmp) file | vtkBMPWriter | |
Write a JPEG (.jpg) file | vtkJPEGWriter | |
Write a PNG (.png) file | vtkPNGWriter | |
Write a PNM (.pnm) file | vtkPNMWriter | |
Write a TIFF (.tif) file | vtkTIFFWriter | |
Write a .mha/.mhd + .raw file | vtkMetaImageWriter |
Geometric Objects
Parametric Objects
These examples demonstrate how to create an display one of the many vtkParametric* objects. All of the classes listed can be used in an identical fashion.
Implicit Functions and Iso-surfaces
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Visualize different isocontours using a slider | vtkContourFunction | |
Sample and visualize an implicit function | vtkSampleFunction | |
Extract largest isosurface | vtkPolyDataConnectivityFilter | |
BandedPolyDataContourFilter | vtkBandedPolyDataContourFilter | |
Create filled contours (vtkClipPolyData) | vtkContourFilter | |
An implicit representation of a sphere | vtkSphere | |
Marching cubes | vtkMarchingCubes | Create a voxelized sphere |
Marching squares | vtkMarchingSquares | Create a contour from a structured point set (image) |
Working with 3D Data
Data Type Conversions
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Convert a vtkPolyData to a vtkUnstructuredGrid | vtkAppendFilter |
Point cloud operations
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Generate a random point cloud | vtkPointSource | |
Downsample a point cloud | vtkCleanPolyData | Remove points so that there are no points within a tolerance of any point. |
Working with Meshes
Working with Structured 3D Data
This section includes vtkImageData, vtkStructuredGrid, and vtkRectilinearGrid.
"ImageData" is not the traditional "flat, 2D image" you are used to. It is a special VTK data structure in the collection of 3D data structures provided by VTK. Here is an overview of these data structures: [1]. Image data can represent at typical 2D image, but also, a 3D volume.
vtkImageData
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Get the coordinates of the center of a cell | vtkImageData | |
Get the id of a cell from its grid coordinates | vtkStructuredData | |
Iterating over a vtkImageData | vtkImageData | Set and access locations in a 3D image. Iterate. |
Normalize an image | vtkImageNormalize | |
Extract a volume of interest (subvolume) | vtkExtractVOI | Crop |
Add two or more images | vtkImageWeightedSum | |
Resize a vtkImageData | vtkImageReslice | |
Change the extent of a vtkImageData | vtkImageTranslateExtent |
Conversions
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Convert a vtkImageData to a vtkPolyData | vtkImageDataGeometryFilter | |
Convert a vtkImageData to a vtkStructuredGrid | vtkImageDataToPointSet |
vtkStructuredGrid
vtkStructuredPoints
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Convert a vtkStructuredPoints to a vtkUnstructuredGrid | vtkStructuredPoints, vtkUnstructuredGrid |
vtkRectilinearGrid
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Rectilinear grid | vtkRectilinearGrid | |
Visualize the cells of a rectilinear grid | vtkRectilinearGrid, vtkShrinkFilter | |
Convert a vtkRectilinearGrid to a vtkUnstructuredGrid mesh | vtkRectilinearGridToTetrahedra |
Registration
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Iterative Closest Points (ICP) Transform | vtkIterativeClosestPointTransform | |
Landmark Transform | vtkLandmarkTransform |
Surface reconstruction
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Create a surface from Unorganized Points (Gaussian Splat) | vtkGaussianSplatter | |
Triangulate a Terrain Map | vtkDelaunay2D | Generate heights (z values) on a 10x10 grid (a terrain map) and then triangulate the points to form a surface. |
Create cubes from labeled volume data | vtkMetaImageReader, vtkMaskFields | |
Create models from labeled volume data (Discrete MarchingCubes) | vtkDiscreteMarchingCubes | |
Create a solid mesh from Unorganized Points (Delaunay3D) | vtkDelaunay3D | Convex hull. |
Create a surface from Unorganized Points (with post processing) | vtkSurfaceReconstructionFilter | |
Create a surface from Unorganized Points | vtkSurfaceReconstructionFilter |
Utilities
CMake Techniques
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Check if a specific module is present | ||
Check VTK Version in CMake |
Math Operations
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
LU Factorization | vtkMath | |
Normalize a vector | vtkMath | |
vtkVectorDot | vtkVectorDot | |
Raise all elements in an array to a power | vtkPowerWeighting | |
Least Squares | vtkMath::SolveLeastSquares | |
Homogeneous Least Squares | vtkMath::SolveHomogeneousLeastSquares | |
Compute eigenvalues and eigenvectors of a symmetric matrix | vtkMath::Jacobi | |
Matrix transpose | vtkMatrix3x3 | |
Matrix inverse | vtkMatrix3x3 | |
Get a vector perpendicular to another vector | vtkMath::Perpendiculars | |
Get the lengths of an array of vectors | vtkVectorNorm | |
Interpolate 1-tuples (linear, spline-based) | vtkTupleInterpolator vtkCardinalSpline vtkKochanekSpline | A simple example demonstrating how functions defined by sparsely distributed supporting points can be interpolated at arbitrary positions. |
Graphs
Graph Conversions
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
vtkMutableDirectedGraph to vtkDirectedGraph | vtkMutableDirectedGraph, vtkDirectedGraph | |
vtkDirectedGraph to vtkMutableDirectedGraph | vtkMutableDirectedGraph, vtkDirectedGraph | |
vtkTree to vtkMutableDirectedGraph | vtkMutableDirectedGraph, vtkTree |
Graph Conversions That Don't Work
Data Structures
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Attach attributes | vtkInformation | Attach attributes to a VTK array |
Find all points within a radius of a specified point | vtkPointLocator | |
Visualization of the tree of a vtkCellLocator | vtkCellLocator | |
Visualization of the tree of a vtkPointLocator | vtkPointLocator | |
Efficient 3D point query | vtkPointLocator | |
Efficient 3D cell query | vtkCellLocator | |
Points inside an object using vtkCellTreeLocator | vtkCellTreeLocator |
Timing Demonstrations
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Octree timing demo | vtkOctreePointLocator | Plot the runtime vs MaxPointsPerRegion |
KDTree timing demo | vtkKdTreePointLocator | Plot the runtime vs MaxLevel (doesn't seem correct) |
OBBTree timing demo | vtkOBBTree | Plot the runtime vs MaxLevel |
ModifiedBSPTree timing demo | vtkModifiedBSPTree | Plot the runtime vs MaxLevel |
KD-Tree
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
vtkKdTree_BuildLocatorFromPoints | vtkKdTree | |
vtkKdTree_BuildLocatorFromPoints_ClosestKPoints | vtkKdTree | |
Access the points of a KDTree | vtkKdTree | |
Find the closest point to a query point | vtkKdTreePointLocator | |
Find the closest N points to a query point | vtkKdTreePointLocator | |
Visualize levels of the tree | vtkKdTreePointLocator | |
Find points within a specified radius of a query point | vtkKdTreePointLocator | |
Data structure comparison | vtkKdTree, vtkOBBTree, vtkOctreePointLocator, vtkModifiedBSPTree | Illustrates, side by side, the differences between several spatial data structures |
Oriented Bounding Box (OBB) Tree
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Intersect a line with a vtkOBBTree | vtkOBBTree | |
Intersect a line with an OBB Tree and display all intersected cells | vtkOBBTree | |
Visualize levels of the tree | vtkOBBTree |
Octree
Modified BSP Tree
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Intersect a line with a modified BSP Tree | vtkModifiedBSPTree | |
Intersect a line with a modified BSP Tree and display all intersected cells | vtkModifiedBSPTree | |
Visualize levels of the tree | vtkModifiedBSPTree |
VTK Concepts
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Attach a scalar value to each point (PointData) or cell (CellData) in a data set |
Lighting
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Create shadows | vtkShadowMapPass | |
Add a directional light to a scene | vtkLight | |
Display the location and direction of a light | vtkLightActor |
Visualization
See this tutorial for a brief explanation of the VTK terminology of mappers, actors, etc.
Volume Rendering
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
HAVS | vtkHAVSVolumeMapper | |
Smart volume mapper | vtkSmartVolumeMapper | |
Min intensity rendering | vtkFixedPointVolumeRayCastMapper | |
ITK->VTK conversion | Conversion maintaining DICOM orientation and position |
User Interaction
Working with Images
Image Processing
Widgets
Plotting
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Line plot | vtkChartXY | |
Scatter plot | vtkPlotPoints | |
Bar chart | vtkChartXY | |
Pie chart | vtkChartPie, vtkPlotPie | |
Parallel coordinates | vtkChartParallelCoordinates | |
Diagram |
Animation
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Animate actors | vtkAnimationScene, vtkAnimationCue | |
Animation | vtkRenderWindowInteractor::CreateRepeatingTimer | Move a sphere across a scene. |
Animation (the right way) | vtkAnimationScene, vtkAnimationCue | Zoom in on a sphere. |
Data Animation | vtkCallbackCommand, vtkProgrammableFilter | Update points in a dataset every specified interval. |
Data Animation (subclass) | vtkCommand, vtkProgrammableFilter | Update points in a dataset every specified interval (using a vtkCommand subclass instead of a callback function. |
Geographic Visualization (Geovis)
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Compass Widget | vtkCompassWidget | |
Earth source | vtkEarthSource | Create the Earth. |
Convert lat/long coordinates to world coordinates | vtkGeoAssignCoordinates |
Information Visualization (Infovis)
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Parallel coordinates | vtkParallelCoordinatesView | |
Tree map | vtkTreeMapView |
Qt
Click here for a tutorial on how to setup Qt.
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Convert a QImage to a vtkImageData | vtkQImageToImageSource | |
Use the showEvent event to do things that you might want to do in the constructor | ||
Render window without a .ui file | QVTKWidget | This is a very basic example that shows how to create a Qt window. Typically, one would want to design a form in the QtDesigner (this is shown in RenderWindowUi) |
Render window with a .ui (single inheritance) | QMainWindow | Using a QVTKWidget with the Qt Single Inheritance model |
Render window with a .ui (multiple inheritance) | QMainWindow | Using a QVTKWidget with the Qt Multiple Inheritance model |
Side by side render windows | QApplication | |
vtkQtBarChart | vtkQtBarChart | |
Border Widget | vtkBorderWidget, QApplication | |
Connect a VTK event to a Qt slot | vtkEventQtSlotConnect | |
Convert a vtkImageData to a QImage | ||
Share the camera between QVTKWidgets |
Matlab
You must turn on VTK_USE_MATLAB_MEX to use these.
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
vtkMatlabEngineFilter | vtkMatlabEngineFilter |
Databases
SQL
If you have any trouble or errors with the following examples, please troubleshoot using these instructions.
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Connect to and read a MySQL database | vtkMySQLDatabase, vtkSQLQuery | |
Create a MySQL database | vtkMySQLDatabase | |
Write to a MySQL database | vtkSQLQuery, vtkMySQLDatabase |
Broken/Missing Examples (Please write/fix me!)
Some of these are simply shells waiting for a good example. Some of these have a specific problem that is noted. Please help improve them!
Testing Needed
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
AVI (Windows only) | vtkAVIWriter | Someone please test this. |
OggTheora | vtkOggTheoraWriter | Can't find lvtkoggtheora |
MPEG2 | vtkMPEG2Writer | CMake won't find MPEG2 include? |
FFMPEG | vtkFFMPEGWriter | CMake won't find FFMPEG include? |
Display a histogram | vtkImageAccumulate, vtkBarChartActor | Testing images seem to vary slightly on different machines. |
Small Problems
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Interact/move the vertices of a graph | vtkGraph | |
Read an mdb Access database file | vtkODBCDatabase | Error: “Could not execute statement” |
Sobel edge detection 3D | vtkImageSobel3D | |
Anisotropic diffusion (3D) | vtkImageAnisotropicDiffusion3D | Need a suitable input. |
Write an ExodusII file | vtkExodusIIWriter | Write a time varying file. Someone who is familiar with this format should make a reasonable example. |
ImageReader2 | vtkImageReader2 | No errors, but no image is displayed. I think this is a superclass not intended to be used directly? |
Stacked plot | vtkPlotStacked | Image produced is not consistent. Try again after Marcus merges StringToImage topic. |
Display a representative object of each class derived from vtkCell3D | vtkCell3D | HexagonalPrism seems wrong, Polyhedron is empty. |
Low pass filter an image | vtkImageIdealLowPass | |
Delete points | vtkPolyData | No longer crashes but doesn't seem to do anything. See example Delete cells. |
Delete cells | vtkPolyData | Not sure if this has much utility? |
Play/stop/fast forward etc buttons | vtkPlaybackWidget | Need to show user how to start recording? Playback a recording? |
Get world coordinates of mouse click | vtkCoordinate | When zoomed this does not produce the correct coordinate. vtkWorldPointPicker? |
Vary the shape of vertices | vtkGraphLayoutView | |
Vary the width of edges | vtkGraphLayoutView | |
Write an unstructured grid to parallel files | vtkXMLPUnstructuredGridWriter | Even with SetNumberOfPieces(4), only 2 files are generated? |
Convert a vtkTable to a vtkGraph | vtkTableToGraph | How to specify the columns? |
Generate a diagonal matrix | vtkDiagonalMatrixSource | What type is output? |
Generate different glyphs based on a table | vtkGlyph3D | How to specify which values get which glyphs? |
Write an image file to parallel files | vtkXMLPImageDataWriter | Even with SetNumberOfPieces(4), only 2 files are generated? |
Combine the points of multiple PolyData datasets | vtkAppendPoints | The data sets seem to have been combined (there are 10 points and 10 cells in the output), but nothing is displayed -- this is because the points and cells are copied but not the verts. See example vtkAppendPolyData instead (there's already an example for that). |
Extract a subgraph | vtkExtractSelectedGraph | Waiting for dual vtkGraphView |
Order cells from a viewing direction | vtkKdTree | |
Merge selections | vtkSelection | |
SpherePuzzle | vtkSpherePuzzle | Looks like a beach ball... what is the point? |
vtkImageIterator | vtkImageIterator | |
Extract points based on a criterion function | vtkExtractSelectedThresholds | |
Clip using an implicit data set | vtkImplicitDataSet | |
Get connected cells | vtkCellLinks | How to use vtkCellLinks::Links class? How to know how many cells GetCells returns? |
Convert data from an object into a vtkTable | vtkDataObjectToTable | How to get the point coordinates into the table? |
vtkImageViewer2 | vtkImageViewer2 | How to start the interaction? |
Convert a polydata to an implicit function | vtkImplicitDataSet | The error is: "Can't evaluate dataset!" |
vtkCameraWidget | vtkCameraWidget | How to use this? |
Compute occupancy of an object on a grid | vtkVoxelModeller | VTK_BIT is not supported - convert it? |
Divide a point cloud into uniform cubic voxels | vtkCellLocator | We can determine which cell a point is in, but how to determine which points are in a particular cell? |
Flight | vtkInteractorStyleFlight | linux keypresses not handled. I submitted a patch to the devel list - we'll see if they respond. |
vtkPointHandleRepresentation2D | vtkPointHandleRepresentation2D | |
RecordEvents | vtkInteractorEventRecorder | How to exit? |
PlayBackEvents | vtkInteractorEventRecorder | How to slow down? |
Quadric Surface Fitting | vtkQuadric | |
Rectangular button source | vtkRectangularButtonSource | is this the intended usage? |
ApplyColors | vtkApplyColors | How is this different from just adding a Colors array to a vtkDataSet? |
vtkPCAAnalysisFilter | vtkPCAAnalysisFilter | What is the difference between this and vtkPCAStatistics? The eigenvalues vector doesn't seem to be valid. It seems like the eigenvector corresponding to the smallest value is stored as the normal of the cell in the output - how do you get the other two eigen vectors? |
Wish List
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
Plot data (Legacy method) | vtkXYPlotActor | The charts examples always seem to render slightly differently. |
Display a histogram | vtkImageAccumulate, XYPlotActor | The charts examples always seem to render slightly differently. |
vtkTableBasedClipDataSet | vtkTableBasedClipDataSet | Empty |
vtkLSDynaReader | vtkLSDynaReader | Empty |
vtkCompositeDataGeometryFilter | vtkCompositeDataGeometryFilter | Empty - combine multiple blocks into a single data set |
vtkTryDowncast | vtkTryDowncast | Empty |
vtkCubeAxesActor2D | vtkCubeAxesActor2D |
Big Problems
Example Name | VTK Classes Demonstrated | Description |
---|---|---|
A comparison of some graph layout strategies | vtkGraphLayoutView | This crashes unless you build against the VTK-SideBySideGraphs branch from here: git@github.com:daviddoria/daviddoria-vtk.git |
Extract iso-surfaces | vtkMarchingContourFilter | No output produced without a vtkVoxelModeller, strange output produced with a vtkVoxelModeller. |
Set a value by manipulating something | vtkContinuousValueWidget | Can't instantiate this class? But nothing derives from it? |
Delete a cell. | vtkPolyData | I tried this with lines and it doesn't work (crashes). The documentation says only works with polys - so wait for this functionality to be added? |
Box intersection | vtkBox | This class doesn't have any non static functions! Need to create convenience functions. |
vtkTensorProbeWidget | vtkTensorProbeWidget | How is this used? |
GeoGlobeSource | vtkGeoGlobeSource | |
GeoView | vtkGeoView | |
FixedPointRayCastImage | vtkFixedPointRayCastImage | Shell |
vtkFrustumCoverageCuller | vtkFrustumCoverageCuller | Doesn't seem to have a property to specify a frustum? What is it for? How to use it? |
vtkKdTreeSelector | vtkKdTreeSelector | Shell |
vtkRungeKutta4 | vtkRungeKutta4 | Shell |
vtkCoincidentPoints | vtkCoincidentPoints | What is this for? |
Threaded/Parallel example | Shell | |
Assign an array to a particular field | vtkAssignAttribute | Shell |
vtkTransposeMatrix | vtkTransposeMatrix | What is this supposed to operate on? There is no vtkMatrix class. |
vtkHyperOctree | vtkHyperOctree | What does this do? |
vtkTextExtraction | vtkTextExtraction | Shell |