Create An Image Of Vectors

Synopsis

This example illustrates how to instantiate and use an itk::Image whose pixels are of itk::Vector type.

Results

C++

[1.345, 6.841, 3.295]

Python

itkVectorF3 ([1.345, 6.841, 3.295])

Code

C++

#include "itkVector.h"
#include "itkImage.h"

int
main(int, char *[])
{
  using PixelType = itk::Vector<float, 3>;
  using ImageType = itk::Image<PixelType, 3>;

  // Then the image object can be created
  ImageType::Pointer image = ImageType::New();

  // The image region should be initialized
  const ImageType::IndexType start = { { 0, 0, 0 } };      // First index at {X,Y,Z}
  const ImageType::SizeType  size = { { 200, 200, 200 } }; // Size of {X,Y,Z}

  ImageType::RegionType region;
  region.SetSize(size);
  region.SetIndex(start);

  // Pixel data is allocated
  image->SetRegions(region);
  image->Allocate();

  // The image buffer is initialized to a particular value
  ImageType::PixelType initialValue;

  // A vector can initialize all its components to the
  // same value by using the Fill() method.
  initialValue.Fill(0.0);

  // Now the image buffer can be initialized with this
  // vector value.
  image->FillBuffer(initialValue);

  const ImageType::IndexType pixelIndex = { { 27, 29, 37 } }; // Position {X,Y,Z}


  ImageType::PixelType pixelValue;
  pixelValue[0] = 1.345; // x component
  pixelValue[1] = 6.841; // y component
  pixelValue[2] = 3.295; // x component

  image->SetPixel(pixelIndex, pixelValue);

  ImageType::PixelType value = image->GetPixel(pixelIndex);

  std::cout << value << std::endl;


  return EXIT_SUCCESS;
}

Python

#!/usr/bin/env python

Dimension = 3
ComponentType = itk.ctype('float')
PixelType = itk.Vector[ComponentType, Dimension]
ImageType = itk.Image[PixelType, Dimension]

image = ImageType.New()

start = itk.Index[Dimension]()
start[0] = 0
start[1] = 0
start[2] = 0

size = itk.Size[Dimension]()
size[0] = 200
size[1] = 200
size[2] = 200

region = itk.ImageRegion[Dimension]()
region.SetSize(size)
region.SetIndex(start)

image.SetRegions(region)
image.Allocate()

vectorValue = PixelType()
vectorValue[0] = 0
vectorValue[1] = 0
vectorValue[2] = 0
image.FillBuffer(vectorValue)

pixelIndex = itk.Index[Dimension]()
pixelIndex[0] = 27
pixelIndex[1] = 29
pixelIndex[2] = 37

pixelValue = PixelType()
pixelValue[0] = 1.345
pixelValue[1] = 6.841
pixelValue[2] = 3.295

image.SetPixel(pixelIndex, pixelValue)

value = image.GetPixel(pixelIndex)

print(value)

Classes demonstrated