Compute Histogram From Grayscale Image#
Synopsis#
Compute a histogram from a grayscale image
Results#
Output:
Frequency = [ 0,
8593,
17734,
11515,
5974,
2225,
2400,
3422,
3531,
3283,
2125,
2628,
1954,
152,
0,
0 ]
Code#
C++#
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageToHistogramFilter.h"
#include "itkImageRandomIteratorWithIndex.h"
int
main(int argc, char * argv[])
{
if (argc != 3)
{
std::cerr << argv[0] << "InputFileName NumberOfBins" << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimension = 2;
using PixelType = unsigned char;
using ImageType = itk::Image<PixelType, Dimension>;
constexpr unsigned int MeasurementVectorSize = 1; // Grayscale
const auto binsPerDimension = static_cast<unsigned int>(std::stoi(argv[2]));
ImageType::Pointer image = itk::ReadImage<ImageType>(argv[1]);
using ImageToHistogramFilterType = itk::Statistics::ImageToHistogramFilter<ImageType>;
ImageToHistogramFilterType::HistogramType::MeasurementVectorType lowerBound(binsPerDimension);
lowerBound.Fill(0);
ImageToHistogramFilterType::HistogramType::MeasurementVectorType upperBound(binsPerDimension);
upperBound.Fill(255);
ImageToHistogramFilterType::HistogramType::SizeType size(MeasurementVectorSize);
size.Fill(binsPerDimension);
auto imageToHistogramFilter = ImageToHistogramFilterType::New();
imageToHistogramFilter->SetInput(image);
imageToHistogramFilter->SetHistogramBinMinimum(lowerBound);
imageToHistogramFilter->SetHistogramBinMaximum(upperBound);
imageToHistogramFilter->SetHistogramSize(size);
try
{
imageToHistogramFilter->Update();
}
catch (const itk::ExceptionObject & error)
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
ImageToHistogramFilterType::HistogramType * histogram = imageToHistogramFilter->GetOutput();
std::cout << "Frequency = [ ";
for (unsigned int i = 0; i < histogram->GetSize()[0]; ++i)
{
std::cout << histogram->GetFrequency(i);
if (i != histogram->GetSize()[0] - 1)
{
std::cout << "," << std::endl;
}
}
std::cout << " ]" << std::endl;
return EXIT_SUCCESS;
}
Classes demonstrated#
-
template<typename TImage>
class ImageToHistogramFilter : public itk::ImageSink<TImage> This class generates a histogram from an image.
The concept of Histogram in ITK is quite generic. It has been designed to manage multiple components data. This class facilitates the computation of an histogram from an image.
This filter is automatically multi-threaded. When AutoMinimumMaximum is off and the NumberOfStreamDivisions is set to more than one, then this filter streams its input in a series of requested regions. A histogram is computed for each streamed and threaded region then merged.
Subclassed by itk::Statistics::MaskedImageToHistogramFilter< TImage, TMaskImage >