Wrap ITK Python

I’m trying to convert a C++ ITK code in python, but i find some issues with this input: TemplateTypeError: itk.ImageFileReader is not wrapped for input type itk.Image[itk.UL,3]. But i don’t know hot to solve the problem because i use this function to enter a .mha file.
Code:

import itk
import sys
import os
path=input(“Enter the path”)
Dim=3
PixelType=itk.F
LabelPixelType=itk.UL
ImageType=itk.Image[PixelType,Dim]
LabeledImageType=itk.Image[LabelPixelType,Dim]
MaskPixelType=itk.UC
MaskImageType=itk.Image[MaskPixelType,Dim]
#read the 3mm input volume
LabelReaderType=itk.ImageFileReader[LabeledImageType]
labelReader=LabelReaderType.New()
labelReader.SetFileName(path+“/T2.mha”)

Entire C++ code:
pkdMaskCreation.cxx (4.8 KB)

I guess itk::Image is not instantiated with unsigned long by default, so that is not part of wheel distribution. Try LabelPixelType=itk.US. Alternatively build ITK with Python wrapping yourself, and enable unsigned long for the wrapping.

1 Like

Thank you so much, with LabelPixelType=itk.US it seems to work. But i have another problem: if i want to use an iterator like iteratorType=itk.ImageRegionIterator[LabeledImageType] in python what i have to do, due to AttributeError: module 'itk' has no attribute 'ImageRegionIterator'. I read something about numpy, do you have some examples?

typedef itk::ImageRegionIterator IteratorType;
IteratorType maskIt(outputImage,outputImage->GetLargestPossibleRegion());
LabelPixelType backgroundValue = 0;
LabelPixelType foregroundValue = 1;
for (maskIt.GoToBegin(); !maskIt.IsAtEnd(); ++maskIt)
{
ImageType::PointType point;
outputImage->TransformIndexToPhysicalPoint(maskIt.GetIndex(),point);
if (maskInterpolator->IsInsideBuffer(point))
{
if (maskInterpolator->Evaluate(point) == 0)
{
maskIt.Set(backgroundValue);
}
else
{
maskIt.Set(foregroundValue);
}
}
else
{
maskIt.Set(backgroundValue);
}
}

ImageRegionIterator is not wrapped on purpose, because accessing images via iterators from Python is way too slow. Here is how to convert to/from numpy.

2 Likes

If you want to expose an existing C++ ITK filter to python, wrap the whole filter to python, not the internals. This is how is done in all the external modules, https://github.com/InsightSoftwareConsortium/ITKModuleTemplate

You are trying to do in python what ITK does in c++, this is not performant. Better to compute it in c++ and then, expose it to python with the wrapping mechanisms of ITK. Especially if you already have the filter written in c++. Hope it helps!

3 Likes

The problem is that the code is very older (many years ago) and some libraries in c++ changed,so some functions are no more supported, so i have also to modify the code

Can i build a ITKModule with that procedure in Windows?

Yes, Windows is one of the supported platforms.