当前位置:   article > 正文

python打开文件_利用Python打开DICOM CT文件

pydicom 读取rtdose文件

fe88a3d0b4f2dee6d23811903a32678c.png

DICOM全称为Digital Imaging and Communications in Medicine,即医学数字成像和通信标准。本文中读取的CT图像就是使用DICOM标准存储的。其实不只CT图像,大部分临床影像都被存储为DICOM格式,如MR与PET图像。DICOM文件中除了包含有影像数据外,还囊括了大量机器,患者信息。这些信息被存储在一个个tags or attributes之下。Pydicom包为我们提供了非常简单易用的方法来读取这些文件。

1. 打开Jupyter notebook,导入需要的科学包

import 

2. 利用load_scan()和get_pixels_hu()读取CT文件

  1. def load_scan(path):
  2. temp = [pydicom.dcmread(path + f) for f in os.listdir(path)]
  3. slices = [t for t in temp if t.Modality == 'CT']
  4. slices.sort(key = lambda x: int(x.InstanceNumber))
  5. try:
  6. slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
  7. except:
  8. slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
  9. for s in slices:
  10. s.SliceThickness = slice_thickness
  11. return slices

pydicom.dcmread可以读取文件夹下所有文件dicom文件。这里的t.Modality用于取得该文件存贮数据所对应的成像模态。因为同一患者文件夹下可能包含RTstructure文件,RTplan文件,和RTdose文件。但这些文件并不包含影像数据。又或者是该患者文件夹下包含了MR和PET文件,那么在读取CT文件时,我们也不需要用到这些文件。所以t.Modality在此处用作判定条件。

slices.sort用于将CT图像按照成像顺序排列,解决文件读取过程中可能出现的CT图像乱序。

slices[0].ImagePositionPatient[2]返回当前CT图像的成像坐标,相邻两层之间的坐标差为层厚。

  1. def get_pixels_hu(scans):
  2. image = np.stack([s.pixel_array for s in scans])
  3. image = image.astype(np.int16)
  4. # Convert to Hounsfield units (HU)
  5. intercept = scans[0].RescaleIntercept
  6. slope = scans[0].RescaleSlope
  7. if slope != 1:
  8. image = slope * image.astype(np.float64)
  9. image = image.astype(np.int16)
  10. image += np.int16(intercept)
  11. return np.array(image, dtype=np.int16)

利用pydicom.dcmread读取CT文件后,s.pixel_array包含了该层图像的所有原始成像数据,为了得到HU值,需要利用scans[0].RescaleIntercept和scans[0].RescaleSlope进行转换。

3. 下面以读取HNSCC_01文件夹下的CT文件为例。关注“质子重离子放疗”微信公众号,后台回复“HNSCC01”获取CT文件。

  1. # open CT_lung dataset
  2. dir_path_ct = './Data/HNSCC_01/'
  3. patient_ct = load_scan(dir_path_ct)
  4. imgs_ct = get_pixels_hu(patient_ct)
  5. # For "NotImplementedError: this transfer syntax JPEG 2000 Image Compression,
  6. # can not be read because Pillow lacks the jpeg 2000 decoder plugin"
  7. # https://pydicom.github.io/pydicom/stable/tutorials/installation.html#installing-pillow

如果出现上述NotImplementedError,请先卸载pillow包,然后按照《Python及图像处理相关包安装》中相关步骤,先安装openjpeg,再安装pillow。

4. 利用matplotlib.pyplot绘制第十层CT图像

  1. # display one selected slice
  2. plt.figure(figsize=(10, 10))
  3. plt.title('CT Slice_10')
  4. plt.imshow(imgs_ct[9],cmap='gray')
  5. plt.axis('off')
  6. plt.show()

142cfb30acfeec7d39cfe948aad82f47.png

看完本文有收获?请分享给更多人

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/165509
推荐阅读
相关标签
  

闽ICP备14008679号