Skip to content
35 changes: 33 additions & 2 deletions monai/transforms/intensity/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,39 @@ def __call__(self, img: NdarrayOrTensor, offset: float | None = None) -> Ndarray

img = convert_to_tensor(img, track_meta=get_track_meta())
offset = self.offset if offset is None else offset
out = img + offset
out, *_ = convert_data_type(data=out, dtype=img.dtype, safe=self.safe)
if (
self.safe
and not img.is_floating_point()
and (isinstance(offset, int) or (isinstance(offset, float) and offset.is_integer()))
):
# Keep integral offsets in integer arithmetic to avoid float64 precision
# loss for int64 values above 2**53.
shift = int(offset)
bounds = torch.iinfo(img.dtype)
if shift >= bounds.max - bounds.min:
out = torch.full_like(img, bounds.max)
elif shift <= bounds.min - bounds.max:
out = torch.full_like(img, bounds.min)
else:
# Clamp before adding so even int64 arithmetic cannot overflow.
work = img.to(torch.int64)
if shift > 0:
work = work.clamp(max=bounds.max - shift)
elif shift < 0:
work = work.clamp(min=bounds.min - shift)
# Large offsets may exceed the range of a PyTorch int64 scalar.
# Split them into representable additions after clamping.
int64_bounds = torch.iinfo(torch.int64)
remaining = shift
while remaining:
step = min(remaining, int64_bounds.max) if remaining > 0 else max(remaining, int64_bounds.min)
work = work + step
remaining -= step
out = work.to(img.dtype)
else:
computation_img = img.to(torch.float64) if self.safe and not img.is_floating_point() else img
out = computation_img + offset
out, *_ = convert_data_type(data=out, dtype=img.dtype, safe=self.safe)

return out

Expand Down
30 changes: 30 additions & 0 deletions tests/transforms/test_shift_intensity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,42 @@
import unittest

import numpy as np
import torch

from monai.transforms import ShiftIntensity
from tests.test_utils import NumpyImageTestCase2D


class TestShiftIntensity(NumpyImageTestCase2D):
def test_safe_integer_offset_clamps_unsigned_image(self):
image = torch.tensor([0, 100, 255], dtype=torch.uint8)
for offset, expected in ((1, [1, 101, 255]), (-1, [0, 99, 254]), (1.0, [1, 101, 255]), (-1.0, [0, 99, 254])):
with self.subTest(offset=offset):
result = ShiftIntensity(offset=offset, safe=True)(image)
torch.testing.assert_close(result, torch.tensor(expected, dtype=torch.uint8))

def test_safe_integer_offset_clamps_signed_image(self):
image = torch.tensor([-128, 0, 127], dtype=torch.int8)
result = ShiftIntensity(offset=1, safe=True)(image)
torch.testing.assert_close(result, torch.tensor([-127, 1, 127], dtype=torch.int8))
result = ShiftIntensity(offset=-1, safe=True)(image)
torch.testing.assert_close(result, torch.tensor([-128, -1, 126], dtype=torch.int8))

def test_safe_int64_preserves_large_integer_precision(self):
image = torch.tensor([2**60 + 1, torch.iinfo(torch.int64).max], dtype=torch.int64)
result = ShiftIntensity(offset=1, safe=True)(image)
torch.testing.assert_close(result, torch.tensor([2**60 + 2, torch.iinfo(torch.int64).max], dtype=torch.int64))
negative = torch.tensor([-(2**60 + 1), torch.iinfo(torch.int64).min], dtype=torch.int64)
result = ShiftIntensity(offset=-1, safe=True)(negative)
torch.testing.assert_close(
result, torch.tensor([-(2**60 + 2), torch.iinfo(torch.int64).min], dtype=torch.int64)
)

def test_safe_int64_offset_beyond_scalar_range(self):
image = torch.tensor([2**62], dtype=torch.int64)
result = ShiftIntensity(offset=float(-3 * 2**62), safe=True)(image)
torch.testing.assert_close(result, torch.tensor([torch.iinfo(torch.int64).min], dtype=torch.int64))

def test_value(self):
shifter = ShiftIntensity(offset=1.0)
result = shifter(self.imt)
Expand Down