[ITK-users] ITK Python: numpy to itk image (and viceversa)
Matt McCormick
matt.mccormick at kitware.com
Mon Apr 3 14:40:50 EDT 2017
Hallo Fabio,
> I use ITK with Python Wrap. I need to interface my Python code with a
> Cython-wrapped C++ code that takes only numpy array as input and returns
> numpy array as output.
Cool. By the way, you may be interested in scikit-build [1], which is
a good way to build Cython-wrapped C++ code. We are using it for the
ITK and SimpleITK Python packages, and it has good Cython and CMake
support.
> Hence, I need to convert the Python itk images into numpy array to be given
> as input to the wrapped C++ code, and then convert the numpy array in output
> from the wrapped C++ code back into python itk images.
>
>
>
> Question 1) How can I do that in an efficient way? I found some posts on
> itk.PyBuffer but I could not find anywhere any reference on how to install
> it on my itk wrap build.
Yes, itk.PyBuffer works great for that. Please review a PR for some
additional documentation:
https://github.com/InsightSoftwareConsortium/ITKBridgeNumPy/pull/18
This has been available in ITK for a few releases as a Remote module,
which can be enabled by setting
Module_BridgeNumPy=ON
in ITK's CMake configuration.
Since ITK 4.11.0, it is easier to build since it does not require the
NumPy headers.
In current ITK Git master (to be 4.12.0) the module is enabled by default.
Nightly ITK Python packages for ITK Git master are now being built:
https://github.com/InsightSoftwareConsortium/ITKPythonPackage
macOS and Linux are available. Windows packages will be available over
the coming weeks.
> Question 2) The purpose of writing a part of my algorithm in C++ is to speed
> up the code. If the conversion between python itk images and numpy arrays is
> slow, I would lose all the speed gain obtained with the C++ implementation.
> Are there better ways to deal with that?
The newer versions ITKBridgeNumPy use a NumPy array view, which does
not do any copies during the conversion, and it is very fast.
HTH,
Matt
[1] http://scikit-build.org/
More information about the Insight-users
mailing list