Skip to content

type inconsistency with numpy.mean() #2726

Description

@brad-t-moore

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    status:Use_Milestone_BacklogUse "Backlog" milestone instead of label for issues without a fixed deadlinetype:BugInconsistencies or issues which will cause an incorrect result under some or all circumstances

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions