Welcome to ITKPythonPackage’s documentation!¶
This project provides a setup.py
script to build ITK Python wheels and
infrastructure to build ITK external module Python wheels.
ITK is an open-source, cross-platform system that provides developers with an extensive suite of software tools for image analysis.
To install the stable ITK Python package:
python -m pip install --upgrade pip
python -m pip install itk
The Python packages are built daily. To install the latest build from the ITK Git master branch:
python -m pip install --upgrade pip numpy
python -m pip install itk --upgrade --no-index \
-f https://github.com/InsightSoftwareConsortium/ITKPythonPackage/releases/tag/latest
For more information on ITK’s Python wrapping, see an introduction in the ITK Software Guide. There are also many downloadable examples documented in Sphinx.
Quick start guide¶
Installation¶
To install the ITK Python package:
$ python -m pip install --upgrade pip
$ python -m pip install itk
If a pre-compiled wheel package is not found for your Python distribution, then it will attempt to build from source.
Note
On Windows machines, the source path cannot be greater than 50 characters or issues will occur during build time due to filename truncation in Visual Studio. If you must compile from source, clone this repository in a short directory, like C:/IPP. Then, run setup.py within the repository via the command line.
Usage¶
Basic examples¶
Here is a simple python script that reads an image, applies a median image filter (radius of 2 pixels), and writes the resulting image in a file.
#!/usr/bin/env python
import itk
import sys
input_filename = sys.argv[1]
output_filename = sys.argv[2]
image = itk.imread(input_filename)
median = itk.MedianImageFilter.New(image, Radius = 2)
itk.imwrite(median, output_filename)
There are two ways to instantiate filters with ITKPython:
- Implicit (recommended): ITK type information is automatically detected from the data. Typed filter objects and images are implicitly created.
# Use `ImageFileReader` instead of the wrapping function `imread` to illustrate this example.
reader = itk.ImageFileReader.New(FileName=input_filename)
# Here we specify the filter input explicitly
median = itk.MedianImageFilter.New(Input=reader.GetOutput())
# Same as above but shortened. `Input` does not have to be specified.
median = itk.MedianImageFilter.New(reader.GetOutput())
# Same as above. `.GetOutput()` does not have to be specified.
median = itk.MedianImageFilter.New(reader)
- Explicit: This can be useful if a filter cannot automatically select the type information (e.g. CastImageFilter), or to detect type mismatch errors which can lead to cryptic error messages.
Explicit instantiation of median image filter:
# Use `ImageFileReader` instead of the wrapping function `imread` to illustrate this example.
reader = itk.ImageFileReader.New(FileName=input_filename)
# Here we specify the filter input explicitly
median = itk.MedianImageFilter.New(Input=reader.GetOutput())
# Same as above but shortened. `Input` does not have to be specified.
median = itk.MedianImageFilter.New(reader.GetOutput())
# Same as above. `.GetOutput()` does not have to be specified.
median = itk.MedianImageFilter.New(reader)
Explicit instantiation of cast image filter:
image = itk.imread(input_filename)
InputType = type(image)
# Find input image dimension
input_dimension = image.GetImageDimension()
# Select float as output pixel type
OutputType = itk.Image[itk.UC, input_dimension]
castFilter = itk.CastImageFilter[InputType, OutputType].New()
castFilter.SetInput(image)
itk.imwrite(castFilter, output_filename)
ITK Python types¶
C++ type | Python type |
---|---|
float | itk.F |
double | itk.D |
unsigned char | itk.UC |
std::complex<float> | itk.complex[itk.F] |
This list is not exhaustive and is only presented to illustrate the type names. The complete list of types can be found in the ITK Software Guide.
Types can also be obtained from their name in the C programming language:
itk.F == itk.ctype('float') # True
Instantiate an ITK object¶
There are two types of ITK objects. Most ITK objects (images, filters, adapters, …) are instantiated the following way:
InputType = itk.Image[itk.F,3]
OutputType = itk.Image[itk.F,3]
median = itk.MedianImageFilter[InputType, OutputType].New()
Some objects (matrix, vector, RGBPixel, …) do not require the attribute .New() to be added to instantiate them:
pixel = itk.RGBPixel[itk.D]()
In case of doubt, look at the attributes of the object you are trying to instantiate.
Mixing ITK and NumPy¶
A common use case for using ITK in Python is to mingle NumPy and ITK operations on raster data. ITK provides a large number of I/O image formats and several sophisticated image processing algorithms not available in any other packages. The ability to intersperse that with numpy special purpose hacking provides a great tool for rapid prototyping.
The following script shows how to integrate NumPy and ITK:
import itk
import numpy as np
# Read input image
itk_image = itk.imread(input_filename)
# Run filters on itk.Image
# View only of itk.Image, data is not copied
np_view = itk.GetArrayViewFromImage(itk_image)
# Copy of itk.Image, data is copied
np_copy = itk.GetArrayFromImage(itk_image)
# Do numpy stuff
# Convert back to itk, view only, data is not copied
itk_np_view = itk.GetImageViewFromArray(np_copy)
# Convert back to itk, data is copied
itk_np_copy = itk.GetImageFromArray(np_copy)
# Save result
itk.imwrite(itk_np_view, output_filename)
Similar functions are available to work with VNL vector and matrices:
# Vnl matrix from array
arr = np.zeros([3,3], np.uint8)
matrix = itk.GetVnlMatrixFromArray(arr)
# Array from Vnl matrix
arr = itk.GetArrayFromVnlMatrix(matrix)
# Vnl vector from array
vec = np.zeros([3], np.uint8)
vnl_vector = itk.GetVnlVectorFromArray(vec)
# Array from Vnl vector
vec = itk.GetArrayFromVnlVector(vnl_vector)
Examples¶
Examples can be found in the ITKExamples project.
Build ITK Module Python packages¶
ITK is organized into modules. Modules for ITK can be developed outside the ITK source tree as external modules. The external module can be made available in ITK’s CMake configuration by contributing it as a remote module. Python packages can also be generated for external modules and uploaded to the Python Package Index (PyPI)
This section describes how to create, build, and upload ITK external module Python packages to PyPI.
Prerequisites¶
Building wheels requires:
- CMake
- Git
- C++ Compiler - Platform specific requirements are summarized in scikit-build documentation.
- Python
Create the module¶
To create an ITK module with Python wrapping, first run cookiecutter:
python -m pip install cookiecutter
python -m cookiecutter gh:InsightSoftwareConsortium/ITKModuleTemplate
# Fill in the information requested at the prompts
Then, add your classes. Reference documentation on how to populate the module can be found in the ITK Software Guide.
GitHub automated CI package builds¶
Freely available continous integration (CI) testing services for open source repositories on GitHub can be used to generate Linux, macOS, and Windows Python packages for your module.
After enabling builds for the GitHub repository with a CircleCI, TravisCI, and AppVeyor account, Python wheel packages will be available with the continuous integration builds. These services use the configurations generated by the ITKModuleTemplate.
Automated platform scripts¶
Automated scripts are available in this repository to build Python packages that are binary compatible with the Python distributions provided by Python.org, Anaconda, and package managers like apt or Homebrew. The following sections outline how to use the associated scripts for Linux, macOS, and Windows.
Once the builds are complete, Python packages will be available in the dist directory.
Linux¶
To build portable Python packages on Linux, first install Docker.
For the first local build, clone the ITKPythonPackage repository inside your and download the required ITK binary builds:
cd ~/ITKMyModule
git clone https://github.com/InsightSoftwareConsortium/ITKPythonPackage
./ITKPythonPackage/scripts/dockcross-manylinux-download-cache-and-build-module-wheels.sh
For subsequent builds, just call the build script:
./ITKPythonPackage/scripts/dockcross-manylinux-build-module-wheels.sh
macOS¶
First, install the Python.org macOS Python distributions. This step requires sudo:
cd ~/ITKMyModule
git clone https://github.com/InsightSoftwareConsortium/ITKPythonPackage
./ITKPythonPackage/scripts/macpython-install-python.sh
Then, build the wheels:
./ITKPythonPackage/scripts/macpython-build-wheels.sh
Windows¶
First, install Microsoft Visual Studio 2015, Git, and CMake, which should be added to the system PATH environmental variable.
Open a PowerShell terminal as Administrator, and install Python:
PS C:\> Set-ExecutionPolicy Unrestricted
PS C:\> $pythonArch = "64"
PS C:\> iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/scikit-build/scikit-ci-addons/master/windows/install-python.ps1'))
In a PowerShell prompt, run the windows-build-wheels.ps1 script:
PS C:\Windows> cd C:\ITKMyModule
PS C:\ITKMyModule> git clone https://github.com/InsightSoftwareConsortium/ITKPythonPackage.git IPP
PS C:\ITKMyModule> .\ITKPythonPackage\scripts\windows-download-cache-and-build-module-wheels.ps1
Upload the packages to PyPI¶
First, register for an account on PyPI.
Next, create a ~/.pypirc file with your login credentials:
[distutils]
index-servers =
pypi
pypitest
[pypi]
username=<your-username>
password=<your-password>
[pypitest]
repository=https://test.pypi.org/legacy/
username=<your-username>
password=<your-password>
where <your-username> and <your-password> correspond to your PyPI account.
Then, upload wheels to the testing server:
python -m pip install twine
python -m twine upload -r pypitest dist/*
Check out the packages on https://test.pypi.org/ the testing server.
Finally, upload the wheel packages to the production PyPI server:
python -m twine upload dist/*
Congratulations! Your packages can be installed with the commands:
python -m pip install --upgrade pip
python -m pip install itk-<yourmodulename>
Build ITK Python packages¶
This section describes how to builds ITK’s Python packages. In most cases, the pre-built ITK binary wheels can be used.
ITK Python packages are built nightly on Kitware build systems and uploaded to the ITKPythonPackage GitHub releases page.
Prerequisites¶
Building wheels requires:
- CMake
- Git
- C++ Compiler - Platform specific requirements are summarized in scikit-build documentation.
- Python
Automated platform scripts¶
Steps required to build wheels on Linux, macOS and Windows have been automated. The following sections outline how to use the associated scripts.
Linux¶
On any linux distribution with docker and bash installed, running the script dockcross-manylinux-build-wheels.sh will create 64-bit wheels for both python 2.x and python 3.x in the dist directory.
For example:
$ git clone https://github.com/InsightSoftwareConsortium/ITKPythonPackage.git
[...]
$ ./scripts/dockcross-manylinux-build-wheels.sh
[...]
$ ls -1 dist/
itk-4.11.0.dev20170218-cp27-cp27m-manylinux1_x86_64.whl
itk-4.11.0.dev20170218-cp27-cp27mu-manylinux1_x86_64.whl
itk-4.11.0.dev20170218-cp34-cp34m-manylinux1_x86_64.whl
itk-4.11.0.dev20170218-cp35-cp35m-manylinux1_x86_64.whl
itk-4.11.0.dev20170218-cp36-cp36m-manylinux1_x86_64.whl
macOS¶
First, install the Python.org macOS Python distributions. This step requires sudo:
./scripts/macpython-install-python.sh
Then, build the wheels:
$ ./scripts/macpython-build-wheels.sh
[...]
$ ls -1 dist/
itk-4.11.0.dev20170213-cp27-cp27m-macosx_10_6_x86_64.whl
itk-4.11.0.dev20170213-cp34-cp34m-macosx_10_6_x86_64.whl
itk-4.11.0.dev20170213-cp35-cp35m-macosx_10_6_x86_64.whl
itk-4.11.0.dev20170213-cp36-cp36m-macosx_10_6_x86_64.whl
Windows¶
First, install Microsoft Visual Studio 2015, Git, and CMake, which should be added to the system PATH environmental variable.
Open a PowerShell terminal as Administrator, and install Python:
PS C:\> Set-ExecutionPolicy Unrestricted
PS C:\> $pythonArch = "64"
PS C:\> iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/scikit-build/scikit-ci-addons/master/windows/install-python.ps1'))
In a PowerShell prompt:
PS C:\Windows> cd C:\
PS C:\> git clone https://github.com/InsightSoftwareConsortium/ITKPythonPackage.git IPP
PS C:\> cd IPP
PS C:\IPP> .\scripts\windows-build-wheels.ps1
[...]
PS C:\IPP> ls dist
Directory: C:\IPP\dist
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/9/2017 11:14 PM 63274441 itk-4.11.0.dev20170407-cp35-cp35m-win_amd64.whl
-a---- 4/10/2017 2:08 AM 63257220 itk-4.11.0.dev20170407-cp36-cp36m-win_amd64.whl
We need to work in a short directory to avoid path length limitations on Windows, so the repository is cloned into C:IPP.
Also, it is very important to disable antivirus checking on the C:IPP directory. Otherwise, the build system conflicts with the antivirus when many files are created and deleted quickly, which can result in Access Denied errors. Windows 10 ships with an antivirus application, Windows Defender, that is enabled by default.
sdist¶
To create source distributions, sdist’s, that will be used by pip to compile a wheel for installation if a binary wheel is not available for the current Python version or platform:
$ python setup.py sdist --formats=gztar,zip
[...]
$ ls -1 dist/
itk-4.11.0.dev20170216.tar.gz
itk-4.11.0.dev20170216.zip
Manual builds¶
Building ITK Python wheels¶
Build the ITK Python wheel with the following command:
mkvirtualenv build-itk
pip install -r requirements-dev.txt
python setup.py bdist_wheel
Efficiently building wheels for different version of python¶
If on a given platform you would like to build wheels for different version of python, you can download and build the ITK components independent from python first and reuse them when building each wheel.
Here are the steps:
Build ITKPythonPackage with ITKPythonPackage_BUILD_PYTHON set to OFF
Build “flavor” of package using:
python setup.py bdist_wheel -- \ -DITK_SOURCE_DIR:PATH=/path/to/ITKPythonPackage-core-build/ITKs
Miscellaneous¶
Written by Jean-Christophe Fillion-Robin and Matt McCormick from Kitware Inc.
It is covered by the Apache License, Version 2.0:
http://www.apache.org/licenses/LICENSE-2.0
For more information about ITK, visit https://itk.org