VTK Image To ITK Image

Warning

Fix Problem Contains problems not fixed from original wiki.

Synopsis

Convert a VTK image to an ITK image.

Results

Note

Help Wanted Implementation of Results for sphinx examples containing this message. Reconfiguration of CMakeList.txt may be necessary. Write An Example <https://itk.org/ITKExamples/Documentation/Contribute/WriteANewExample.html>

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>;

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

  ImageType::Pointer 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.