Skip to content

Commit bdb3604

Browse files
committed
Fix channel-wise intensity normalization for integer type inputs. Signed-off-by: Adrian Voicu <adrianvoicu.tm@gmail.com>
1 parent 28a0df1 commit bdb3604

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

monai/transforms/intensity/array.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,8 @@ def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
907907
if self.divisor is not None and len(self.divisor) != len(img):
908908
raise ValueError(f"img has {len(img)} channels, but divisor has {len(self.divisor)} components.")
909909

910+
img, *_ = convert_data_type(img, dtype=torch.float32)
911+
910912
for i, d in enumerate(img):
911913
img[i] = self._normalize( # type: ignore
912914
d,

tests/test_normalize_intensity.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,27 @@ def test_channel_wise(self, im_type):
108108
normalized = normalizer(input_data)
109109
assert_allclose(normalized, im_type(expected), type_test="tensor")
110110

111+
@parameterized.expand([[p] for p in TEST_NDARRAYS])
112+
def test_channel_wise_int(self, im_type):
113+
normalizer = NormalizeIntensity(nonzero=True, channel_wise=True)
114+
input_data = im_type(torch.arange(1, 25).reshape(2, 3, 4))
115+
expected = np.array(
116+
[
117+
[
118+
[-1.593255, -1.3035723, -1.0138896, -0.7242068],
119+
[-0.4345241, -0.1448414, 0.1448414, 0.4345241],
120+
[0.7242068, 1.0138896, 1.3035723, 1.593255],
121+
],
122+
[
123+
[-1.593255, -1.3035723, -1.0138896, -0.7242068],
124+
[-0.4345241, -0.1448414, 0.1448414, 0.4345241],
125+
[0.7242068, 1.0138896, 1.3035723, 1.593255],
126+
],
127+
]
128+
)
129+
normalized = normalizer(input_data)
130+
assert_allclose(normalized, im_type(expected), type_test="tensor", rtol=1e-7, atol=1e-7) # tolerance
131+
111132
@parameterized.expand([[p] for p in TEST_NDARRAYS])
112133
def test_value_errors(self, im_type):
113134
input_data = im_type(np.array([[0.0, 3.0, 0.0, 4.0], [0.0, 4.0, 0.0, 5.0]]))

0 commit comments

Comments
 (0)