Skip to content

Instantly share code, notes, and snippets.

@jizhang02
Created November 16, 2022 11:00
Show Gist options
  • Save jizhang02/6e395880c085f7c9884d9cec5490c710 to your computer and use it in GitHub Desktop.
Save jizhang02/6e395880c085f7c9884d9cec5490c710 to your computer and use it in GitHub Desktop.
convert dicom files into mhd file
'''
-----------------------------------------------
File Name: convert_dcm_to_mhd$
Description: convert dicom files into mhd file
Author: Jing$
Date: 16/11/2022$
-----------------------------------------------
'''
import os
import SimpleITK as sitk
import pydicom
import numpy as np
import glob
def convert(input_path,output_path):
'''
Procedure:
# To get first image as refenece image, supposed all images have same dimensions
# To get Dimensions, 3D spacing, image origin
# To make numpy array
# loop through all the DICOM files
# To read the dicom file
# store the raw image data
:param input_path: the path of dicom files
:param output_path: the output path of mhd files
:return: null
'''
DICOM_directory = glob.glob(input_path)
Image = pydicom.read_file(DICOM_directory[0])
Dimension = (int(Image.Rows), int(Image.Columns), len(DICOM_directory))
Spacing = (float(Image.PixelSpacing[0]), float(Image.PixelSpacing[1]), float(Image.SliceThickness))
Origin = Image.ImagePositionPatient
NpArrDc = np.zeros(Dimension, dtype=Image.pixel_array.dtype)
for filename in DICOM_directory:
df = pydicom.read_file(filename)
NpArrDc[:, :, DICOM_directory.index(filename)] = df.pixel_array
NpArrDc = np.transpose(NpArrDc, (2, 0, 1)) # axis transpose
sitk_img = sitk.GetImageFromArray(NpArrDc, isVector=False)
sitk_img.SetSpacing(Spacing)
sitk_img.SetOrigin(Origin)
sitk.WriteImage(sitk_img, os.path.join(output_path + ".mhd"))
return
convert(input_path="dicoms/*.dcm",output_path="samples/sample")
@jizhang02
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment