Chapter 6
Reading and Writing Images

This chapter describes the toolkit architecture supporting reading and writing of images to files. OTB does not enforce any particular file format, instead, it provides a structure inherited from ITK, supporting a variety of formats that can be easily extended by the user as new formats become available.

We begin the chapter with some simple examples of file I/O.

6.1 Basic Example

The source code for this example can be found in the file
Examples/IO/ImageReadWrite.cxx.

The classes responsible for reading and writing images are located at the beginning and end of the data processing pipeline. These classes are known as data sources (readers) and data sinks (writers). Generally speaking they are referred to as filters, although readers have no pipeline input and writers have no pipeline output.

The reading of images is managed by the class otb::ImageFileReader while writing is performed by the class otb::ImageFileWriter . These two classes are independent of any particular file format. The actual low level task of reading and writing specific file formats is done behind the scenes by a family of classes of type itk::ImageIO . Actually, the OTB image Readers and Writers are very similar to those of ITK, but provide new functionnalities which are specific to remote sensing images.

The first step for performing reading and writing is to include the following headers.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

Then, as usual, a decision must be made about the type of pixel used to represent the image processed by the pipeline. Note that when reading and writing images, the pixel type of the image is not necessarily the same as the pixel type stored in the file. Your choice of the pixel type (and hence template parameter) should be driven mainly by two considerations:

A typical selection for remote sensing images is illustrated in the following lines.

    typedef unsigned short PixelType;
    const unsigned int Dimension = 2;
    typedef otb::Image<PixelType, Dimension> ImageType;

Note that the dimension of the image in memory should match the one of the image in file. There are a couple of special cases in which this condition may be relaxed, but in general it is better to ensure that both dimensions match. This is not a real issue in remote sensing, unless you want to consider multi-band images as volumes (3D) of data.

We can now instantiate the types of the reader and writer. These two classes are parameterized over the image type.

    typedef otb::ImageFileReader<ImageType> ReaderType;
    typedef otb::ImageFileWriter<ImageType> WriterType;

Then, we create one object of each type using the New() method and assigning the result to a itk::SmartPointer .

    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

The name of the file to be read or written is passed with the SetFileName() method.

    reader->SetFileName(inputFilename);
    writer->SetFileName(outputFilename);

We can now connect these readers and writers to filters to create a pipeline. For example, we can create a short pipeline by passing the output of the reader directly to the input of the writer.

    writer->SetInput(reader->GetOutput());

At first view, this may seem as a quite useless program, but it is actually implementing a powerful file format conversion tool! The execution of the pipeline is triggered by the invocation of the Update() methods in one of the final objects. In this case, the final data pipeline object is the writer. It is a wise practice of defensive programming to insert any Update() call inside a try/catch block in case exceptions are thrown during the execution of the pipeline.

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject& err)
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }

Note that exceptions should only be caught by pieces of code that know what to do with them. In a typical application this catch block should probably reside on the GUI code. The action on the catch block could inform the user about the failure of the IO operation.

The IO architecture of the toolkit makes it possible to avoid explicit specification of the file format used to read or write images.1 The object factory mechanism enables the ImageFileReader and ImageFileWriter to determine (at run-time) with which file format it is working with. Typically, file formats are chosen based on the filename extension, but the architecture supports arbitrarily complex processes to determine whether a file can be read or written. Alternatively, the user can specify the data file format by explicit instantiation and assignment the appropriate itk::ImageIO subclass.

To better understand the IO architecture, please refer to Figures 6.1, 6.2, and 6.3.


PIC

Figure 6.1: Collaboration diagram of the ImageIO classes.



PIC

Figure 6.2: Use cases of ImageIO factories.



PIC

Figure 6.3: Class diagram of the ImageIO factories.


The following section describes the internals of the IO architecture provided in the toolbox.

6.2 Pluggable Factories

The principle behind the input/output mechanism used in ITK and therefore OTB is known as pluggable-factories [48]. This concept is illustrated in the UML diagram in Figure 6.1. From the user’s point of view the objects responsible for reading and writing files are the otb::ImageFileReader and otb::ImageFileWriter classes. These two classes, however, are not aware of the details involved in reading or writing particular file formats like PNG or GeoTIFF. What they do is to dispatch the user’s requests to a set of specific classes that are aware of the details of image file formats. These classes are the itk::ImageIO classes. The ITK delegation mechanism enables users to extend the number of supported file formats by just adding new classes to the ImageIO hierarchy.

Each instance of ImageFileReader and ImageFileWriter has a pointer to an ImageIO object. If this pointer is empty, it will be impossible to read or write an image and the image file reader/writer must determine which ImageIO class to use to perform IO operations. This is done basically by passing the filename to a centralized class, the itk::ImageIOFactory and asking it to identify any subclass of ImageIO capable of reading or writing the user-specified file. This is illustrated by the use cases on the right side of Figure 6.2. The ImageIOFactory acts here as a dispatcher that help to locate the actual IO factory classes corresponding to each file format.

Each class derived from ImageIO must provide an associated factory class capable of producing an instance of the ImageIO class. For example, for PNG files, there is a itk::PNGImageIO object that knows how to read this image files and there is a itk::PNGImageIOFactory class capable of constructing a PNGImageIO object and returning a pointer to it. Each time a new file format is added (i.e., a new ImageIO subclass is created), a factory must be implemented as a derived class of the ObjectFactoryBase class as illustrated in Figure 6.3.

For example, in order to read PNG files, a PNGImageIOFactory is created and registered with the central ImageIOFactory singleton2 class as illustrated in the left side of Figure 6.2. When the ImageFileReader asks the ImageIOFactory for an ImageIO capable of reading the file identified with filename the ImageIOFactory will iterate over the list of registered factories and will ask each one of them is they know how to read the file. The factory that responds affirmatively will be used to create the specific ImageIO instance that will be returned to the ImageFileReader and used to perform the read operations.

With respect to the ITK formats, OTB adds most of the remote sensing image formats. In order to do so, the Geospatial Data Abstraction Library, GDAL http://www.gdal.org/, is encapsultated in a ImageIO factory. GDAL is a translator library for raster geospatial data formats that is released under an X/MIT style Open Source license. As a library, it presents a single abstract data model to the calling application for all supported formats, which include CEOS, GeoTIFF, ENVI, and much more. See http://www.gdal.org/formats_list.html for the full format list.

Since GDAL is itself a multi-format library, the GDAL IO factory is able to choose the appropriate resource for reading and writing images.

In most cases the mechanism is transparent to the user who only interacts with the ImageFileReader and ImageFileWriter. It is possible, however, to explicitly select the type of ImageIO object to use. Please see the ITK Software for more details about this.

6.3 IO Streaming

6.3.1 Implicit Streaming

The source code for this example can be found in the file
Examples/IO/StreamingImageReadWrite.cxx.

As we have seen, the reading of images is managed by the class otb::ImageFileReader while writing is performed by the class otb::ImageFileWriter . ITK’s pipeline implements streaming. That means that a filter for which the ThreadedGenerateData method is implemented, will only produce the data for the region requested by the following filter in the pipeline. Therefore, in order to use the streaming functionality one needs to use a filter at the end of the pipeline which requests for adjacent regions of the image to be processed. In ITK, the itk::StreamingImageFilter class is used for this purpose. However, ITK does not implement streaming from/to files. This means that even if the pipeline has a small memory footprint, the images have to be stored in memory at least after the read operation and before the write operation.

OTB implements read/write streaming. For the image file reading, this is transparent for the programmer, and if a streaming loop is used at the end of the pipeline, the read operation will be streamed. For the file writing, the otb::ImageFileWriter has to be used.

The first step for performing streamed reading and writing is to include the following headers.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

Then, as usual, a decision must be made about the type of pixel used to represent the image processed by the pipeline.

    typedef unsigned char PixelType;
    const unsigned int Dimension = 2;
    typedef otb::Image<PixelType, Dimension> ImageType;

We can now instantiate the types of the reader and writer. These two classes are parameterized over the image type. We will rescale the intensities of the as an example of intermediate processing step.

    typedef otb::ImageFileReader<ImageType>                        ReaderType;
    typedef itk::RescaleIntensityImageFilter<ImageType, ImageType> RescalerType;
    typedef otb::ImageFileWriter<ImageType>               WriterType;

Then, we create one object of each type using the New() method and assigning the result to a itk::SmartPointer .

    ReaderType::Pointer   reader = ReaderType::New();
    RescalerType::Pointer rescaler = RescalerType::New();
    WriterType::Pointer   writer = WriterType::New();

The name of the file to be read or written is passed with the SetFileName() method. We also choose the range of intensities for the rescaler.

    reader->SetFileName(inputFilename);
    rescaler->SetOutputMinimum(0);
    rescaler->SetOutputMaximum(255);
    writer->SetFileName(outputFilename);

We can now connect these readers and writers to filters to create a pipeline.

    rescaler->SetInput(reader->GetOutput());
    writer->SetInput(rescaler->GetOutput());

We can now trigger the pipeline execution by calling the Update method on the writer.

      writer->Update();

The writer will ask its preceding filter to provide different portions of the image. Each filter in the pipeline will do the same until the request arrives to the reader. In this way, the pipeline will be executed for each requested region and the whole input image will be read, processed and written without being fully loaded in memory.

6.3.2 Explicit Streaming

The source code for this example can be found in the file
Examples/IO/ExplicitStreamingExample.cxx.

Usually, the streaming process is hidden within the pipeline. This allows the user to get rid of the annoying task of splitting the images into tiles, and so on. However, for some kinds of processing, we do not really need a pipeline: no writer is needed, only read access to pixel values is wanted. In these cases, one has to explicitly set up the streaming procedure. Fortunately, OTB offers a high level of abstraction for this task. We will need to include the following header files:

  #include "otbRAMDrivenAdaptativeStreamingManager.h"

The otb::RAMDrivenAdaptativeStreamingManager class manages the streaming approaches which are possible with the image type over which it is templated. The class itk::ImageRegionSplitter is templated over the number of dimensions of the image and will perform the actual image splitting. More information on splitter can be found in section 27.3

  //  typedef otb::StreamingTraits<ImageType> StreamingTraitsType;
  //  typedef itk::ImageRegionSplitter<2>     SplitterType;
    typedef otb::RAMDrivenAdaptativeStreamingManager<ImageType> StreamingManagerType;

Once a region of the image is available, we will use classical region iterators to get the pixels.

    typedef ImageType::RegionType RegionType;
  
    typedef itk::ImageRegionConstIterator<ImageType> IteratorType;

We instantiate the image file reader, but in order to avoid reading the whole image, we call the GenerateOutputInformation() method instead of the Update() one. GenerateOutputInformation() will make available the information about sizes, band, resolutions, etc. After that, we can access the largest possible region of the input image.

    ImageReaderType::Pointer reader = ImageReaderType::New();
  
    reader->SetFileName(infname);
  
    reader->GenerateOutputInformation();
  
    RegionType largestRegion = reader->GetOutput()->GetLargestPossibleRegion();

We set up now the local streaming capabilities by asking the streaming traits to compute the number of regions to split the image into given the splitter, the user defined number of lines, and the input image information.

  /⋆
    SplitterType::Pointer splitter = SplitterType::New();
    unsigned int          numberOfStreamDivisions =
      StreamingTraitsType::CalculateNumberOfStreamDivisions(
        reader->GetOutput(),
        largestRegion,
        splitter,
        otb::SET_BUFFER_NUMBER_OF_LINES,
        0, 0, nbLinesForStreaming);

We can now get the split regions and iterate through them.

    unsigned int piece = 0;
    RegionType   streamingRegion;
  
    for (piece = 0;
         piece < numberOfStreamDivisions;
         piece++)
      {

We get the region

      /⋆streamingRegion =
        splitter->GetSplit(piece, numberOfStreamDivisions, largestRegion);
      ⋆/
      streamingRegion = streamingManager->GetSplit(piece);
      std::cout << "Processing region: " << streamingRegion << std::endl;

We ask the reader to provide the region.

      reader->GetOutput()->SetRequestedRegion(streamingRegion);
      reader->GetOutput()->PropagateRequestedRegion();
      reader->GetOutput()->UpdateOutputData();

We declare an iterator and walk through the region.

      IteratorType it(reader->GetOutput(), streamingRegion);
      it.GoToBegin();
  
      while (!it.IsAtEnd())
        {
        std::cout << it.Get() << std::endl;
        ++it;
        }

6.4 Reading and Writing RGB Images

The source code for this example can be found in the file
Examples/IO/RGBImageReadWrite.cxx.

RGB images are commonly used for representing data acquired from multispectral sensors. This example illustrates how to read and write RGB color images to and from a file. This requires the following headers as shown.

  #include "itkRGBPixel.h"
  #include "otbImage.h"
  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

The itk::RGBPixel class is templated over the type used to represent each one of the red, green and blue components. A typical instantiation of the RGB image class might be as follows.

    typedef itk::RGBPixel<unsigned char> PixelType;
    typedef otb::Image<PixelType, 2>     ImageType;

The image type is used as a template parameter to instantiate the reader and writer.

    typedef otb::ImageFileReader<ImageType> ReaderType;
    typedef otb::ImageFileWriter<ImageType> WriterType;
  
    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

The filenames of the input and output files must be provided to the reader and writer respectively.

    reader->SetFileName(inputFilename);
    writer->SetFileName(outputFilename);

Finally, execution of the pipeline can be triggered by invoking the Update() method in the writer.

    writer->Update();

You may have noticed that apart from the declaration of the PixelType there is nothing in this code that is specific for RGB images. All the actions required to support color images are implemented internally in the itk::ImageIO objects.

6.5 Reading, Casting and Writing Images

The source code for this example can be found in the file
Examples/IO/ImageReadCastWrite.cxx.

Given that ITK and OTB are based on the Generic Programming paradigm, most of the types are defined at compilation time. It is sometimes important to anticipate conversion between different types of images. The following example illustrates the common case of reading an image of one pixel type and writing it on a different pixel type. This process not only involves casting but also rescaling the image intensity since the dynamic range of the input and output pixel types can be quite different. The itk::RescaleIntensityImageFilter is used here to linearly rescale the image values.

The first step in this example is to include the appropriate headers.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"
  #include "itkUnaryFunctorImageFilter.h"
  #include "itkRescaleIntensityImageFilter.h"

Then, as usual, a decision should be made about the pixel type that should be used to represent the images. Note that when reading an image, this pixel type is not necessarily the pixel type of the image stored in the file. Instead, it is the type that will be used to store the image as soon as it is read into memory.

    typedef float         InputPixelType;
    typedef unsigned char OutputPixelType;
    const unsigned int Dimension = 2;
  
    typedef otb::Image<InputPixelType,  Dimension> InputImageType;
    typedef otb::Image<OutputPixelType, Dimension> OutputImageType;

We can now instantiate the types of the reader and writer. These two classes are parameterized over the image type.

    typedef otb::ImageFileReader<InputImageType>  ReaderType;
    typedef otb::ImageFileWriter<OutputImageType> WriterType;

Below we instantiate the RescaleIntensityImageFilter class that will linearly scale the image intensities.

    typedef itk::RescaleIntensityImageFilter<
        InputImageType,
        OutputImageType>    FilterType;

A filter object is constructed and the minimum and maximum values of the output are selected using the SetOutputMinimum() and SetOutputMaximum() methods.

    FilterType::Pointer filter = FilterType::New();
    filter->SetOutputMinimum(0);
    filter->SetOutputMaximum(255);

Then, we create the reader and writer and connect the pipeline.

    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();
  
    filter->SetInput(reader->GetOutput());
    writer->SetInput(filter->GetOutput());

The name of the files to be read and written are passed with the SetFileName() method.

    reader->SetFileName(inputFilename);
    writer->SetFileName(outputFilename);

Finally we trigger the execution of the pipeline with the Update() method on the writer. The output image will then be the scaled and cast version of the input image.

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject& err)
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }

6.6 Extracting Regions

The source code for this example can be found in the file
Examples/IO/ImageReadRegionOfInterestWrite.cxx.

This example should arguably be placed in the filtering chapter. However its usefulness for typical IO operations makes it interesting to mention here. The purpose of this example is to read and image, extract a subregion and write this subregion to a file. This is a common task when we want to apply a computationally intensive method to the region of interest of an image.

As usual with OTB IO, we begin by including the appropriate header files.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

The otb::ExtractROI is the filter used to extract a region from an image. Its header is included below.

  #include "otbExtractROI.h"

Image types are defined below.

    typedef unsigned char InputPixelType;
    typedef unsigned char OutputPixelType;
    const unsigned int Dimension = 2;
    typedef otb::Image<InputPixelType,  Dimension> InputImageType;
    typedef otb::Image<OutputPixelType, Dimension> OutputImageType;

The types for the otb::ImageFileReader and otb::ImageFileWriter are instantiated using the image types.

    typedef otb::ImageFileReader<InputImageType>  ReaderType;
    typedef otb::ImageFileWriter<OutputImageType> WriterType;

The ExtractROI type is instantiated using the input and output pixel types. Using the pixel types as template parameters instead of the image types allows restricting the use of this class to otb::Image s which are used with scalar pixel types. See section 6.8.1 for the extraction of ROIs on otb::VectorImage s. A filter object is created with the New() method and assigned to a itk::SmartPointer .

    typedef otb::ExtractROI<InputImageType::PixelType,
        OutputImageType::PixelType> FilterType;
  
    FilterType::Pointer filter = FilterType::New();

The ExtractROI requires a region to be defined by the user. This is done by defining a rectangle with the following methods (the filter assumes that a 2D image is being processed, for N-D region extraction, you can use the itk::RegionOfInterestImageFilter class).

    filter->SetStartX(atoi(argv[3]));
    filter->SetStartY(atoi(argv[4]));
    filter->SetSizeX(atoi(argv[5]));
    filter->SetSizeY(atoi(argv[6]));

Below, we create the reader and writer using the New() method and assigning the result to a SmartPointer.

    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

The name of the file to be read or written is passed with the SetFileName() method.

    reader->SetFileName(inputFilename);
    writer->SetFileName(outputFilename);

Below we connect the reader, filter and writer to form the data processing pipeline.

    filter->SetInput(reader->GetOutput());
    writer->SetInput(filter->GetOutput());

Finally we execute the pipeline by invoking Update() on the writer. The call is placed in a try/catch block in case exceptions are thrown.

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject& err)
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }

6.7 Reading and Writing Vector Images

Images whose pixel type is a Vector, a CovariantVector, an Array, or a Complex are quite common in image processing. One of the uses of these tye of images is the processing of SLC SAR images, which are complex.

6.7.1 Reading and Writing Complex Images

The source code for this example can be found in the file
Examples/IO/ComplexImageReadWrite.cxx.

This example illustrates how to read and write an image of pixel type std::complex. The complex type is defined as an integral part of the C++ language.

We start by including the headers of the complex class, the image, and the reader and writer classes.

  #include <complex>
  #include "otbImage.h"
  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

The image dimension and pixel type must be declared. In this case we use the std::complex<> as the pixel type. Using the dimension and pixel type we proceed to instantiate the image type.

    const unsigned int Dimension = 2;
  
    typedef std::complex<float>              PixelType;
    typedef otb::Image<PixelType, Dimension> ImageType;

The image file reader and writer types are instantiated using the image type. We can then create objects for both of them.

    typedef otb::ImageFileReader<ImageType> ReaderType;
    typedef otb::ImageFileWriter<ImageType> WriterType;
  
    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

Filenames should be provided for both the reader and the writer. In this particular example we take those filenames from the command line arguments.

    reader->SetFileName(argv[1]);
    writer->SetFileName(argv[2]);

Here we simply connect the output of the reader as input to the writer. This simple program could be used for converting complex images from one fileformat to another.

    writer->SetInput(reader->GetOutput());

The execution of this short pipeline is triggered by invoking the Update() method of the writer. This invocation must be placed inside a try/catch block since its execution may result in exceptions being thrown.

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject& err)
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }

For a more interesting use of this code, you may want to add a filter in between the reader and the writer and perform any complex image to complex image operation.

6.8 Reading and Writing Multiband Images

The source code for this example can be found in the file
Examples/IO/MultibandImageReadWrite.cxx.

The otb::Image class with a vector pixel type could be used for representing multispectral images, with one band per vector component, however, this is not a practical way, since the dimensionality of the vector must be known at compile time. OTB offers the otb::VectorImage where the dimensionality of the vector stored for each pixel can be chosen at runtime. This is needed for the image file readers in order to dynamically set the number of bands of an image read from a file.

The OTB Readers and Writers are able to deal with otb::VectorImage s transparently for the user.

The first step for performing reading and writing is to include the following headers.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"

Then, as usual, a decision must be made about the type of pixel used to represent the image processed by the pipeline. The pixel type corresponds to the scalar type stored in the vector components. Therefore, for a multiband Pléiades image we will do:

    typedef unsigned short PixelType;
    const unsigned int Dimension = 2;
    typedef otb::VectorImage<PixelType, Dimension> ImageType;

We can now instantiate the types of the reader and writer. These two classes are parameterized over the image type.

    typedef otb::ImageFileReader<ImageType> ReaderType;
    typedef otb::ImageFileWriter<ImageType> WriterType;

Then, we create one object of each type using the New() method and assigning the result to a itk::SmartPointer .

    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

The name of the file to be read or written is passed with the SetFileName() method.

    reader->SetFileName(inputFilename);
    writer->SetFileName(outputFilename);

We can now connect these readers and writers to filters to create a pipeline. The only thig to take care of is, when executing the program, choosing an output image file format which supports multiband images.

    writer->SetInput(reader->GetOutput());

    try
      {
      writer->Update();
      }
    catch (itk::ExceptionObject& err)
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }

6.8.1 Extracting ROIs

The source code for this example can be found in the file
Examples/IO/ExtractROI.cxx.

This example shows the use of the otb::MultiChannelExtractROI and otb::MultiToMonoChannelExtractROI which allow the extraction of ROIs from multiband images stored into otb::VectorImage s. The first one povides a Vector Image as output, while the second one provides a classical otb::Image with a scalar pixel type. The present example shows how to extract a ROI from a 4-band SPOT 5 image and to produce a first multi-band 3-channel image and a second mono-channel one for the SWIR band.

We start by including the needed header files.

  #include "otbImageFileReader.h"
  #include "otbImageFileWriter.h"
  #include "otbMultiChannelExtractROI.h"
  #include "otbMultiToMonoChannelExtractROI.h"

The program arguments define the image file names as well as the rectangular area to be extracted.

    const char  inputFilename  = argv[1];
    const char  outputFilenameRGB = argv[2];
    const char  outputFilenameMIR = argv[3];
  
    unsigned int startX((unsigned int) ::atoi(argv[4]));
    unsigned int startY((unsigned int) ::atoi(argv[5]));
    unsigned int sizeX((unsigned int) ::atoi(argv[6]));
    unsigned int sizeY((unsigned int) ::atoi(argv[7]));

As usual, we define the input and output pixel types.

    typedef   unsigned char InputPixelType;
    typedef   unsigned char OutputPixelType;

First of all, we extract the multiband part by using the otb::MultiChannelExtractROI class, which is templated over the input and output pixel types. This class in not templated over the images types in order to force these images to be of otb::VectorImage type.

    typedef otb::MultiChannelExtractROI<InputPixelType,
        OutputPixelType>  ExtractROIFilterType;

We create the extractor filter by using the New method of the class and we set its parameters.

    ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
  
    extractROIFilter->SetStartX(startX);
    extractROIFilter->SetStartY(startY);
    extractROIFilter->SetSizeX(sizeX);
    extractROIFilter->SetSizeY(sizeY);

We must tell the filter which are the channels to be used. When selecting contiguous bands, we can use the SetFirstChannel and the SetLastChannel. Otherwise, we select individual channels by using the SetChannel method.

    extractROIFilter->SetFirstChannel(1);
    extractROIFilter->SetLastChannel(3);

We will use the OTB readers and writers for file access.

    typedef otb::ImageFileReader<ExtractROIFilterType::InputImageType> ReaderType;
    typedef otb::ImageFileWriter<ExtractROIFilterType::InputImageType> WriterType;
  
    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writer = WriterType::New();

Since the number of bands of the input image is dynamically set at runtime, the UpdateOutputInformation method of the reader must be called before using the extractor filter.

    reader->SetFileName(inputFilename);
    reader->UpdateOutputInformation();
    writer->SetFileName(outputFilenameRGB);

We can then build the pipeline as usual.

    extractROIFilter->SetInput(reader->GetOutput());
  
    writer->SetInput(extractROIFilter->GetOutput());

And execute the pipeline by calling the Update method of the writer.

    writer->Update();

The usage of the otb::MultiToMonoChannelExtractROI is similar to the one of the otb::MultiChannelExtractROI described above.

The goal now is to extract an ROI from a multi-band image and generate a mono-channel image as output.

We could use the otb::MultiChannelExtractROI and select a single channel, but using the otb::MultiToMonoChannelExtractROI we generate a otb::Image instead of an otb::VectorImage . This is useful from a computing and memory usage point of view. This class is also templated over the pixel types.

    typedef otb::MultiToMonoChannelExtractROI<InputPixelType,
        OutputPixelType>
    ExtractROIMonoFilterType;

For this filter, only one output channel has to be selected.

    extractROIMonoFilter->SetChannel(4);


PIC

Figure 6.4: Quicklook of the original SPOT 5 image.



PIC PIC

Figure 6.5: Result of the extraction. Left: 3-channel image. Right: mono-band image.


Figure 6.5 illustrates the result of the application of both extraction filters on the image presented in figure 6.4.

6.9 Reading Image Series

The source code for this example can be found in the file
Examples/IO/ImageSeriesIOExample.cxx.

This example shows how to read a list of images and concatenate them into a vector image. We will write a program which is able to perform this operation taking advantage of the streaming functionnalities of the processing pipeline. We will assume that all the input images have the same size and a single band.

The following header files will be needed:

  #include "otbImage.h"
  #include "otbVectorImage.h"
  #include "otbImageFileReader.h"
  #include "otbImageList.h"
  #include "otbImageListToVectorImageFilter.h"
  #include "otbImageFileWriter.h"

We will start by defining the types for the input images and the associated readers.

    typedef unsigned short int PixelType;
    const unsigned int Dimension = 2;
  
    typedef otb::Image<PixelType, Dimension> InputImageType;
  
    typedef otb::ImageFileReader<InputImageType> ImageReaderType;

We will use a list of image file readers in order to open all the input images at once. For this, we use the otb::ObjectList object and we template it over the type of the readers.

    typedef otb::ObjectList<ImageReaderType> ReaderListType;
  
    ReaderListType::Pointer readerList = ReaderListType::New();

We will also build a list of input images in order to store the smart pointers obtained at the output of each reader. This allows us to build a pipeline without really reading the images and using lots of RAM. The otb::ImageList object will be used.

    typedef otb::ImageList<InputImageType> ImageListType;
  
    ImageListType::Pointer imageList = ImageListType::New();

We can now loop over the input image list in order to populate the reader list and the input image list.

    for (unsigned int i = 0; i < NbImages; ++i)
      {
  
      ImageReaderType::Pointer imageReader = ImageReaderType::New();
  
      imageReader->SetFileName(argv[i + 2]);
  
      std::cout << "Adding image " << argv[i + 2] << std::endl;
  
      imageReader->UpdateOutputInformation();
  
      imageList->PushBack(imageReader->GetOutput());
  
      readerList->PushBack(imageReader);
  
      }

All the input images will be concatenated into a single output vector image. For this matter, we will use the otb::ImageListToVectorImageFilter which is templated over the input image list type and the output vector image type.

    typedef otb::VectorImage<PixelType, Dimension> VectorImageType;
  
    typedef otb::ImageListToVectorImageFilter<ImageListType, VectorImageType>
    ImageListToVectorImageFilterType;
  
    ImageListToVectorImageFilterType::Pointer iL2VI =
      ImageListToVectorImageFilterType::New();

We plug the image list as input of the filter and use a otb::ImageFileWriter to write the result image to a file, so that the streaming capabilities of all the readers and the filter are used.

    iL2VI->SetInput(imageList);
  
    typedef otb::ImageFileWriter<VectorImageType> ImageWriterType;
  
    ImageWriterType::Pointer imageWriter = ImageWriterType::New();
  
    imageWriter->SetFileName(argv[1]);

We can tune the size of the image tiles, so that the total memory footprint of the pipeline is constant for any execution of the program.

    unsigned long memoryConsumptionInMB = 10;
  
    std::cout << "Memory consumption: " << memoryConsumptionInMB << std::endl;
  
    imageWriter->SetAutomaticTiledStreaming(memoryConsumptionInMB);
  
    imageWriter->SetInput(iL2VI->GetOutput());
  
    imageWriter->Update();