Read An Image


This examples demonstrates how to read an image file into an itk::Image. The file type is determined by the extension of the specified filename.





#include "itkImage.h"
#include "itkImageFileReader.h"

main(int argc, char * argv[])
  if (argc != 2)
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0];
    std::cerr << " <InputFileName>";
    std::cerr << std::endl;
    return EXIT_FAILURE;

  constexpr unsigned int Dimension = 2;

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

  using ReaderType = itk::ImageFileReader<ImageType>;
  ReaderType::Pointer reader = ReaderType::New();

  ImageType::Pointer image = reader->GetOutput();

  return EXIT_SUCCESS;

Classes demonstrated

template<typename TOutputImage, typename ConvertPixelTraits = DefaultConvertPixelTraits<typename TOutputImage::IOPixelType>>
class ImageFileReader : public itk::ImageSource<TOutputImage>

Data source that reads image data from a single file.

This source object is a general filter to read data from a variety of file formats. It works with a ImageIOBase subclass to actually do the reading of the data. Object factory machinery can be used to automatically create the ImageIOBase, or the ImageIOBase can be manually created and set. Note that this class reads data from a single file; if you wish to read data from a series of files use ImageSeriesReader.

TOutputImage is the type expected by the external users of the filter. If data stored in the file is stored in a different format then specified by TOutputImage, than this filter converts data between the file type and the external expected type. The ConvertTraits template argument is used to do the conversion.

A Pluggable factory pattern is used this allows different kinds of readers to be registered (even at run time) without having to modify the code in this class. Normally just setting the FileName with the appropriate suffix is enough to get the reader to instantiate the correct ImageIO and read the file properly. However, some files (like raw binary format) have no accepted suffix, so you will have to manually create the ImageIO instance of the write type.





ITK Sphinx Examples:

See itk::ImageFileReader for additional documentation.