Skip to content

fix: division by zero in DICOMReader._get_affine for single-slice 3D volumes #8925

Description

@rtmalikian

Problem

In monai/data/image_reader.py, the DICOMReader._get_affine method at line 764 computes:

n = metadata[MetaKeys.SPATIAL_SHAPE][-1]
k1, k2, k3 = (t1n - sx) / (n - 1), (t2n - sy) / (n - 1), (t3n - sz) / (n - 1)

When n == 1 (single-slice 3D DICOM segmentation), n - 1 = 0 causes a ZeroDivisionError.

This occurs in the segmentation code path (_get_seg_data) at line 898, where lastImagePositionPatient is always set from the frame metadata regardless of the number of frames. For a single-frame segmentation, the first and last positions are identical, so t1n - sx = 0, t2n - sy = 0, t3n - sz = 0, and n - 1 = 0, resulting in 0 / 0.

Proposed Fix

Guard the lastImagePositionPatient computation in _get_affine with n > 1:

if "lastImagePositionPatient" in metadata and n > 1:

Affected Files

  • monai/data/image_reader.py (line 761)

Activity

  1. added a commit that references this issue on Jun 19, 2026
    7a85527
  2. added a commit that references this issue on Jun 29, 2026
    083f911
  3. added a commit that references this issue on Jul 5, 2026
    abbb47c
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