This page describes how to use ITK from .NET.
NOTE: You must build ITK, wrapper DLL, and .NET exe all using the same target platform i.e. Win32/x86 or Win64/x64
CMakeLists.txt
file:
# File: CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(ExampleWrapper)
find_package(ITK REQUIRED)
include(${ITK_USE_FILE})
add_library(ExampleWrapper SHARED example.h example.hxx example_wrap.cxx)
target_link_libraries(ExampleWrapper ${ITK_LIBRARIES})
example.h
file:
// File : example.h
#ifndef __example_h
#define __example_h
#include <string>
template<class TPixel, unsigned int VDimension>
void SmoothImage(
const std::string input, const std::string output, const double sigma
);
#include "example.hxx"
#endif // __example_h
example.hxx
file:
#ifndef __example_hxx
#define __example_hxx
#include "example.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSmoothingRecursiveGaussianImageFilter.h"
template<class TPixel, unsigned int VDimension>
void SmoothImage(
const std::string input, const std::string output, const double sigma
) {
// Read input
typedef itk::Image<TPixel,VDimension> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(input);
reader->Update();
// Apply filter
typedef itk::SmoothingRecursiveGaussianImageFilter<ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(reader->GetOutput());
filter->SetSigma(sigma);
filter->Update();
// Write output
typedef itk::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(output);
writer->Update();
}
#endif // __example_hxx
example.i
file (instructs SWIG how to generate the wrapper):
// File : example.i
%module example
%include "std_string.i"
%{
#include "example.h"
%}
%include "example.h"
%template(SmoothImageUC2)SmoothImage<unsigned char, 2>;
%template(SmoothImageF2) SmoothImage<float, 2>;
swig -c++ -csharp -dllimport ExampleWrapper example.i
example_wrap.cxx
example.cs
examplePINVOKE.cs
ExampleWrapper.dll
runme.cs
file:
// File: runme.cs
using System;
public class runme {
[STAThread()]
static void Main() {
try {
example.SmoothImageUC2(
input: "C:/Temp/cthead1.png",
output: "C:/Temp/cthead1-smooth.png",
sigma: 5.0
);
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
}
mcs -platform:x86 -target:exe -out:example.exe runme.cs example.cs examplePINVOKE.cs
ExampleWrapper.dll
(the easiest way is to copy the dll to the same folder as example.exe
)