Getting Started Coding/ITK/Image

From FarsightWiki
Jump to: navigation, search

Return to:

Getting Started

This example demonstrates how to read and write an itkImage to a file.

ImageFileReaderWriter.cxx

 
#include <iostream>                         // The iostream library is an object-oriented library that provides input and output functionality using streams.
#include <string>
#include "itkImage.h"                       // Templated n-dimensional image class. 		
#include "itkImageFileReader.h"             // Reads an image from a single file.
#include "itkImageFileWriter.h"             // Writes an image to a single file. 
#include "itkBinaryThresholdImageFilter.h"  // Binarize an input image by thresholding.
#include "itkBinaryImageToLabelMapFilter.h" // Label the connected components in a binary image and produce a collection of label objects.
#include "itkLabelMapToLabelImageFilter.h"  
#include "itkLabelStatisticsImageFilter.h"
 
 
 
 
int main(int argc, char *argv[])                             // Excecution of the program starts with the given inputs
						             // argc = argument count: the number of the program's command-line arguments
						             // argv = argument vector: the value of the program's command-line arguments
{				
	std::string outputFilename;
							     // argv[0] = name of the program  --> counts as 1 argument
	if(argc == 5)					     // if there are more exactly 5 input arguments, so
						             // argv[0] + 4 additional input arguments which must be specified									
		{
		outputFilename = argv[1];	             // then the very first argument is assigned to the standard string "outputFilename"
		}
	  else						     // with any other count of input arguments, an error message will appear requiring the following inputs:
		{    
			std::cerr << "Usage: " << std::endl; // ouputs an error message 
			std::cerr << argv[0] << "   requires the following inputs:   [inputImageFile] [outputfilename] [lowerThreshold] [upperThreshold]" << std::endl;
			return EXIT_FAILURE;	             // signifies that the application as failed
		}
 
 
        //Pre-define the first 2 input arguments
	typedef unsigned char     PixelType; // define type used to represent pixels 
	const     unsigned int    Dimension = 2; // assgin a constant number to the dimensionality of the image
 
	// Start Linkage to ITK
	// ITK is templated and can be accessed by given it a name with its specification
	typedef itk::Image< PixelType, Dimension >  ImageType;  // "ImageType" is defined as an Image with  
	//     (----^----) (---------^----------)  (----^----)	// 2 Dimension and an unsigned number of pixels
	//          |                |                  |   
	// access this template      |			|
	//			     |			|
	//		       Specification	        |
	//					        |
	//					    New Name
 
 
        typedef itk::ImageFileReader<ImageType> ReaderType; // ReaderType is defined and can be accessed multiple times w/o a repeated typedef
 
	ReaderType::Pointer reader = ReaderType::New(); //
        //	(----^---) (------^------)   (-------^-------)
        //           |		  |                  |
        //	 access this      |                  |
        //           |            |                  |
        //           |       new pointer,            |
        //	     |______ pointed at              |
        //                                           |
        //                   filling info with_______|
        //	                   		     |
        //                               reserves/allocates new 
        //				   memory for "reader"
 
	reader->SetFileName(argv[1]); //Sets File name of "reader" to the first argument specified ("Picture.jpg")
 
        // TRY-CATCH Exception Handling
 
		try 
		{
			reader->Update();           // this guarded section will be executed
		}
		catch(itk::ExceptionObject & err)   // handles exception if any exists 
		{
			std::cerr << err.GetDescription()<<std::endl;  // outputs the description of the error 
			return EXIT_FAILURE;
		}
        // if no exceptions are caught, execution of the program continues
 
 
        ImageType::Pointer image = reader->GetOutput(); // similar to the example above
                                                        // access ImageType
                                                        // creates new pointer, image
                                                        // pointer's input = reader's output
                                                        // Image gets imported as "image"
 
 
        //Pre-define the last 2 input arguments         // threshold is determined by the intensity of a pixel value bordering the background and an object 
	int lowerThreshold = 25;
	int upperThreshold = 255;                       
	if (argc > 3)
	{                                               // atoi converts a string to integer safely. It prevents the string to be displayed in its HEX format. 
		lowerThreshold = atoi(argv[3]);         // the third argument is assigned to lowerThreshold
	}
	if (argc > 4)
	{
		upperThreshold =atoi(argv[4]);          // the fourth argument is assigned to lowerThreshold
	}
	}
 
        // BinaryThresholdImageFilter will convert a grayscale image to a binary image. 
	typedef itk::BinaryThresholdImageFilter <ImageType,ImageType> BinaryThresholdImageFilterType;
 
	BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New();
 
	thresholdFilter ->SetInput (reader ->GetOutput());
	thresholdFilter ->SetLowerThreshold(lowerThreshold);
	thresholdFilter ->SetUpperThreshold(upperThreshold);
	thresholdFilter ->SetInsideValue(255);
	thresholdFilter ->SetOutsideValue(0);
 
        // writes the new binary image to a file. 
	typedef  itk::ImageFileWriter< ImageType  > WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName(argv[2]);
	writer->SetInput(reader->GetOutput());
 
        writer->SetInput(thresholdFilter->GetOutput());
 
        // TRY-CATCH Exception Handling
	  try 
	  {
		  writer ->Update();                      // updates writer 
	  }
	  catch(itk::ExceptionObject &err)                // checks if there are any exceptions
	  { 
		  std::cerr << "ExceptionObject caught!" <<std::endl;
		  std::cerr << err <<std::endl;
		  return EXIT_FAILURE;
	  }
 
 
 
	//BinaryImageToLabelMapFilter: 
	//    Labels the objects in a binary image. Each distinct object is assigned a unique label. 
	//    The final object labels start with 1 and are consecutive. Objects that are reached earlier by a raster order scan have a lower label.
	 typedef itk::BinaryImageToLabelMapFilter<ImageType> BinaryImageToLabelMapFilterType;
	 BinaryImageToLabelMapFilterType::Pointer binaryImageToLabelMapFilter = BinaryImageToLabelMapFilterType::New();
         binaryImageToLabelMapFilter->SetInput(thresholdFilter->GetOutput());
	 binaryImageToLabelMapFilter->Update();
 
	 typedef itk::LabelMapToLabelImageFilter<BinaryImageToLabelMapFilterType::OutputImageType, ImageType> LabelMapToLabelImageFilterType;
	 LabelMapToLabelImageFilterType::Pointer labelMapToLabelImageFilter = LabelMapToLabelImageFilterType::New();
	 labelMapToLabelImageFilter->SetInput(binaryImageToLabelMapFilter->GetOutput());
	 labelMapToLabelImageFilter->Update();
 
	 typedef itk::LabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsImageFilterType;
         LabelStatisticsImageFilterType::Pointer labelStatisticsImageFilter = LabelStatisticsImageFilterType::New();
         labelStatisticsImageFilter->SetLabelInput( labelMapToLabelImageFilter->GetOutput() );
         labelStatisticsImageFilter->SetInput(image);
         labelStatisticsImageFilter->Update();
 
 
	// Display of the Program
        // Display the number of labels in the image. 
	  std::cout << "Number of labels: " << labelStatisticsImageFilter->GetNumberOfLabels() << std::endl;
	  std::cout << std::endl;  
 
	  typedef LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType;
          typedef LabelStatisticsImageFilterType::LabelPixelType                LabelPixelType;
 
        // iterates through the images and calculates the desired statistics
	for(ValidLabelValuesType::const_iterator vIt=labelStatisticsImageFilter->GetValidLabelValues().begin();
		vIt != labelStatisticsImageFilter->GetValidLabelValues().end();
		++vIt)
              {
	        if ( labelStatisticsImageFilter->HasLabel(*vIt) )
		  {
		  LabelPixelType labelValue = *vIt;
		  std::cout << "Min Intensity: " << labelStatisticsImageFilter->GetMinimum( labelValue ) << std::endl;
		  std::cout << "Max Intensity: " << labelStatisticsImageFilter->GetMaximum( labelValue ) << std::endl;
		  std::cout << "median: " << labelStatisticsImageFilter->GetMedian( labelValue ) << std::endl;
		  std::cout << "mean: " << labelStatisticsImageFilter->GetMean( labelValue ) << std::endl;
		  std::cout << "sigma: " << labelStatisticsImageFilter->GetSigma( labelValue ) << std::endl;
		  std::cout << "variance: " << labelStatisticsImageFilter->GetVariance( labelValue ) << std::endl;
		  std::cout << "Sum: " << labelStatisticsImageFilter->GetSum( labelValue ) << std::endl;
		  std::cout << "Area: " << labelStatisticsImageFilter->GetCount( labelValue ) << std::endl;
		  std::cout << "Region: " << labelStatisticsImageFilter->GetRegion( labelValue ) << std::endl;
 
		  std::cout << std::endl << std::endl;
 
		  }
		}
		  return EXIT_SUCCESS;
}


Once ImageFileReaderWriter.exe has been build, run executable through Microsoft Visual Studio Command Prompt.

CMake List

cmake_minimum_required(VERSION 2.6)

project(ImageReaderWriter)

find_package(ITK REQUIRED)
include(${ITK_USE_FILE})

add_executable(ImageReaderWriter ImageReaderWriter.cxx)
target_link_libraries(ImageReaderWriter ${ITK_LIBRARIES})
Personal tools