We start with the imports:
import dicom
import os
import numpy
The
pydicompackage can be installed throughpipand can be found in https://pypi.python.org/pypi/pydicom/
Populate a lstFilesDCM with the filenames of the DICOM files under a given PathDicom directory:
PathDicom = "./dir_with_dicom_series/"
lstFilesDCM = [] # create an empty list
for dirName, subdirList, fileList in os.walk(PathDicom):
for filename in fileList:
if ".dcm" in filename.lower(): # check whether the file's DICOM
lstFilesDCM.append(os.path.join(dirName,filename))
Use the first of the DICOM files to read in some of the metadata, specifically the image dimensions, the pixel-spacing, and the slice-thickness:
# Get ref file
RefDs = dicom.read_file(lstFilesDCM[0])
# Load dimensions based on the number of rows, columns, and slices (along the Z axis)
ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM))
# Load spacing values (in mm)
ConstPixelSpacing = (float(RefDs.PixelSpacing[0]), float(RefDs.PixelSpacing[1]), float(RefDs.SliceThickness))
Load all the pixel data into an appropriate sized NumPy array named ArrayDicom:
# The array is sized based on 'ConstPixelDims'
ArrayDicom = numpy.zeros(ConstPixelDims, dtype=RefDs.pixel_array.dtype)
# loop through all the DICOM files
for filenameDCM in lstFilesDCM:
# read the file
ds = dicom.read_file(filenameDCM)
# store the raw image data
ArrayDicom[:, :, lstFilesDCM.index(filenameDCM)] = ds.pixel_array
The entire code can be seen in the accompanying .py file
The script is apparently made to work if you have a directory containing only CT images. If you have different kinds of DICOM files in the directory, you could either make sure that you remove all files not CT or you could add the following lines to your code (starting from line 13):
Then only the CT images will be added to your list.
EDIT: It may not be ONLY CT. Could also be for example MRI images. Then you should use:
if ds.SOPClassUID == '1.2.840.10008.5.1.4.1.1.4': # MRI images
More info on SOPClaissUID here