how to apply kernel in ConvolutionImageFilter

Hello,

I want to apply an image (kernel) to an input Image, but I am not sure how can I apply that correctly.
I have attached the sample of my code here:

#include “itkImageFileReader.h”
#include “itkImageFileWriter.h”
#include “itkConvolutionImageFilter.h”

int main(int argc, char *argv)
{
if (argc < 3)
{
std::cerr << “Usage: ” << std::endl;
return EXIT_FAILURE;
}
const char * inputImage = argv[1];
const char * kernelImage = argv[2];
const char * outputImage = argv[3];

constexpr unsigned int Dimension = 3;
using InputPixelType = double;
using OutputPixelType = double;
using KernelPixelType = double;
using InputImageType = itk::Image< InputPixelType, Dimension >;
using OutputImageType = itk::Image< OutputPixelType, Dimension >;
using KernelImageType = itk::Image< KernelPixelType, Dimension >;

using ReaderType = itk::ImageFileReader< InputImageType >;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputImage);

using ReaderKernelType = itk::ImageFileReader< KernelImageType >;
ReaderKernelType::Pointer kernel = ReaderKernelType::New();
kernel->SetFileName(kernelImage);

using ImageType = itk::Image<double, 3>;
ImageType::Pointer ker = ImageType::New();

// Convolve image with kernel.
typedef itk::ConvolutionImageFilter FilterType;
FilterType::Pointer convolutionFilter = FilterType::New();
convolutionFilter->SetInput(reader->GetOutput());
convolutionFilter->SetKernelImage(kernel);

using WriterType = itk::ImageFileWriter< OutputImageType >;
WriterType::Pointer writer = WriterType::New();
//writer->SetInput(rescaler->GetOutput());
writer->SetFileName(outputImage);

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

return EXIT_SUCCESS;
}

Thanks in advance,
Eleni

Hi Eleni,

Following the template requirements of itk::ConvolutionImageFilter, add its template parameters:

using FilterType = itk::ConvolutionImageFilter< InputImageType, KernelImageType, OutputImageType >;

and set the input to the writer to be the output of the convolution filter:

writer->SetInput(convolutionFilter->GetOutput());

Hope this helps,
Matt

1 Like

Hi Matt,

I can’t click on the blue link, is there any link?
My issue is how to connect the kernelImage with the convolutionFilter? I try the following but I get a compile error:

using FilterType = itk::ConvolutionImageFilter< InputImageType, KernelImageType, OutputImageType >;
FilterType::Pointer convolutionFilter = FilterType::New();
convolutionFilter->SetInput(reader->GetOutput());
convolutionFilter->SetKernelImage(kernelImage); //kernel

Could you please provide some help?

Thanks a lot,
Eleni

Matt’s blue link was originally broken, I have edited his answer to fix the link.

You need to change

convolutionFilter->SetKernelImage(kernelImage); //kernel

into:

convolutionFilter->SetKernelImage(kernel->GetOutput()); //kernel
2 Likes

Thank you both!

1 Like