Skip to content

NormalizeIntensity inverse fails on non-contiguous inputs with nonzero=True #9182

Open

Description

@mottopanikeiku

Describe the bug

The text in this issue was written with AI assistance (Claude and GPT-6 Astra).

NormalizeIntensity(nonzero=True) accepts a transposed image, but inverse() on the result raises a stride error. NormalizeIntensityd and channel_wise=True fail the same way. This blocks restoring the original intensities after normalizing an image whose axes were reordered.

To Reproduce

import torch
from monai.transforms import NormalizeIntensity, NormalizeIntensityd

image = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[0.0, 0.0], [0.0, 2.0]]]).transpose(1, 2)
for channel_wise in (False, True):
    for dictionary in (False, True):
        transform = (
            NormalizeIntensityd("image", nonzero=True, channel_wise=channel_wise)
            if dictionary
            else NormalizeIntensity(nonzero=True, channel_wise=channel_wise)
        )
        data = {"image": image.clone()} if dictionary else image.clone()
        normalized = transform(data)
        label = f"{type(transform).__name__}(channel_wise={channel_wise})"
        try:
            restored = transform.inverse(normalized)
            restored = restored["image"] if dictionary else restored
            print(label, "round_trip=", torch.allclose(restored, image))
        except RuntimeError as error:
            print(label, type(error).__name__ + ":", str(error))

All four cases print:

RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

Expected behavior

round_trip= True for all four cases, as for a contiguous input.

Environment

MONAI dev (6aa4abf) from source, PyTorch 2.14.1+cpu, NumPy 2.5.4, Python 3.12.13, Linux.

Additional context

The error comes from mask.view(-1)[zeroed_idx] = True in NormalizeIntensity.inverse (added in #8905): the boolean mask keeps the transposed layout. Making that mask contiguous fixes all four cases. I have the fix with regression tests and will open a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions