Skip to content

Fix DICOMSeriesToVolumeOperator casting bug #529

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 3 commits into from
Apr 22, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions monai/deploy/operators/dicom_series_to_volume_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ def generate_voxel_data(self, series):
# with the NumPy array returned from the ITK GetArrayViewFromImage on the image
# loaded from the same DICOM series.
vol_data = np.stack([s.get_pixel_array() for s in slices], axis=0)
vol_data = vol_data.astype(np.int16)
if slices[0][0x0028,0x0103].value == 1:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

value 0 is for unsigned integer.

vol_data = vol_data.astype(np.uint16)

# For now we support monochrome image only, for which DICOM Photometric Interpretation
# (0028,0004) has defined terms, MONOCHROME1 and MONOCHROME2, with the former being:
Expand Down Expand Up @@ -154,11 +155,29 @@ def generate_voxel_data(self, series):
except KeyError:
slope = 1


# check if vol_data, intercept, and slope can be cast to uint16 without data loss
if np.can_cast(vol_data, np.uint16, casting='safe') and np.can_cast(intercept, np.uint16, casting='safe') and np.can_cast(slope, np.uint16, casting='safe'):
logging.info(f"Casting to uint16")
vol_data = np.array(vol_data, dtype=np.uint16)
intercept = np.uint16(intercept)
slope = np.uint16(slope)
elif np.can_cast(vol_data, np.float32, casting='safe') and np.can_cast(intercept, np.float32, casting='safe') and np.can_cast(slope, np.float32, casting='safe'):
logging.info(f"Casting to float32")
vol_data = np.array(vol_data, dtype=np.float32)
intercept = np.float32(intercept)
slope = np.float32(slope)
elif np.can_cast(vol_data, np.float64, casting='safe') and np.can_cast(intercept, np.float64, casting='safe') and np.can_cast(slope, np.float64, casting='safe'):
logging.info(f"Casting to float64")
vol_data = np.array(vol_data, dtype=np.float64)
intercept = np.float64(intercept)
slope = np.float64(slope)

if slope != 1:
vol_data = slope * vol_data.astype(np.float64)
vol_data = vol_data.astype(np.int16)
vol_data += np.int16(intercept)
return np.array(vol_data, dtype=np.int16)
vol_data = slope * vol_data

vol_data += intercept
return vol_data

def create_volumetric_image(self, vox_data, metadata):
"""Creates an instance of 3D image.
Expand Down