Make Part of an Image Transparent#

Synopsis#

Demonstrates how to assign transparency to pixels in an image, then writing the result to a tif file for inspection and verification.

Results#

test.tif

Output Image.#

Code#

C++#

#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkTIFFImageIO.h"
#include "itkRGBAPixel.h"

int
main(int argc, char * argv[])
{
  std::string outputFilename;
  if (argc > 1)
  {
    outputFilename = argv[1];
  }
  else
  {
    outputFilename = "test.tif";
  }

  using PixelType = itk::RGBAPixel<unsigned char>;
  using ImageType = itk::Image<PixelType, 2>;

  ImageType::RegionType region;
  ImageType::IndexType  start;
  start[0] = 0;
  start[1] = 0;

  ImageType::SizeType size;
  size[0] = 200;
  size[1] = 300;

  region.SetSize(size);
  region.SetIndex(start);

  auto image = ImageType::New();
  image->SetRegions(region);
  image->Allocate();

  itk::ImageRegionIterator<ImageType> imageIterator(image, region);

  while (!imageIterator.IsAtEnd())
  {
    ImageType::PixelType pixel = imageIterator.Get();

    if (imageIterator.GetIndex()[0] > 100)
    {
      pixel.SetRed(0);
      pixel.SetGreen(255);
      pixel.SetBlue(0);
      // pixel.SetAlpha(255); // invisible
      pixel.SetAlpha(122);
    }
    else
    {
      pixel.SetRed(255);
      pixel.SetGreen(0);
      pixel.SetBlue(0);
      pixel.SetAlpha(static_cast<unsigned char>(0.5 * 255));
    }
    imageIterator.Set(pixel);

    ++imageIterator;
  }

  using WriterType = itk::ImageFileWriter<ImageType>;
  using TIFFIOType = itk::TIFFImageIO;
  auto writer = WriterType::New();
  auto tiffIO = TIFFIOType::New();
  tiffIO->SetPixelType(itk::IOPixelEnum::RGBA);
  writer->SetFileName(outputFilename);
  writer->SetInput(image);
  writer->SetImageIO(tiffIO);
  writer->Update();

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TComponent = unsigned short>
class RGBAPixel : public itk::FixedArray<TComponent, 4>

Represent Red, Green, Blue and Alpha components for color images.

This class is templated over the representation used for each component.

The following syntax for assigning an index is allowed/suggested:

RGBAPixel<float> pixel; pixel = 1.0f, 0.0f, .5f, .8;
RGBAPixel<char> pixelArray[2];
pixelArray[0] = 255, 255, 255, 230;
pixelArray[1] = 255, 255, 244, 255;

Since RGBAPixel is a subclass of Array, you can access its components as: pixel[0], pixel[1], pixel[2], pixel[3]

ITK Sphinx Examples:

See itk::RGBAPixel for additional documentation.