Getting Started Coding/ITK/Image

From FarsightWiki
(Difference between revisions)
Jump to: navigation, search
 
(20 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
Return to:
 +
 +
[[Getting_Started_Coding| Getting Started]]
 +
 
This example demonstrates how to read and write an itkImage to a file.  
 
This example demonstrates how to read and write an itkImage to a file.  
  
 
==ImageFileReaderWriter.cxx==
 
==ImageFileReaderWriter.cxx==
<syntaxhighlight lang="cpp">
+
<syntaxhighlight lang="cpp">  
#include "itkImage.h"
+
#include <iostream>                         // The iostream library is an object-oriented library that provides input and output functionality using streams.
#include "itkImageFileWriter.h"
+
#include "itkImageFileReader.h"
+
#include <iostream>
+
 
#include <string>
 
#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[])                                //The parameters argc, argument count, and argv, argument vector,[1] respectively
 
{   //give the number and value of the program's command-line arguments. The names of
 
  //argc and argv may be any valid identifier in C, but it is common convention to
 
  //use these names. In C++, the names are to be taken literally
 
  
                                                                 
 
  std::string outputFilename;                                   // "standard string" allows outputFilename to take a "string" as an argument
 
  //easier to pass standard string than passing around char arrays
 
  if(argc > 2)                   // if there are more than 1 arguments
 
    {
 
    outputFilename = argv[1];                                   // then the very first argument is assigned to the standard string "outputFilename"
 
    }
 
  else
 
    {   
 
std::cerr << "Usage: " << std::endl;              //Try and Catch Method. Error Message will display required input if missing
 
std::cerr << argv[0] << " [inputImageFile] [outputfilename]" << std::endl;
 
return EXIT_FAILURE;
 
    }
 
  
  
  //The purpose of "typedef" is to assign alternative names to existing types
+
int main(int argc, char *argv[])                            // Excecution of the program starts with the given inputs
  typedef unsigned char    PixelType; // Pixeltype has been assigned char (0 - 255)
+
            // 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
 +
}
  
  //variables declared with ‘const’ added become constants and cannot be altered by the program.
 
  const    unsigned int    Dimension = 2; //Dimension has been declared as a constant with a value of 2
 
// unsigned defines the range possible for the int.
 
 
 
  //everything used in ITK has be to defined and declared, since ITK is templated
 
  typedef itk::Image< PixelType, Dimension >  ImageType; //ImageType consists of the defined Pixeltype and Dimension
 
  typedef itk::ImageFileReader<ImageType> ReaderType;
 
ReaderType::Pointer reader = ReaderType::New();
 
reader->SetFileName(argv[1]);
 
  
try
+
        //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();
+
reader->Update();           // this guarded section will be executed
 
}
 
}
catch(itk::ExceptionObject & e)
+
catch(itk::ExceptionObject & err)   // handles exception if any exists
 
{
 
{
std::cerr << e.GetDescription()<<std::endl;
+
std::cerr << err.GetDescription()<<std::endl; // outputs the description of the error
 
return EXIT_FAILURE;
 
return EXIT_FAILURE;
 
}
 
}
ImageType::Pointer image = reader->GetOutput();
+
        // if no exceptions are caught, execution of the program continues
typedef  itk::ImageFileWriter< ImageType > WriterType;
+
  WriterType::Pointer writer = WriterType::New();
+
       
  writer->SetFileName(argv[2]);
+
        ImageType::Pointer image = reader->GetOutput(); // similar to the example above
  writer->SetInput(reader->GetOutput());
+
                                                        // access ImageType
  writer->Update();
+
                                                        // creates new pointer, image
+
                                                        // pointer's input = reader's output
  return EXIT_SUCCESS;
+
                                                        // 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; 
  
== ImageFileReaderWriter.exe ==
+
  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;
 +
}
 +
 
 +
</syntaxhighlight>
 +
 +
 
 +
 
 +
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})

Latest revision as of 18:16, 30 September 2011

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