Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add an example that demonstrates interfacing with NumPy #366

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .binder/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
itk>=5.2rc3
itkwidgets
itk>=5.3rc4
itkwidgets>=1.0a3
matplotlib
4 changes: 2 additions & 2 deletions .github/workflows/build-test-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ jobs:
strategy:
max-parallel: 3
matrix:
os: [ubuntu-18.04, windows-2019, macos-10.15]
os: [ubuntu-20.04, windows-2019, macos-10.15]
include:
- os: ubuntu-18.04
- os: ubuntu-20.04
c-compiler: "gcc"
cxx-compiler: "g++"
cmake-build-type: "MinSizeRel"
Expand Down
2 changes: 1 addition & 1 deletion Superbuild/External-Python.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ ExternalProject_Add(ITKPython
DOWNLOAD_COMMAND ""
CONFIGURE_COMMAND ${PYTHON_EXECUTABLE} -m venv "${_itk_venv}"
BUILD_COMMAND ${ITKPYTHON_EXECUTABLE} -m pip install --upgrade pip
INSTALL_COMMAND ${ITKPYTHON_EXECUTABLE} -m pip install --ignore-installed itk>=5.3rc4 sphinx==4.4.0 docutils<0.18 six black nbsphinx ipython sphinx-contributors
INSTALL_COMMAND ${ITKPYTHON_EXECUTABLE} -m pip install --ignore-installed itk>=5.3rc4 sphinx==4.4.0 docutils<0.18 six black nbsphinx ipython sphinx-contributors ipykernel matplotlib itkwidgets
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/ITKBlackConfig.cmake
)
2 changes: 2 additions & 0 deletions src/Bridge/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
if(ENABLE_QUICKVIEW)
add_subdirectory_if_module_enabled(VtkGlue)
endif()

add_subdirectory_if_module_enabled( NumPy )
1 change: 1 addition & 0 deletions src/Bridge/NumPy/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_example(ConvertNumPyArrayToitkImage)
18 changes: 18 additions & 0 deletions src/Bridge/NumPy/ConvertNumPyArrayToitkImage/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.16.3)

project( ConvertNumPyArrayToitkImage )

find_package( ITK REQUIRED )
include( ${ITK_USE_FILE} )

enable_testing()

set(input_image ${CMAKE_CURRENT_BINARY_DIR}/Slicer.png)

if(ITK_WRAP_PYTHON)
add_test(NAME ConvertNumPyArrayToitkImageTestPython
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Code.py
${input_image}
SliceRevised.png
)
endif()
71 changes: 71 additions & 0 deletions src/Bridge/NumPy/ConvertNumPyArrayToitkImage/Code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/bin/env python

# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import itk
import numpy as np

if len(sys.argv) != 3:
print("Usage: " + sys.argv[0] + " <input_image> <output_image>")
sys.exit(1)

# Parse comamnd line arguments
input_file_name = sys.argv[1]
output_file_name = sys.argv[2]

# Read input image
PixelType = itk.ctype("unsigned char")
ImageType = itk.Image[itk.UC, 2]
itk_image = itk.imread(input_file_name, PixelType)
OriginalRegion = itk_image.GetLargestPossibleRegion()
OriginalSize = OriginalRegion.GetSize()

print(f"The size of the ITK image data read from the input file = {OriginalSize}\n")

# There are two ways to bridge the data structures.
# i) Give direct access to memory holding the data called "View" functions for displaying
# purpose. But you can't modify the data
np_view_array = itk.GetArrayViewFromImage(itk_image, ttype=ImageType)
print(f"The size of the NumPy array viewed from itk::Image = {np_view_array.shape}")

# ii) Generate a copy of the data using using array_from_image function.
# You can then freely modify the data as it has no effect on the original ITK image.

# Copy itk.Image pixel data to numpy array
np_array = itk.GetArrayFromImage(itk_image, ttype=ImageType)
print(f"The size of the NumPy array copied from itk::Image = {np_array.shape}")

# Create an ITK image from the numpy array and then write it out
itk_np = itk.GetImageFromArray(np.ascontiguousarray(np_array))

region = itk_np.GetLargestPossibleRegion()
size = region.GetSize()
print(f"ITK image data size after convesion from NumPy = {size}\n")

itk.imwrite(itk_np, output_file_name)


# The order of the indexes is according to the type of object the data is stored in.
# A numpy array is indexed by [row , col ] for 2D data or [slice , row , col ] for 3D data.
# While ITK image data is indexed by (x , y ) for 2D or (x , y , z ) for 3D data.
# To demonstrate here, we create a 2D pixel array data
# and access a pixel with the same indices

np_data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.int32)
itk_np_view_data = itk.image_view_from_array(np_data)

print(f"ITK image data pixel value at [2,1] = {itk_np_view_data.GetPixel([2,1])}")
print(f"NumPy array pixel value at [2,1] = {np_data[2,1]}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "d1bdfc3b",
"metadata": {},
"source": [
"# Bridging ITK image data with NumPy array\n",
"\n",
"This example illustrates interfacing ITK Image data with NumPy array."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25e89adb",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"from urllib.request import urlretrieve\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"import itk\n",
"from itkwidgets import view\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7cdd2254",
"metadata": {},
"outputs": [],
"source": [
"input_image_path = \"Slicer.png\"\n",
"\n",
"if not os.path.exists(input_image_path):\n",
" url = \"https://data.kitware.com/api/v1/file/602c10a22fa25629b97d2896/download\"\n",
" urlretrieve(url, input_image_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "edf8512f",
"metadata": {},
"outputs": [],
"source": [
"PixelType = itk.ctype(\"unsigned char\")\n",
"ImageType = itk.Image[itk.UC, 2]\n",
"\n",
"itk_image = itk.imread(input_image_path, PixelType)\n",
"\n",
"OriginalRegion = itk_image.GetLargestPossibleRegion()\n",
"OriginalSize = OriginalRegion.GetSize()\n",
"\n",
"print (f'ITK image size = {OriginalSize}')\n",
"view(itk_image, ui_collapsed=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4c1a935a",
"metadata": {},
"outputs": [],
"source": [
"array = itk.GetArrayFromImage(itk_image, ttype=ImageType)\n",
"print(f'Array size = {array.shape}')\n",
"plt.gray()\n",
"plt.imshow(array)\n",
"plt.axis('off')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4efdcf7d",
"metadata": {},
"outputs": [],
"source": [
"itk_image_convert = itk.GetImageFromArray(np.ascontiguousarray(array))\n",
"region = itk_image_convert.GetLargestPossibleRegion()\n",
"size = region.GetSize()\n",
"print(f'Size = {size}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "753d085c",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
52 changes: 52 additions & 0 deletions src/Bridge/NumPy/ConvertNumPyArrayToitkImage/Documentation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
:name: ConvertNumPyArrayToitkImage

Interface ITK with NumPy Array
===============================

.. index::
single: Image

.. toctree::
:maxdepth: 1

ConvertNumPyArrayToitkImage.ipynb

Synopsis
--------

This example illustrates interfacing ITK Image data with NumPy array.
While doing this, there are two key issues to keep in mind. One, the order of
indexes is different between ITK image data class and NumPy array.
Second, there are two ways to access ITK image data as a NumPy array.
i) Get direct access to memory with the data called"View" functions, or
ii) Copy the data using array_from_image function. If the view functions are used,
the data can't be modified.

Results
-------
The size of the ITK image data read from the input file = itkSize2 ([221, 257])

The size of the NumPy array viewed from itk::Image = (257, 221)
The size of the NumPy array copied from itk::Image = (257, 221)
ITK image data size after convesion from NumPy = itkSize2 ([221, 257])

ITK image data pixel value at [2,1] = 6
NumPy array pixel value at [2,1] = 8


Code
----

Python
......

.. literalinclude:: Code.py
:language: python
:lines: 1, 16-



Classes demonstrated
--------------------

.. breathelink:: itk::Image
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
59ac2cc1a14666a72b9c21c1abd1a45aeef567d2e4690b761df2b36904dbc37f52458b54e6a22b32186f13fe45a4c91da6e9e0c3bcfbe0e959c81b514fb97237
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
64dd1f56f598fb9dfe8ebbf725a5fe1530ecabe1962661376e1228a3640c31316741d7c703f482adfaf9086762b44018f05a863b37bb19608735c7fd8ba57ca0
7 changes: 7 additions & 0 deletions src/Bridge/NumPy/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
NumPy
======

.. toctree::
:maxdepth: 1

ConvertNumPyArrayToitkImage/Documentation.rst
1 change: 1 addition & 0 deletions src/Bridge/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Bridge
:maxdepth: 2

VtkGlue/index.rst
NumPy/index.rst