ITK
ITK copied to clipboard
itkPython: itkImage use in np.where returns incorrect results
Description
It is possible to pass an itkImage to a numpy.where call, but the results are incorrect. A test of
np.where(<itk::Image>==<value>, <true_result>, <false_result>)
will return an image full of <false_result>
, regardless of the value of <value>
and regardless of the content of the image.
Steps to Reproduce
See attached ipython notebook. In summary
import itk
import numpy as np
print("A numpy array (arr) and itkImage (img) set to identity.")
arr = np.eye(3,3)
img = itk.GetImageFromArray(arr)
print("Using an itkImage in np.where statement produces unexpected results...")
print(" Array where arr[i,j]==0 change to a 2 =", np.where(arr==0,2,arr))
print(" itkImage where img[i,j]==0 change to a 2 =", np.where(img==0,2,img))
Produces...
A numpy array (arr) and itkImage (img) set to identity.
Using an itkImage in np.where statement produces unexpected results...
Array where arr[i,j]==0 change to a 2 = [[1. 2. 2.]
[2. 1. 2.]
[2. 2. 1.]]
itkImage where img[i,j]==0 change to a 2 = [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Additionally,
print("The test itkImage==<value> appears to always return false?")
arr = np.zeros([3,3])
img = itk.GetImageFromArray(arr)
print(" Given arr=0, using np.where to change any instance of arr[i,j]==0 to a 2 =", np.where(arr==0,2,arr))
print(" Given img=0, using np.where to change any instance of img[i,j]==0 to a 2 =", np.where(img==0,2,img))
produces...
The test itkImage==<value> appears to always return false?
Given arr=0, using np.where to change any instance of arr[i,j]==0 to a 2 = [[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
Given img=0, using np.where to change any instance of img[i,j]==0 to a 2 = [[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Expected behavior
Using an itk:image in a numpy conditional should work as if a numpy array was used.
Actual behavior
Using an itk::image in a numpy.where conditional always returns false.
Reproducibility
See attached ipython notebook.
Versions
ITKv5.3rc01
Environment
Linux, Ubuntu 20.XX
Zipped ipython notebook attached. itkImageAndNPWhereAreNotCompatible.zip
xref https://github.com/InsightSoftwareConsortium/ITK/issues/1092
Related:
- https://data-apis.org/array-api/latest/index.html
- https://labs.quansight.org/blog/2019/07/uarray-update-api-changes-overhead-and-comparison-to-array_function/
- https://labs.quansight.org/blog/2021/11/pydata-extensibility-vision/
This issue has been automatically marked as stale because it has not had recent activity. Thank you for your contributions.