import os
import pydicom
import nibabel as nib
import numpy as np
from glob import glob
from pydicom.pixel_data_handlers.util import apply_voi_lut
def dicom_to_nifti(dicom_dir, nifti_path):
dicom_files = glob(os.path.join(dicom_dir, '*.dcm'))
dicom_files.sort()
if not dicom_files:
return False
first_dicom = pydicom.dcmread(dicom_files[0])
pixel_array = apply_voi_lut(first_dicom.pixel_array, first_dicom)
slices = [pydicom.dcmread(f) for f in dicom_files]
slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
pixel_spacing = first_dicom.PixelSpacing
slice_thickness = first_dicom.SliceThickness
image_shape = list(pixel_array.shape) + [len(slices)]
image_3d = np.zeros(image_shape, dtype=pixel_array.dtype)
for i, s in enumerate(slices):
image_3d[:, :, i] = apply_voi_lut(s.pixel_array, s)
nifti_image = nib.Nifti1Image(image_3d, np.eye(4))
nifti_image.header['pixdim'][1:4] = [pixel_spacing[0], pixel_spacing[1], slice_thickness]
nib.save(nifti_image, nifti_path)
return True
def main(input_dir, output_dir):
for root, dirs, files in os.walk(input_dir):
if files:
path_parts = root.split(os.sep)
if len(path_parts) >= 4:
patient_id = path_parts[-3]
image_id = path_parts[-1]
output_filename = f"{patient_id}-{image_id}.nii.gz"
output_path = os.path.join(output_dir, output_filename)
if dicom_to_nifti(root, output_path):
print(f"Converted {root} to {output_path}")
else:
print(f"Failed to convert {root}")
else:
print(f"Skipping {root}: Not enough path levels")
if __name__ == "__main__":
input_directory = "D:\\your\input\folder"
output_directory = "D:\\your\output\folder"
if not os.path.exists(output_directory):
os.makedirs(output_directory)
main(input_directory, output_directory)
02-25
9424
06-27
1万+
12-28
802
06-18
1521