ITK icon indicating copy to clipboard operation
ITK copied to clipboard

type inconsistency with numpy.mean()

Open brad-t-moore opened this issue 2 years ago • 2 comments

Description

Briefly: calling np.mean() on an instance of itk.itkPyBufferPython.NDArrayITKBase returns a single value of type itk.itkPyBufferPython.NDArrayITKBase whereas np.mean() called on an numpy.ndarray returns a scalar numpy.float32. This causing what I think is an array-check in MONAI to crash.

Steps to Reproduce

I'm trying to run some MONAI code using ITK's file reader. Deep within MONAI's transform code there is a type check the result of a np.mean() call:

> .\lib\site-packages\monai\transforms\intensity\array.py(529)_normalize()
    527         _sub = sub if sub is not None else np.mean(img[slices])
    528         if isinstance(_sub, np.ndarray):
--> 529             _sub = _sub[slices]
    530 
    531         _div = div if div is not None else np.std(img[slices])

Line 529 crashes with a IndexError: too many indices for array: array is 0-dimensional, but 3 were indexed error.

You can see the different types below:

ipdb> type(_sub)
<class 'itk.itkPyBufferPython.NDArrayITKBase'>
ipdb>  _sub.dtype
dtype('float32')
ipdb>  print(_sub)
0.11837979
ipdb>  sub
None
ipdb>  print(np.mean(img[slices]))
0.11837979
ipdb>  type(np.mean(img[slices]))
<class 'itk.itkPyBufferPython.NDArrayITKBase'>
ipdb>  type(np.mean(itk.array_from_image(img)[slices]))
*** RuntimeError: No suitable template parameter can be found.
ipdb>  tmp = np.asarray(img)
<class 'numpy.ndarray'>
ipdb>  tmp.shape
(1, 960, 644)
ipdb>  type(np.mean(tmp[slices]))
<class 'numpy.float32'>
ipdb>  type(img)
<class 'itk.itkPyBufferPython.NDArrayITKBase'>
ipdb>  np.mean(tmp[slices])
0.11837979
ipdb>  print(np.mean(img[slices]))
0.11837979

Expected behavior

I don't know the correctness of MONAI's code here, but should the return type of the np.mean() call be consistent?

Actual behavior

calling np.mean() on an instance of itk.itkPyBufferPython.NDArrayITKBase returns a single value of type itk.itkPyBufferPython.NDArrayITKBase whereas np.mean() called on an numpy.ndarray returns a scalar numpy.float32.

Reproducibility

100%

Versions

itk 5.2.1.post1

Environment

monai 0.6.0 numpy 1.21.2 python 3.7.6 Windows 10

Additional Information

brad-t-moore avatar Sep 08 '21 21:09 brad-t-moore

@brad-t-moore thanks for the report --- yes, it seems reasonable to return the same type.

thewtex avatar Sep 09 '21 00:09 thewtex

This issue has been automatically marked as stale because it has not had recent activity. Thank you for your contributions.

stale[bot] avatar Apr 16 '22 10:04 stale[bot]