Skip to content

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

@rtmalikian

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions