Convert RGB Image to Grayscale Image#
Synopsis#
Convert a RGB Image to its luminance image (grayscale one).
Results#
Code#
Python#
#!/usr/bin/env python
import itk
import argparse
parser = argparse.ArgumentParser(description="Compute RBG Image To Grayscale Image.")
parser.add_argument("input_image")
parser.add_argument("output_image")
args = parser.parse_args()
Dimension = 2
ComponentType = itk.UC
InputPixelType = itk.RGBPixel[ComponentType]
InputImageType = itk.Image[InputPixelType, Dimension]
OutputPixelType = itk.UC
OutputImageType = itk.Image[OutputPixelType, Dimension]
reader = itk.ImageFileReader[InputImageType].New()
reader.SetFileName(args.input_image)
rgbFilter = itk.RGBToLuminanceImageFilter.New(reader)
writer = itk.ImageFileWriter[OutputImageType].New()
writer.SetFileName(args.output_image)
writer.SetInput(rgbFilter.GetOutput())
writer.Update()
C++#
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRGBToLuminanceImageFilter.h"
int
main(int argc, char * argv[])
{
if (argc != 3)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0];
std::cerr << "<InputFileName> <OutputFileName>";
std::cerr << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimension = 2;
using ComponentType = unsigned char;
using InputPixelType = itk::RGBPixel<ComponentType>;
using InputImageType = itk::Image<InputPixelType, Dimension>;
const auto input = itk::ReadImage<InputImageType>(argv[1]);
using OutputPixelType = unsigned char;
using OutputImageType = itk::Image<OutputPixelType, Dimension>;
using FilterType = itk::RGBToLuminanceImageFilter<InputImageType, OutputImageType>;
auto filter = FilterType::New();
filter->SetInput(input);
try
{
itk::WriteImage(filter->GetOutput(), argv[2]);
}
catch (const itk::ExceptionObject & error)
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Classes demonstrated#
-
template<typename TInputImage, typename TOutputImage>
class RGBToLuminanceImageFilter : public itk::UnaryGeneratorImageFilter<TInputImage, TOutputImage> Converts an RGB image into a grayscale image.
This filters converts an RGB image into a Luminance on by computing pixel-wise a linear combination on the Red, Green and Blue channels. The pixel type of the input image must have a GetLuminance() method. This is the case of the itk::RGBPixel class.