XYU

Engineering Cybernetics.                    

Several Approaches to Load Medical Images

03 Jun 2019 » Vision

DICOM

Way 1:

import pydicom
dcm = pydicom.dcmread('xxx.dcm')
data = dcm.pixel_array

Way 2:

import os
import cv2
import pydicom
import SimpleITK as sitk
#路径不可包含中文
path = '.'
reader = sitk.ImageSeriesReader()
# dicom文件的顺序不是由其文件名决定的,而是由seriesIDs决定
seriesIDs = reader.GetGDCMSeriesIDs(path) 
# 读取seriesIDs相同的dicom文件的顺序
dicom_names = reader.GetGDCMSeriesFileNames(path, seriesIDs[0])

reader.SetFileNames(dicom_names)
image = reader.Execute()
image_array = sitk.GetArrayFromImage(image)

NII

import nibabel as nib 
img = nib.load('xxx.nii')
data = img.get_fdata()

# 读取scaling信息:
header = img.header
header.get_slope_inter()
# 或
header['scl_inter']
header['scl_slope']

MHD

Way 1:

import skimage.io as io
img = io.imread('xxx.mhd', plugin='simpleitk')
data = img

Way 2:

import SimpleITK as sitk
import numpy as np
'''
This funciton reads a '.mhd' file using SimpleITK and return the image array, origin and spacing of the image.
'''

def load_itk(filename):
    # Reads the image using SimpleITK
    itkimage = sitk.ReadImage(filename)

    # Convert the image to a  numpy array first and then shuffle the dimensions to get axis in the order z,y,x
    ct_scan = sitk.GetArrayFromImage(itkimage)

    # Read the origin of the ct_scan, will be used to convert the coordinates from world to voxel and vice versa.
    origin = np.array(list(reversed(itkimage.GetOrigin())))

    # Read the spacing along each dimension
    spacing = np.array(list(reversed(itkimage.GetSpacing())))

    return ct_scan, origin, spacing

References:
[1] https://nipy.org/nibabel/nifti_images.html#data-scaling
[2] https://stackoverflow.com/a/42594949

© 2019 XYU.