diff --git a/monai/transforms/utils.py b/monai/transforms/utils.py index 1d3204b7a0..bb514104ae 100644 --- a/monai/transforms/utils.py +++ b/monai/transforms/utils.py @@ -157,7 +157,8 @@ 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() @@ -165,10 +166,7 @@ def rescale_array( 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( diff --git a/tests/test_scale_intensity.py b/tests/test_scale_intensity.py index ddc2fb08e1..cf57b4e3a4 100644 --- a/tests/test_scale_intensity.py +++ b/tests/test_scale_intensity.py @@ -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)