Change pixels in 2D/3D images


Similar to an older post. One can modify 2D/3D images in order to change specific pixels /voxels. This became useful recently while trying to remove a tissue from a segmented image. For something more complicated you may want to use Slicer, but for simple cases like this a python script enough. Appended you can also find the corresponding C++ code. Keep in mind that python handles all supported PixelTypes automatically while for the C++ one needs to update the PixelType typedef and the dimension variable.

#!/usr/bin/env python
import itk
import sys

if len(sys.argv) != 5:
    print("Usage: " + sys.argv[0] + " <inputImage> <inputPixel> <outputPixel> <outputImage>")
    sys.exit(1)

inputImage = sys.argv[1]
inputPixel = int(sys.argv[2])
outputPixel = int(sys.argv[3])
outputImage = sys.argv[4]


image = itk.imread(inputImage)
imfilter = itk.ChangeLabelImageFilter.New(image)
imfilter.SetChange(inputPixel,outputPixel)
itk.imwrite(imfilter.GetOutput(), outputImage)

Also in C++

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkChangeLabelImageFilter.h"

int main(int argc, char** argv)
{
    if (argc != 5)
    {
        std::cerr << "Usage: " << std::endl;
        std::cerr << argv[0];
        std::cerr << "<InputFileName> <InputPixel> <OutputPixel> <OutputFileName>";
        std::cerr << std::endl;
        return 1;
    }

    const  int Dimension = 3;
    //const  int Dimension = 2;

    using PixelType = unsigned char;
    using ImageType = itk::Image<PixelType, Dimension>;
    PixelType InputPixel = std::atoi(argv[2]);
    PixelType OutputPixel = std::atoi(argv[3]);

    using ReaderType = itk::ImageFileReader<ImageType>;
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(argv[1]);

    using ChangeLabelFilterType = itk::ChangeLabelImageFilter<ImageType,ImageType>;
    ChangeLabelFilterType::Pointer cfilter = ChangeLabelFilterType::New();
    cfilter->SetInput(reader->GetOutput());
    cfilter->SetChange(InputPixel,OutputPixel);

    using WriterType = itk::ImageFileWriter<ImageType>;
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName(argv[4]);
    writer->SetInput(cfilter->GetOutput());

    try
    {
        writer->Update();
    }
    catch (itk::ExceptionObject & error)
    {
        std::cerr << "Error: " << error << std::endl;
        return 1;
    }

    return 0;
}
itk