How to read a palette image as a scalar image with ITK?

389 views Asked by At

When I'm reading an image, the itk::ImageIOBase, as implemented here, tels me that the image has a RGB pixel type. The format of the image is TIFF, but can be png or gif as well.

itk::ImageIOBase::Pointer imageIO =
    itk::ImageIOFactory::CreateImageIO(
        fileName, itk::ImageIOFactory::ReadMode);

How to know, through ITK, whether the image is actually a palette image, i.e. scalar image along with a color palette, and read the image as a scalar image + palette ? I need to retrive the index, as stored in the file as well as the color palette used in the file.

For now, my only solution is to use freeImagePlus to identify and read this type of image. I haven't found any function in the class ImageIOBase that could relate to that.

Any help would be appreciated, I haven't found much information on this on the internet !

2

There are 2 answers

0
beesleep On BEST ANSWER

To answer my own question, the feature is now implemented in ITK, in the master branch, and offer the support of palette for png tif and bmp images

Here a working example, for those who are interested :

#include "itkImage.h"
#include <iostream>
#include <string>

#include "itkPNGImageIOFactory.h"
#include "itkImageFileReader.h"
#include "itkPNGImageIO.h"

int main()
{
    std::string filename("testImage_palette.png");

    auto io = itk::PNGImageIO::New();

    // tell the reader not to expand palette to RGB, if possible
    io->SetExpandRGBPalette(false);

    typedef unsigned short PixelType;
    typedef itk::Image<PixelType, 2> imageType;
    typedef itk::ImageFileReader<imageType> ReaderType;
    ReaderType::Pointer reader = ReaderType::New();

    reader->SetFileName(filename);
    reader->SetImageIO(io);

    try {
        reader->Update();
    } catch (itk::ExceptionObject &err) {
        std::cerr << "ExceptionObject caught !" << std::endl;
        std::cerr << err << std::endl;
        return EXIT_FAILURE;
    }

    std::cout<< std::endl << "IsReadAsScalarPlusPalette:" <<io->GetIsReadAsScalarPlusPalette() << std::endl;

    if (io->GetIsReadAsScalarPlusPalette()) {
        auto palette(io->GetColorPalette());
        std::cout<< "palette (size="<< palette.size()<<"):"<< std::endl;
        auto m(std::min(static_cast<size_t>(10),palette.size()));
        for (size_t i=0; i<m;++i) {
            std::cout << "["<<palette[i]<< "]"<< std::endl;
        }
        if (m< palette.size())
            std::cout<< "[...]"<< std::endl;
    }
    // if io->GetIsReadAsScalarPlusPalette() im will be the index of the palette image
    auto im(reader->GetOutput()); 
}
3
Dženan On

Have you tried to read it as grayscale image? What result does this reader produce without explicitly setting an IO on it?

typedef itk::Image<unsigned char, 2> uc2Type;
typedef itk::ImageFileReader<uc2Type> ReaderType;

Unless you need the color pallette for something, this could be enough.