VTK Image to ITK Image#

Synopsis#

Convert a VTK image to an ITK image.

Results#

Input image.

Input Image#

QuickView output.

Output In QuickView#

Code#

C++#

#include <itkImage.h>

#include <itkVTKImageToImageFilter.h>

#include "vtkSmartPointer.h"
#include "vtkPNGReader.h"
#include <vtkImageLuminance.h>

#ifdef ENABLE_QUICKVIEW
#  include "QuickView.h"
#endif

int
main(int argc, char * argv[])
{
  if (argc < 2)
  {
    std::cerr << "Required: filename" << std::endl;
    return EXIT_FAILURE;
  }

  vtkSmartPointer<vtkPNGReader> reader = vtkSmartPointer<vtkPNGReader>::New();
  reader->SetFileName(argv[1]);
  // reader->SetNumberOfScalarComponents(1); //doesn't seem to work - use ImageLuminance instead
  reader->Update();


  // Must convert image to grayscale because itkVTKImageToImageFilter only accepts single channel images
  vtkSmartPointer<vtkImageLuminance> luminanceFilter = vtkSmartPointer<vtkImageLuminance>::New();
  luminanceFilter->SetInputConnection(reader->GetOutputPort());
  luminanceFilter->Update();

  using ImageType = itk::Image<unsigned char, 2>;

  using VTKImageToImageType = itk::VTKImageToImageFilter<ImageType>;

  auto vtkImageToImageFilter = VTKImageToImageType::New();
  vtkImageToImageFilter->SetInput(luminanceFilter->GetOutput());
  // vtkImageToImageFilter->SetInput(reader->GetOutput());
  vtkImageToImageFilter->Update();

  auto image = ImageType::New();
  image->Graft(vtkImageToImageFilter->GetOutput()); // Need to do this because QuickView can't accept const

#ifdef ENABLE_QUICKVIEW
  QuickView viewer;
  viewer.AddImage(image.GetPointer()); // Need to do this because QuickView can't accept smart pointers
  viewer.Visualize();
#endif

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TOutputImage>
class VTKImageToImageFilter : public itk::VTKImageImport<TOutputImage>

Converts a VTK image into an ITK image and plugs a VTK data pipeline to an ITK datapipeline.

This class puts together an itk::VTKImageImport and a vtk::ImageExport. It takes care of the details related to the connection of ITK and VTK pipelines. The User will perceive this filter as an adaptor to which a vtkImageData can be plugged as input and an itk::Image is produced as output.

ITK Sphinx Examples:

See itk::VTKImageToImageFilter for additional documentation.