Skip to content
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
8 changes: 3 additions & 5 deletions monai/transforms/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,18 +157,16 @@ def rescale_array(
"""
Rescale the values of numpy array `arr` to be from `minv` to `maxv`.
"""
dtype_ = dtype or arr.dtype
if dtype is not None:
arr, *_ = convert_data_type(arr, dtype=dtype)
mina = arr.min()
maxa = arr.max()

if mina == maxa:
return arr * minv

norm = (arr - mina) / (maxa - mina) # normalize the array first
arr = (norm * (maxv - minv)) + minv # rescale by minv and maxv, which is the normalized array by default

ret, *_ = convert_data_type(arr, dtype=dtype_)
return ret
return (norm * (maxv - minv)) + minv # rescale by minv and maxv, which is the normalized array by default


def rescale_instance_array(
Expand Down
12 changes: 12 additions & 0 deletions tests/test_scale_intensity.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ def test_factor_scale(self):
expected = p((self.imt * (1 + 0.1)).astype(np.float32))
assert_allclose(result, p(expected), rtol=1e-7, atol=0)

def test_int(self):
"""integers should be handled by converting them to floats first."""
for p in TEST_NDARRAYS:
scaler = ScaleIntensity(minv=1.0, maxv=2.0)
result = scaler(p(self.imt.astype(int)))
_imt = self.imt.astype(int).astype(np.float32)
mina = _imt.min()
maxa = _imt.max()
norm = (_imt - mina) / (maxa - mina)
expected = p((norm * (2.0 - 1.0)) + 1.0)
assert_allclose(result, expected, type_test=False, rtol=1e-7, atol=0)

def test_channel_wise(self):
for p in TEST_NDARRAYS:
scaler = ScaleIntensity(minv=1.0, maxv=2.0, channel_wise=True)
Expand Down