InsightSoftwareConsortium / InsightSoftwareConsortium/ITK

type inconsistency with numpy.mean()

Open
#2,726 2 comments 0 reactions 0 assignees View on GitHub
status:Use_Milestone_Backlog type:Bug
Dominant language
C++
Stars
1.7k
Forks
748
Avg merge
1d 1h
Merged PRs (30d)
64

Description

### 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)

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]))

ipdb> type(np.mean(itk.array_from_image(img)[slices]))
*** RuntimeError: No suitable template parameter can be found.
ipdb> tmp = np.asarray(img)

ipdb> tmp.shape
(1, 960, 644)
ipdb> type(np.mean(tmp[slices]))

ipdb> type(img)

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.