Generate Random Image#

Synopsis#

This example produces an image with random pixel values.

Results#

Output image

Output image#

Code#

C++#

#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkImageFileWriter.h"

int
main(int argc, char * argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage:" << std::endl;
    std::cerr << argv[0] << " <OutputFileName>" << std::endl;
    return EXIT_FAILURE;
  }
  const char * outputFileName = argv[1];

  constexpr unsigned int Dimension = 2;
  using PixelType = unsigned char;

  using ImageType = itk::Image<PixelType, Dimension>;

  ImageType::SizeType size;
  size.Fill(10);

  using RandomImageSourceType = itk::RandomImageSource<ImageType>;

  auto randomImageSource = RandomImageSourceType::New();
  randomImageSource->SetNumberOfWorkUnits(1); // to produce reproducible results
  randomImageSource->SetSize(size);

  try
  {
    itk::WriteImage(randomImageSource->GetOutput(), outputFileName);
  }
  catch (const itk::ExceptionObject & error)
  {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Classes demonstrated#

template<typename TOutputImage>
class RandomImageSource : public itk::ImageSource<TOutputImage>

Generate an n-dimensional image of random pixel values.

RandomImageSource generates an image of random pixel values. This filter uses an inline random number generator since the library drand48, although thread-safe, is very slow in a threaded environment. The output image may be of any dimension. NOTE: To produce deterministic results, set the number of threads to 1.

ITK Sphinx Examples:

See itk::RandomImageSource for additional documentation.