From 7a85527f1c993a44404b2cc97057465236b98898 Mon Sep 17 00:00:00 2001 From: rtmalikian Date: Thu, 18 Jun 2026 17:28:58 -0700 Subject: [PATCH] fix: guard division by zero in DICOMReader._get_affine for single-slice volumes When n=1 (single-slice 3D DICOM segmentation), (n-1) is zero causing ZeroDivisionError in the direction vector computation for the z-axis. This happens in the segmentation code path where lastImagePositionPatient is always set regardless of the number of frames. Fix: add n > 1 guard before computing z-axis direction from lastImagePositionPatient. For single-slice volumes, the z-axis column remains as the identity [0, 0, 1, 0] from np.eye(4). Fixes #8925 Signed-off-by: Raphael Malikian --- monai/data/image_reader.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/monai/data/image_reader.py b/monai/data/image_reader.py index a85eb95c20..6859dca62f 100644 --- a/monai/data/image_reader.py +++ b/monai/data/image_reader.py @@ -761,10 +761,10 @@ def _get_affine(self, metadata: dict, lps_to_ras: bool = True): if "lastImagePositionPatient" in metadata: t1n, t2n, t3n = metadata["lastImagePositionPatient"] n = metadata[MetaKeys.SPATIAL_SHAPE][-1] - k1, k2, k3 = (t1n - sx) / (n - 1), (t2n - sy) / (n - 1), (t3n - sz) / (n - 1) - affine[0, 2] = k1 - affine[1, 2] = k2 - affine[2, 2] = k3 + if n > 1: + affine[0, 2] = (t1n - sx) / (n - 1) + affine[1, 2] = (t2n - sy) / (n - 1) + affine[2, 2] = (t3n - sz) / (n - 1) if lps_to_ras: affine = orientation_ras_lps(affine)