Skip to content

NibabelWriter fails on 2D channel-less arrays with no target affine (regression in 1.6.0) #9166

Open

Description

@garciadias

Describe the bug

NibabelWriter.set_metadata() raises TypeError: '>=' not supported between instances of 'NoneType' and 'int' for a 2D array written with channel_dim=None when no original_affine / spatial_shape is given. The same call works for 3D arrays, and it worked for 2D arrays in 1.5.1.

spatial_resample now derives the spatial rank from get_spatial_ndim(img) (the MetaTensor.spatial_ndim path). For this input that gives rank 1, so the spatial_size is None and spatial_rank > 1 auto-size branch is skipped. spatial_size stays None and then reaches fall_back_tuple(..., lambda x: x >= 0).

To Reproduce

import numpy as np, tempfile
from monai.data.image_writer import NibabelWriter

for shape in [(64, 64), (8, 64, 64)]:
    w = NibabelWriter(output_dtype=np.float32)
    w.set_data_array(np.random.rand(*shape).astype(np.float32), channel_dim=None, spatial_ndim=None)
    w.set_metadata({"affine": np.eye(4), "original_affine": None})
    w.write(tempfile.NamedTemporaryFile(suffix=".nii").name)
  • MONAI 1.5.1: both shapes OK
  • MONAI 1.6.1: (64, 64) fails with the TypeError above; (8, 64, 64) OK

Expected behavior

2D channel-less arrays are written unchanged, as they were in 1.5.1.

Workaround

Passing "spatial_shape": data.shape in the metadata avoids the failing branch. Output is identical when no target affine is given.

Environment

MONAI 1.6.1 (also present on dev), Python 3.12.

Activity

  1. Karunasagar12 commented on Oct 18, 2026

    @Karunasagar12

    Hi @garciadias, thanks for the clear repro and the pointer to get_spatial_ndim. Is anyone already working on this? If not, I'd like to take it.

    My plan is to trace how spatial_resample derives the spatial rank for a channel-less 2D array and fix that path, then add a regression test based on your (64, 64) example. I'm happy to adjust if you'd prefer a different approach.

  2. ericspod commented on Oct 20, 2026

    @ericspod
    Member

    Hi @Karunasagar12 If you wanted to look into this issue feel free but @Spenhouet mentioned he had a fix already for it. It you wanted to check that PR it would help to have more eyes on things, thanks.

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